diff --git a/pool/shard001/C++/0022207_NstBrdCtc65.cpp b/pool/shard001/C++/0022207_NstBrdCtc65.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2af3cb49f0860e506bf1342ff6edadafeea3da53 --- /dev/null +++ b/pool/shard001/C++/0022207_NstBrdCtc65.cpp @@ -0,0 +1,117 @@ +//////////////////////////////////////////////////////////////////////////////////////// +// +// Nestopia - NES/Famicom emulator written in C++ +// +// Copyright (C) 2003-2007 Martin Freij +// +// This file is part of Nestopia. +// +// Nestopia 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. +// +// Nestopia 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 Nestopia; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +//////////////////////////////////////////////////////////////////////////////////////// + +#include "../NstMapper.hpp" +#include "NstBrdCtc65.hpp" + +namespace Nes +{ + namespace Core + { + namespace Boards + { + #ifdef NST_MSVC_OPTIMIZE + #pragma optimize("s", on) + #endif + + void Ctc65::SubReset(bool) + { + for (dword i=0x8000; i <= 0xFFFF; i += 0x2) + { + Map( i + 0x0, &Ctc65::Peek_Prg, &Ctc65::Poke_8000 ); + Map( i + 0x1, &Ctc65::Peek_Prg, &Ctc65::Poke_8001 ); + } + + regs[0] = 0; + regs[1] = 0; + + UpdatePrg(); + } + + void Ctc65::SubSave(State::Saver& state) const + { + const byte data[2] = {regs[0],regs[1]}; + state.Begin( AsciiId<'R','E','G'>::V ).Write( data ).End(); + } + + void Ctc65::SubLoad(State::Loader& state) + { + while (const dword chunk = state.Begin()) + { + if (chunk == AsciiId<'R','E','G'>::V) + { + State::Loader::Data<2> data( state ); + + regs[0] = data[0]; + regs[1] = data[1]; + + UpdatePrg(); + } + + state.End(); + } + } + + #ifdef NST_MSVC_OPTIMIZE + #pragma optimize("", on) + #endif + + void Ctc65::UpdatePrg() + { + const uint chip = (regs[1] << 5 & 0x20) << (regs[0] >> 7); + openBus = chip < (regs[0] >> 7); + + prg.SwapBanks + ( + chip | (regs[0] & 0x1E) | (regs[0] >> 5 & regs[0]), + chip | (regs[0] & 0x1F) | (~regs[0] >> 5 & 0x01) + ); + } + + NES_POKE_D(Ctc65,8000) + { + if (regs[0] != data) + { + regs[0] = data; + UpdatePrg(); + ppu.SetMirroring( (data & 0x40) ? Ppu::NMT_VERTICAL : Ppu::NMT_HORIZONTAL ); + } + } + + NES_POKE_D(Ctc65,8001) + { + if (regs[1] != data) + { + regs[1] = data; + UpdatePrg(); + } + } + + NES_PEEK_A(Ctc65,Prg) + { + return !openBus ? prg.Peek( address - 0x8000 ) : (address >> 8); + } + } + } +} diff --git a/pool/shard001/C++/0022217_flip.cpp b/pool/shard001/C++/0022217_flip.cpp new file mode 100644 index 0000000000000000000000000000000000000000..50923435c5c41c6d4a00f2b167f88d6b57ccdd29 --- /dev/null +++ b/pool/shard001/C++/0022217_flip.cpp @@ -0,0 +1,32 @@ +/** + * @file flip.cpp + * @brief mex interface for cv::flip + * @ingroup core + * @author Amro + * @date 2015 + */ +#include "mexopencv.hpp" +using namespace std; +using namespace cv; + +/** + * Main entry called from Matlab + * @param nlhs number of left-hand-side arguments + * @param plhs pointers to mxArrays in the left-hand-side + * @param nrhs number of right-hand-side arguments + * @param prhs pointers to mxArrays in the right-hand-side + */ +void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) +{ + // Check the number of arguments + nargchk(nrhs==2 && nlhs<=1); + + // Argument vector + vector rhs(prhs, prhs+nrhs); + + // Process + Mat src(rhs[0].toMat()), dst; + int flipCode = rhs[1].toInt(); + flip(src, dst, flipCode); + plhs[0] = MxArray(dst); +} diff --git a/pool/shard001/C++/0022220_FCActor.cpp b/pool/shard001/C++/0022220_FCActor.cpp new file mode 100644 index 0000000000000000000000000000000000000000..14785780ecc89924273178881f7c456fab90e882 --- /dev/null +++ b/pool/shard001/C++/0022220_FCActor.cpp @@ -0,0 +1,165 @@ +/* + Copyright (C) 2011-2012 by Martin Linklater + + 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 "FCActor.h" + +FCActor::FCActor() +{ +} + +FCActor::~FCActor() +{ + FCPhysics::Instance()->TwoD()->DestroyBody(m_physicsBody); +} + +void FCActor::Init( FCXMLNode xml, + FCXMLNode bodyXML, + FCXMLNode modelXML, + FCResourceRef res, + std::string name, + FCHandle handle) +{ + m_createXML = xml; + m_id = FCXML::StringValueForNodeAttribute(m_createXML, kFCKeyId); + m_handle = handle; + + // hardwired to 2D for now 8) + + if (bodyXML) + { + FCPhysics2DBodyDefRef bodyDef = FCPhysics2DBodyDefRef( new FCPhysics2DBodyDef ); + + FCVector2f pos; + pos.Zero(); + + pos.x += FCXML::FloatValueForNodeAttribute(m_createXML, kFCKeyOffsetX); + pos.y += FCXML::FloatValueForNodeAttribute(m_createXML, kFCKeyOffsetY); + + bodyDef->position = pos; + + bodyDef->angle = FCXML::FloatValueForNodeAttribute(m_createXML, kFCKeyRotation); + + if( FCXML::BoolValueForNodeAttribute(m_createXML, kFCKeyDynamic) ) + bodyDef->isStatic = false; + else + bodyDef->isStatic = true; + + bodyDef->canSleep = false; + bodyDef->shapeXML = bodyXML; + + if (name.size()) { + m_physicsBody = FCPhysics::Instance()->TwoD()->CreateBody(bodyDef, name, handle); + } + else { + m_physicsBody = FCPhysics::Instance()->TwoD()->CreateBody(bodyDef, "", handle); + } + } + + // now create a model + if (modelXML) + { + m_model = plt_FCModel_Create(); + m_model->InitWithModel(modelXML, res); + } + else + { + if (bodyXML) + { + // physics but no model so build a physics mode + + m_model = plt_FCModel_Create(); + FCColor4f* pColor = (FCColor4f*)res->UserData(); + if( pColor ) + m_model->InitWithPhysics(bodyXML, *pColor); + else { + FCColor4f grey(0.5f, 0.5f, 0.5f, 1.0f ); + m_model->InitWithPhysics(bodyXML, grey); + } + } + } +} + +void FCActor::SetPosition(FCVector3f pos) +{ + m_physicsBody->SetPosition(pos); +} + +FCVector3f FCActor::Position() const +{ + return m_physicsBody->Position(); +} + +void FCActor::SetLinearVelocity(FCVector3f vel) +{ + m_physicsBody->SetLinearVelocity(vel); +} + +FCVector3f FCActor::LinearVelocity() const +{ + return m_physicsBody->LinearVelocity(); +} + +void FCActor::SetDebugModelColor(FCColor4f color) +{ + m_model->SetDebugMeshColor(color); +} + +void FCActor::ApplyImpulseAtWorldPos(FCVector3f impulse, FCVector3f pos) +{ + m_physicsBody->ApplyImpulseAtWorldPos(impulse, pos); +} + +void FCActor::Update(float realTime, float gameTime) +{ + if( m_physicsBody ) + { + FCVector3f pos = m_physicsBody->Position(); + float rot = m_physicsBody->Rotation(); + + if( m_model ) + { + m_model->SetRotation(rot); + m_model->SetPosition(pos); + } + } +} + +bool FCActor::NeedsUpdate() +{ + return false; +} + +bool FCActor::NeedsRender() +{ + return false; +} + +bool FCActor::RespondsToTapGesture() +{ + return false; +} + +FCModelRefVec FCActor::RenderGather() +{ + FCModelRefVec ret; + return ret; +} diff --git a/pool/shard001/C++/0022221_configuration.cc b/pool/shard001/C++/0022221_configuration.cc new file mode 100644 index 0000000000000000000000000000000000000000..6645dc0b332350c9b0fa508e8a3e326be7f572e6 --- /dev/null +++ b/pool/shard001/C++/0022221_configuration.cc @@ -0,0 +1,54 @@ +/** + * @file configuration.cc + * @author Krzysztof Trzepla + * @copyright (C) 2016 ACK CYFRONET AGH + * @copyright This software is released under the MIT license cited in + * 'LICENSE.txt' + */ + +#include "configuration.h" + +#include + +namespace one { +namespace messages { + +Configuration::Configuration( + std::unique_ptr serverMessage) +{ + auto *configurationMsg = serverMessage->mutable_configuration(); + + m_rootUuid = configurationMsg->root_uuid(); + + auto *subscriptions = configurationMsg->mutable_subscriptions(); + std::transform(subscriptions->pointer_begin(), subscriptions->pointer_end(), + std::back_inserter(m_subscriptions), + [](auto subscription) { return std::move(*subscription); }); + + auto *disabledSpaces = configurationMsg->mutable_disabled_spaces(); + std::transform(disabledSpaces->pointer_begin(), + disabledSpaces->pointer_end(), std::back_inserter(m_disabledSpaces), + [](auto disabled_space) { return std::move(*disabled_space); }); +} + +const folly::fbstring &Configuration::rootUuid() const { return m_rootUuid; } + +const std::vector &Configuration::subscriptions() const +{ + return m_subscriptions; +} + +const std::vector &Configuration::disabledSpaces() const +{ + return m_disabledSpaces; +} + +std::string Configuration::toString() const +{ + std::stringstream stream; + stream << "type: 'Configuration', root UUID: '" << m_rootUuid << "'"; + return stream.str(); +} + +} // namespace messages +} // namespace one diff --git a/pool/shard001/C++/0022226_TexturesMap.cpp b/pool/shard001/C++/0022226_TexturesMap.cpp new file mode 100644 index 0000000000000000000000000000000000000000..05e0dd813cbdff26b1a81a3726b89bad0f92ac42 --- /dev/null +++ b/pool/shard001/C++/0022226_TexturesMap.cpp @@ -0,0 +1,119 @@ +/* + Copyright (C) 1999-2006 Id Software, Inc. and contributors. + For a list of contributors, see the accompanying CONTRIBUTORS file. + + This file is part of GtkRadiant. + + GtkRadiant 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. + + GtkRadiant 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 GtkRadiant; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include "TexturesMap.h" +#include "texturelib.h" + +#include "../image.h" // QERApp_LoadImage + +TexturesMap::TextureConstructor::TextureConstructor (TexturesMap* cache) : + m_cache(cache) +{ +} + +GLTexture* TexturesMap::TextureConstructor::construct (const TextureKey& key) +{ + GLTexture* texture = new GLTexture(key.first, key.second); + if (m_cache->realised()) { + texture->realise(); + } + return texture; +} + +void TexturesMap::TextureConstructor::destroy (GLTexture* texture) +{ + if (m_cache->realised()) { + texture->unrealise(); + } + delete texture; +} + +TexturesMap::TexturesMap () : + m_qtextures(TextureConstructor(this)), m_observer(0), m_unrealised(1) +{ +} + +LoadImageCallback TexturesMap::defaultLoader () const +{ + return LoadImageCallback(0, QERApp_LoadImage); +} + +GLTexture* TexturesMap::capture (const std::string& name) +{ + return capture(defaultLoader(), name); +} + +GLTexture* TexturesMap::capture (const LoadImageCallback& loader, const std::string& name) +{ + g_debug("textures capture: '%s'\n", name.c_str()); + return m_qtextures.capture(TextureKey(loader, name)).get(); +} + +void TexturesMap::release (GLTexture* texture) +{ + g_debug("textures release: '%s'\n", texture->getName().c_str()); + m_qtextures.release(TextureKey(texture->load, texture->getName())); +} + +void TexturesMap::attach (TexturesCacheObserver& observer) +{ + ASSERT_MESSAGE(m_observer == 0, "TexturesMap::attach: cannot attach observer"); + m_observer = &observer; +} + +void TexturesMap::detach (TexturesCacheObserver& observer) +{ + ASSERT_MESSAGE(m_observer == &observer, "TexturesMap::detach: cannot detach observer"); + m_observer = 0; +} + +void TexturesMap::realise () +{ + if (--m_unrealised == 0) { + for (TextureCache::iterator i = m_qtextures.begin(); i != m_qtextures.end(); ++i) { + if (!(*i).value.empty()) { + (*(*i).value).realise(); + } + } + if (m_observer != 0) { + m_observer->realise(); + } + } +} + +void TexturesMap::unrealise () +{ + if (++m_unrealised == 1) { + if (m_observer != 0) { + m_observer->unrealise(); + } + for (TextureCache::iterator i = m_qtextures.begin(); i != m_qtextures.end(); ++i) { + if (!(*i).value.empty()) { + (*(*i).value).unrealise(); + } + } + } +} + +bool TexturesMap::realised () +{ + return m_unrealised == 0; +} diff --git a/pool/shard001/C++/0022241_brainfuck-jit.cpp b/pool/shard001/C++/0022241_brainfuck-jit.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a0dd370948f3b2d09ddcb1297d414c6d55f01f9b --- /dev/null +++ b/pool/shard001/C++/0022241_brainfuck-jit.cpp @@ -0,0 +1,289 @@ +#include +#include +#include + +#include +#include + +#include "brainfuck.h" + +// Wraps an mmap()ed area, which starts with read/write permissions, +// but that can be later turned into read/exec before execution. +// This is good practice since the pages are never writable AND executable +// _at the same_time_ +// (See https://eli.thegreenplace.net/2013/11/05/how-to-jit-an-introduction) +class ExecutableBuffer +{ +private: + uint8_t *buf_, + *ptr_; + size_t size_; + +public: + ExecutableBuffer(size_t size) { + size_ = size; + buf_ = (uint8_t*) mmap( + 0, + size_, + PROT_READ | PROT_WRITE, + MAP_PRIVATE | MAP_ANONYMOUS, + -1, + 0 + ); + if (buf_ == MAP_FAILED) { + perror("mmap"); + exit(1); + } + ptr_ = buf_; + memset(ptr_, 0x00, size); + } + + ~ExecutableBuffer() { + if(munmap(buf_, size_) == -1) { + perror("munmap"); + exit(1); + } + } + + void make_executable() { + if (mprotect(buf_, size_, PROT_READ | PROT_EXEC) == -1) { + perror("mprotect"); + exit(1); + } + } + + uint8_t* get_base () const { return buf_; } + uint8_t* get_ptr () const { return ptr_; } + void set_ptr (uint8_t* ptr) { ptr_ = ptr; } + + void writeb(uint8_t byte) { + // write a single byte + (*ptr_++) = byte; + } + + void writel(uint32_t value) { + // write a 4-bytes word, keeping endianness + writes((uint8_t*)&value, 4); + } + + void writes(const uint8_t* bytes, uint32_t size) { + // write an arbitrary-length series of bytes + memcpy(ptr_, bytes, size); + ptr_ += size; + } +}; + +class JITProgram +{ +private: + ExecutableBuffer &buf_; + +public: + JITProgram(ExecutableBuffer &buf) + : buf_(buf) {} + + ExecutableBuffer& buffer() {return buf_;} + + void start() { + // 0000000000000070 break: + // 70: cc int3 + // buf_.writeb(0xcc); + } + + void finish() { + // 0000000000000071 finish: + // 71: c3 retq + buf_.writeb(0xc3); + } + + void run() { + uint32_t memory[30000]; + memset(memory, 0x00, sizeof(memory)); + + // Set the buffer as executable before attempting to jump + // into it: + buf_.make_executable(); + + // Capture the buffer base ptr: + uint8_t* _base = buf_.get_base(); + + // Inject the address of the working memory in the rdi reg: + asm("movq %0, %%rdi\n": + : "r"(&memory) + : "%rdi"); + + // Cast the base as a func pointer and jump to it: + ((void (*)()) _base)(); + } +}; + +class JITCompiler : public ExpressionVisitor +{ +private: + JITProgram &program_; + ExecutableBuffer &buffer_; + +public: + JITCompiler(JITProgram &program) + : program_(program), + buffer_(program_.buffer()) {} + + virtual void visit(const Increment& inc) { + // 0000000000000000 increment: + // 0: 48 c7 c0 01 00 00 00 movq $1, %rax + // 7: 01 07 addl %eax, (%rdi) + buffer_.writes((uint8_t*)"\x48\xc7\xc0", 3); + buffer_.writel(inc.offset()); + buffer_.writes((uint8_t*)"\x01\x07", 2); + } + + virtual void visit(const Decrement& dec) { + // 0000000000000009 decrement: + // 9: 48 c7 c0 01 00 00 00 movq $1, %rax + // 10: 29 07 subl %eax, (%rdi) + buffer_.writes((uint8_t*)"\x48\xc7\xc0", 3); + buffer_.writel(dec.offset()); + buffer_.writes((uint8_t*)"\x29\x07", 2); + } + + virtual void visit(const Forward& fwd) { + // 0000000000000012 forward: + // 12: 48 c7 c0 01 00 00 00 movq $1, %rax + // 19: 48 01 c7 addq %rax, %rdi + buffer_.writes((uint8_t*)"\x48\xc7\xc0", 3); + buffer_.writel(fwd.offset()*4); + buffer_.writes((uint8_t*)"\x48\x01\xc7", 3); + } + + virtual void visit(const Backward& bwd) { + // 000000000000001c backward: + // 1c: 48 c7 c0 01 00 00 00 movq $1, %rax + // 23: 48 29 c7 subq %rax, %rdi + buffer_.writes((uint8_t*)"\x48\xc7\xc0", 3); + buffer_.writel(bwd.offset()*4); + buffer_.writes((uint8_t*)"\x48\x29\xc7", 3); + } + + virtual void visit(const Input&) { + // 0000000000000026 read: + // 26: 57 pushq %rdi + // 27: 48 c7 c0 03 00 00 02 movq $33554435, %rax + // 2e: 48 89 fe movq %rdi, %rsi + // 31: 48 c7 c7 00 00 00 00 movq $0, %rdi + // 38: 48 c7 c2 01 00 00 00 movq $1, %rdx + // 3f: 0f 05 syscall + // 41: 5f popq %rdi + + buffer_.writeb(0x57); + buffer_.writes((uint8_t*)"\x48\xc7\xc0", 3); + buffer_.writel(0x02000003); + buffer_.writes((uint8_t*)"\x48\x89\xfe", 3); + buffer_.writes((uint8_t*)"\x48\xc7\xc7\x00\x00\x00\x00", 7); + buffer_.writes((uint8_t*)"\x48\xc7\xc2\x01\x00\x00\x00", 7); + buffer_.writes((uint8_t*)"\x0f\x05", 2); + buffer_.writeb(0x5f); + } + + virtual void visit(const Output&) { + // 0000000000000042 write: + // 42: 57 pushq %rdi + // 43: 48 c7 c0 04 00 00 02 movq $33554436, %rax + // 4a: 48 89 fe movq %rdi, %rsi + // 4d: 48 c7 c7 01 00 00 00 movq $1, %rdi + // 54: 48 c7 c2 01 00 00 00 movq $1, %rdx + // 5b: 0f 05 syscall + // 5d: 5f popq %rdi + + buffer_.writeb(0x57); + buffer_.writes((uint8_t*)"\x48\xc7\xc0", 3); + buffer_.writel(0x02000004); + buffer_.writes((uint8_t*)"\x48\x89\xfe", 3); + buffer_.writes((uint8_t*)"\x48\xc7\xc7\x01\x00\x00\x00", 7); + buffer_.writes((uint8_t*)"\x48\xc7\xc2\x01\x00\x00\x00", 7); + buffer_.writes((uint8_t*)"\x0f\x05", 2); + buffer_.writeb(0x5f); + } + + virtual void visit(const Loop& loop) { + // 000000000000005e loop_start: + // 5e: 83 3f 00 cmpl $0, (%rdi) + // 61: 0f 84 00 00 00 00 je 0 + buffer_.writes((uint8_t*)"\x83\x3f\x00", 3); + buffer_.writes((uint8_t*)"\x0f\x84", 2); + buffer_.writel(0); // reserve 4 bytes + + // Save current position: + uint8_t *after_loop_start = buffer_.get_ptr(); + + // Recurse into subexpressions: + for(const auto &child: loop.children()) { + child->accept(*this); + } + + // 0000000000000067 loop_end: + // 67: 83 3f 00 cmpl $0, (%rdi) + // 6a: 0f 85 00 00 00 00 jne 0 + buffer_.writes((uint8_t*)"\x83\x3f\x00", 3); + buffer_.writes((uint8_t*)"\x0f\x85", 2); + // Calculate how much to jump back (consider the 4 bytes + // of the operand itself): + uint32_t jump_back = after_loop_start - buffer_.get_ptr() - 4; + // Append the distance to the jump: + buffer_.writel(jump_back); + + // Now calculate how much to jump forward in case we want + // to skip the loop, to fill the pending jump: + uint8_t *after_loop_end = buffer_.get_ptr(); + uint32_t jump_fwd = after_loop_end - after_loop_start; + + // Go back to the original position (-4), fill the pending + // jump distance and get back to the the current pos: + buffer_.set_ptr(after_loop_start - 4); + buffer_.writel(jump_fwd); + buffer_.set_ptr(after_loop_end); + } + + void compile(const ExpressionVector& expressions) { + program_.start(); + + for(const auto &expression: expressions) { + expression->accept(*this); + } + + program_.finish(); + } +}; + +int main(int argc, char *argv[]) { + std::ifstream ifs(argv[1]); + + if (!ifs) { + std::cerr << "Invalid filename!" << std::endl; + return 1; + } + + std::vector program; + + std::copy( + (std::istreambuf_iterator(ifs)), + (std::istreambuf_iterator()), + std::back_inserter(program) + ); + + try { + auto expressions = Parser().parse(program); + + ExecutableBuffer buffer(1000000); + JITProgram jit_program(buffer); + JITCompiler compiler(jit_program); + + compiler.compile(expressions); + + jit_program.run(); + + } catch (std::exception& e) { + std::cerr << "Error: " << e.what() << std::endl; + } + + return 0; +} diff --git a/pool/shard001/C++/0022242_GetSendStatisticsResult.cpp b/pool/shard001/C++/0022242_GetSendStatisticsResult.cpp new file mode 100644 index 0000000000000000000000000000000000000000..22456e5371a55d3b7ef7e4b8bce198aa3d528c08 --- /dev/null +++ b/pool/shard001/C++/0022242_GetSendStatisticsResult.cpp @@ -0,0 +1,68 @@ +/* +* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"). +* You may not use this file except in compliance with the License. +* A copy of the License is located at +* +* http://aws.amazon.com/apache2.0 +* +* or in the "license" file accompanying this file. This file is distributed +* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +* express or implied. See the License for the specific language governing +* permissions and limitations under the License. +*/ +#include +#include +#include +#include +#include + +#include + +using namespace Aws::SES::Model; +using namespace Aws::Utils::Xml; +using namespace Aws::Utils::Logging; +using namespace Aws::Utils; +using namespace Aws; + +GetSendStatisticsResult::GetSendStatisticsResult() +{ +} + +GetSendStatisticsResult::GetSendStatisticsResult(const AmazonWebServiceResult& result) +{ + *this = result; +} + +GetSendStatisticsResult& GetSendStatisticsResult::operator =(const AmazonWebServiceResult& result) +{ + const XmlDocument& xmlDocument = result.GetPayload(); + XmlNode rootNode = xmlDocument.GetRootElement(); + XmlNode resultNode = rootNode; + if (rootNode.GetName() != "GetSendStatisticsResult") + { + resultNode = rootNode.FirstChild("GetSendStatisticsResult"); + } + + if(!resultNode.IsNull()) + { + XmlNode sendDataPointsNode = resultNode.FirstChild("SendDataPoints"); + if(!sendDataPointsNode.IsNull()) + { + XmlNode sendDataPointsMember = sendDataPointsNode.FirstChild("member"); + while(!sendDataPointsMember.IsNull()) + { + m_sendDataPoints.push_back(sendDataPointsMember); + sendDataPointsMember = sendDataPointsMember.NextNode("member"); + } + + } + } + + XmlNode responseMetadataNode = rootNode.FirstChild("ResponseMetadata"); + m_responseMetadata = responseMetadataNode; + AWS_LOGSTREAM_DEBUG("Aws::SES::Model::GetSendStatisticsResult", "x-amzn-request-id: " << m_responseMetadata.GetRequestId() ); + + return *this; +} diff --git a/pool/shard001/C++/0022257_predefinedsetmodel.cpp b/pool/shard001/C++/0022257_predefinedsetmodel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0995c5de36d03a692450e1f05651055bc75f0da3 --- /dev/null +++ b/pool/shard001/C++/0022257_predefinedsetmodel.cpp @@ -0,0 +1,63 @@ +/* + +Pencil2D - Traditional Animation Software +Copyright (C) 2005-2007 Patrick Corrieri & Pascal Naidon +Copyright (C) 2012-2020 Matthew Chiawen Chang + +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. + +*/ +// PredefinedSetModel.cpp +#include "predefinedsetmodel.h" + +PredefinedSetModel::PredefinedSetModel(QObject *parent, const PredefinedKeySet& mKeySet) + :QAbstractTableModel(parent), mKeySet(mKeySet) +{ +} + +int PredefinedSetModel::rowCount(const QModelIndex & /*parent*/) const +{ + return mKeySet.size(); +} + +int PredefinedSetModel::columnCount(const QModelIndex & /*parent*/) const +{ + return 2; +} + +QVariant PredefinedSetModel::headerData(int section, Qt::Orientation orientation, int role) const +{ + if (role == Qt::DisplayRole) + { + if (orientation == Qt::Horizontal) { + return mKeySet.type(section); + } + } + return QVariant(); +} + +QVariant PredefinedSetModel::data(const QModelIndex &index, int role) const +{ + if (role == Qt::DisplayRole) + { + const int row = index.row(); + const int column = index.column(); + + if (column == PredefinedKeySet::ColumnType::FILES) + { + return mKeySet.filePathAt(row); + } + else if (column == PredefinedKeySet::ColumnType::KEYFRAMEPOS) + { + return QString::number(mKeySet.keyFrameIndexAt(row)); + } + } + return QVariant(); +} diff --git a/pool/shard001/C++/0022260_boss_overlord_wyrmthalak.cpp b/pool/shard001/C++/0022260_boss_overlord_wyrmthalak.cpp new file mode 100644 index 0000000000000000000000000000000000000000..796b2fe9b65f833043163fd6601568648cbb6f3a --- /dev/null +++ b/pool/shard001/C++/0022260_boss_overlord_wyrmthalak.cpp @@ -0,0 +1,132 @@ +/* + * This file is part of the OregonCore Project. See AUTHORS file for Copyright information + * + * 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: Boss_Overlord_Wyrmthalak +SD%Complete: 100 +SDComment: +SDCategory: Blackrock Spire +EndScriptData */ + +#include "ScriptMgr.h" +#include "ScriptedCreature.h" + +#define SPELL_BLASTWAVE 11130 +#define SPELL_SHOUT 23511 +#define SPELL_CLEAVE 20691 +#define SPELL_KNOCKAWAY 20686 + +#define ADD_1X -39.355381f +#define ADD_1Y -513.456482f +#define ADD_1Z 88.472046f +#define ADD_1O 4.679872f + +#define ADD_2X -49.875881f +#define ADD_2Y -511.896942f +#define ADD_2Z 88.195160f +#define ADD_2O 4.613114f + +struct boss_overlordwyrmthalakAI : public ScriptedAI +{ + boss_overlordwyrmthalakAI(Creature* c) : ScriptedAI(c) {} + + uint32 BlastWave_Timer; + uint32 Shout_Timer; + uint32 Cleave_Timer; + uint32 Knockaway_Timer; + bool Summoned; + + void Reset() + { + BlastWave_Timer = 20000; + Shout_Timer = 2000; + Cleave_Timer = 6000; + Knockaway_Timer = 12000; + Summoned = false; + } + + void EnterCombat(Unit* /*who*/) + { + } + + void UpdateAI(const uint32 diff) + { + //Return since we have no target + if (!UpdateVictim()) + return; + + //BlastWave_Timer + if (BlastWave_Timer <= diff) + { + DoCastVictim( SPELL_BLASTWAVE); + BlastWave_Timer = 20000; + } + else BlastWave_Timer -= diff; + + //Shout_Timer + if (Shout_Timer <= diff) + { + DoCastVictim( SPELL_SHOUT); + Shout_Timer = 10000; + } + else Shout_Timer -= diff; + + //Cleave_Timer + if (Cleave_Timer <= diff) + { + DoCastVictim( SPELL_CLEAVE); + Cleave_Timer = 7000; + } + else Cleave_Timer -= diff; + + //Knockaway_Timer + if (Knockaway_Timer <= diff) + { + DoCastVictim( SPELL_KNOCKAWAY); + Knockaway_Timer = 14000; + } + else Knockaway_Timer -= diff; + + //Summon two Beserks + if (!Summoned && HealthBelowPct(50)) + { + Unit* pTarget = SelectTarget(SELECT_TARGET_RANDOM, 0, 100, true); + + if (Creature* SummonedCreature = me->SummonCreature(9216, ADD_1X, ADD_1Y, ADD_1Z, ADD_1O, TEMPSUMMON_TIMED_DESPAWN, 300000)) + SummonedCreature->AI()->AttackStart(pTarget); + if (Creature* SummonedCreature = me->SummonCreature(9268, ADD_2X, ADD_2Y, ADD_2Z, ADD_2O, TEMPSUMMON_TIMED_DESPAWN, 300000)) + SummonedCreature->AI()->AttackStart(pTarget); + Summoned = true; + } + + DoMeleeAttackIfReady(); + } +}; +CreatureAI* GetAI_boss_overlordwyrmthalak(Creature* pCreature) +{ + return new boss_overlordwyrmthalakAI (pCreature); +} + +void AddSC_boss_overlordwyrmthalak() +{ + Script* newscript; + newscript = new Script; + newscript->Name = "boss_overlord_wyrmthalak"; + newscript->GetAI = &GetAI_boss_overlordwyrmthalak; + newscript->RegisterSelf(); +} + diff --git a/pool/shard001/C++/0022263_labelitem.cpp b/pool/shard001/C++/0022263_labelitem.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4b06895a43e7dd0ff742fcceb7fb962e1268d896 --- /dev/null +++ b/pool/shard001/C++/0022263_labelitem.cpp @@ -0,0 +1,121 @@ +/* + This file is part of KDE. + + 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 "labelitem.h" + +#include "polkamodel.h" + +#include + +LabelItem::LabelItem( PolkaModel *model, const Polka::ViewLabel &label ) + : QObject( model ), m_model( model ), m_label( label ), m_menuEnabled( true ) +{ + setBrush( QColor( 255,255,230 ) ); + + m_textItem = new QGraphicsTextItem( this ); + setText( label.text() ); + + m_fanMenu = new FanMenu( this ); + m_fanMenu->setZValue( 50 ); + m_fanMenu->hide(); + + FanMenuItem *menuItem = m_fanMenu->addItem( i18n("Remove") ); + connect( menuItem, SIGNAL( clicked() ), SLOT( emitRemoveLabel() ) ); + menuItem = m_fanMenu->addItem( i18n("Rename") ); + connect( menuItem, SIGNAL( clicked() ), SLOT( emitRenameLabel() ) ); + m_fanMenu->setupItems( 80 ); + + setAcceptHoverEvents( true ); + + setFlags( ItemIsMovable ); +} + +void LabelItem::setLabel( const Polka::ViewLabel &label ) +{ + m_label = label; + setText( label.text() ); +} + +Polka::ViewLabel LabelItem::label() const +{ + return m_label; +} + +void LabelItem::setText( const QString &text ) +{ + m_textItem->setPlainText( text ); + + int textWidth = m_textItem->boundingRect().width(); + int textHeight = m_textItem->boundingRect().height(); + + setRect( - textWidth / 2, - textHeight / 2, textWidth, textHeight ); + + m_textItem->setPos( - textWidth / 2, - textHeight / 2 ); +} + +void LabelItem::setMenuEnabled( bool enabled ) +{ + m_menuEnabled = enabled; + if ( !m_menuEnabled ) { + m_fanMenu->hide(); + } +} + +void LabelItem::hoverEnterEvent( QGraphicsSceneHoverEvent *event ) +{ + Q_UNUSED( event ); + + if ( m_menuEnabled ) { + m_fanMenu->show(); + emit menuShown(); + } +} + +void LabelItem::hoverLeaveEvent( QGraphicsSceneHoverEvent *event ) +{ + Q_UNUSED( event ); + + m_fanMenu->hide(); +} + +void LabelItem::mousePressEvent( QGraphicsSceneMouseEvent *event ) +{ + m_movePos = pos(); + + QGraphicsRectItem::mousePressEvent( event ); +} + +void LabelItem::mouseReleaseEvent( QGraphicsSceneMouseEvent *event ) +{ + if ( pos() != m_movePos ) { + emit itemMoved( m_label, pos() ); + } + + QGraphicsRectItem::mouseReleaseEvent( event ); +} + +void LabelItem::emitRemoveLabel() +{ + emit removeLabel( this ); +} + +void LabelItem::emitRenameLabel() +{ + emit renameLabel( this ); +} diff --git a/pool/shard001/C++/0022265_dijkstrea.cpp b/pool/shard001/C++/0022265_dijkstrea.cpp new file mode 100644 index 0000000000000000000000000000000000000000..52d6189c4f07317bb4bd2ebdc1b423f9b9346062 --- /dev/null +++ b/pool/shard001/C++/0022265_dijkstrea.cpp @@ -0,0 +1,60 @@ +#include +#include + +#include +#include +#include +#include + +using namespace std; + +const int MAXN = 50100; +const int INF = (int)(1e9 + 7); + +int n, m; +int d[MAXN]; +bool viz[MAXN]; +priority_queue, vector >, greater > > pq; +vector G[MAXN], C[MAXN]; + +void dijkstra() +{ + for (int i = 2; i <= n; ++i) + d[i] = INF; + pq.push(make_pair(0, 1)); + while (!pq.empty()) { + int x = pq.top().second; + int val = pq.top().first; + pq.pop(); + viz[x] = true; + for (size_t i = 0; i < G[x].size(); ++i) { + if (viz[G[x][i]]) + continue; + if (C[x][i] + val < d[G[x][i]]) { + d[G[x][i]] = val + C[x][i]; + pq.push(make_pair(d[G[x][i]], G[x][i])); + } + } + } +} + +int main() +{ + freopen("dijkstra.in", "r", stdin); + freopen("dijkstra.out", "w", stdout); + + scanf("%d %d", &n, &m); + for (int i = 1; i <= m; ++i) { + int a, b, c; + scanf("%d %d %d", &a, &b, &c); + G[a].push_back(b); + C[a].push_back(c); + } + dijkstra(); + + for (int i = 2; i <= n; ++i) + printf("%d ", d[i] >= INF ? 0 : d[i]); + printf("\n"); + + return 0; +} diff --git a/pool/shard001/C++/0022266_ObserverHandler.cc b/pool/shard001/C++/0022266_ObserverHandler.cc new file mode 100644 index 0000000000000000000000000000000000000000..6557b5f6d7df24b16638e1ecb960f08950323a80 --- /dev/null +++ b/pool/shard001/C++/0022266_ObserverHandler.cc @@ -0,0 +1,29 @@ +// +// Created by Eddie Hoyle on 17/09/16. +// + +#include "ObserverHandler.hh" + + +void ObserverHandler::addContext( ObserverContext* context ) +{ + m_contexts.push_back( context ); + if ( m_contexts.size() == 1 ) + { + setActiveContext( context ); + } +} + +void ObserverHandler::setActiveContext( ObserverContext* context ) +{ + if ( std::find( m_contexts.begin(), m_contexts.end(), context ) != m_contexts.end() ) + { + m_active = context; + } +} + +ObserverContext* ObserverHandler::getActiveContext() const +{ + return m_active; +} + diff --git a/pool/shard001/C++/0022268_REVector3.cpp b/pool/shard001/C++/0022268_REVector3.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fd2df6adce718823a0a2759d86d73b12dbc9f7a3 --- /dev/null +++ b/pool/shard001/C++/0022268_REVector3.cpp @@ -0,0 +1,56 @@ +/* + * Copyright 2012 - 2013 Kulykov Oleh + * + * 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/recore/REVector3.h" +#include "../../include/recore/REString.h" +#include "../../include/recore/private/REStringUtilsPrivate.h" + + + +REVector3 REVector3::fromString(const char * string) +{ + if (string) + { + REVector3 v; + if (REStringUtilsPrivate::readArrayF32(string, v.coords, 3, ';') == 3) + { + return v; + } + } + return REVector3(); +} + +REVector3 REVector3::fromString(const REString & string) +{ + if (string.length() > 0) + { + REVector3 v; + if (REStringUtilsPrivate::readArrayF32(string.UTF8String(), v.coords, 3, ';') == 3) + { + return v; + } + } + return REVector3(); +} + +REString REVector3::toString(const REVector3 & vector3) +{ + char buff[54]; + const REUInt32 len = REStringUtilsPrivate::writeArrayF32(vector3.coords, buff, 3, ';'); + return REString(buff, len); +} + diff --git a/pool/shard001/C++/0022270_GetDomainNamesResult.cpp b/pool/shard001/C++/0022270_GetDomainNamesResult.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0a37072d4c20d8f65f7eeda022288839c259ef64 --- /dev/null +++ b/pool/shard001/C++/0022270_GetDomainNamesResult.cpp @@ -0,0 +1,57 @@ +/* +* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"). +* You may not use this file except in compliance with the License. +* A copy of the License is located at +* +* http://aws.amazon.com/apache2.0 +* +* or in the "license" file accompanying this file. This file is distributed +* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +* express or implied. See the License for the specific language governing +* permissions and limitations under the License. +*/ +#include +#include +#include +#include + +#include + +using namespace Aws::APIGateway::Model; +using namespace Aws::Utils::Json; +using namespace Aws::Utils; +using namespace Aws; + +GetDomainNamesResult::GetDomainNamesResult() +{ +} + +GetDomainNamesResult::GetDomainNamesResult(const AmazonWebServiceResult& result) +{ + *this = result; +} + +GetDomainNamesResult& GetDomainNamesResult::operator =(const AmazonWebServiceResult& result) +{ + const JsonValue& jsonValue = result.GetPayload(); + if(jsonValue.ValueExists("position")) + { + m_position = jsonValue.GetString("position"); + + } + + if(jsonValue.ValueExists("items")) + { + Array itemsJsonList = jsonValue.GetArray("items"); + for(unsigned itemsIndex = 0; itemsIndex < itemsJsonList.GetLength(); ++itemsIndex) + { + m_items.push_back(itemsJsonList[itemsIndex].AsObject()); + } + } + + + + return *this; +} diff --git a/pool/shard001/C++/0022285_spp_struct.cc b/pool/shard001/C++/0022285_spp_struct.cc new file mode 100644 index 0000000000000000000000000000000000000000..2f21ec9aad02f0029006d77689f45a66cf99917a --- /dev/null +++ b/pool/shard001/C++/0022285_spp_struct.cc @@ -0,0 +1,57 @@ +/****************************************************************************** + * Copyright 2018 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/perception/lidar/lib/detector/cnn_segmentation/spp_engine/spp_struct.h" + +namespace apollo { +namespace perception { +namespace lidar { + +void SppData::MakeReference(size_t width, size_t height, float range) { + obs_prob_data = category_pt_blob->mutable_cpu_data(); + offset_data = instance_pt_blob->mutable_cpu_data(); + confidence_data = confidence_pt_blob->mutable_cpu_data(); + if (height_pt_blob != nullptr) { + z_data = height_pt_blob->mutable_cpu_data(); + } + if (classify_pt_blob != nullptr) { + class_prob_data = classify_pt_blob->mutable_cpu_data(); + } + if (heading_pt_blob != nullptr) { + heading_data = heading_pt_blob->mutable_cpu_data(); + } + + if (obs_prob_data_ref == nullptr) { + obs_prob_data_ref = new float*[height]; + } + for (size_t i = 0; i < height; ++i) { + obs_prob_data_ref[i] = obs_prob_data + i * width; + } + + data_width = width; + data_height = height; + data_range = range; + data_size = width * height; +} + +SppData::~SppData() { + if (obs_prob_data_ref) { + delete[] obs_prob_data_ref; + } +} + +} // namespace lidar +} // namespace perception +} // namespace apollo diff --git a/pool/shard001/C++/0022289_filterSameClassHighBlast.cc b/pool/shard001/C++/0022289_filterSameClassHighBlast.cc new file mode 100644 index 0000000000000000000000000000000000000000..d66ce058b9daa13c39432436487015f7cc76087c --- /dev/null +++ b/pool/shard001/C++/0022289_filterSameClassHighBlast.cc @@ -0,0 +1,91 @@ +/* + * Author: Paul B. Horton + * Organization: Computational Biology Research Center, AIST, Japan + * Copyright (C) 2004, 2006, Paul B. Horton, All rights reserved. + * Creation Date: 2004.6.16 + * Last Modified: $Date: 2009/04/25 06:21:47 $ + * + * Description: filter protein pairs in the WoLF_PSORT dataset. + * pairs with good (low) e-value scores and + * the same localization site are printed out. + * + * + */ +#include +#include +#include +#include "../Blast8ResultReader.hh" +#include "utils/perlish/perlish.hh" +#include "utils/math/StayFiniteLog.hh" +#include "classifiers/LabeledInstances.hh" + +namespace cbrc{ + void filterSameClassHighBlast( std::istream& trainStream, + std::istream& blastResultsStream, + const double& eValueThreshold ){ + Blast8ResultReader blastResults( blastResultsStream, false ); + LabeledInstances lis( LabeledInstances::text, trainStream ); + std::map nameToClass = lis.getNameToClassMap(); + std::vector hitNames; + + for( size_t i = 0; i < lis.size(); ++i ){ + if( !blastResults.has( lis(i).name() ) ) continue; + + const std::vector hitV = blastResults( lis(i).name() ); + + hitNames.clear(); + + for( size_t j = 0; j < hitV.size(); ++j ){ + + if(( nameToClass[ hitV[j].hitName() ] == nameToClass[ lis(i).name() ] ) + && ( hitV[j].eValue() <= eValueThreshold ) + ){ + if( hitV[j].hitName() != lis(i).name() ) hitNames.push_back( hitV[j].hitName() ); + } + } + + if( hitNames.size() > 0 ){ + std::cout << lis(i).name(); + for( size_t i = 0; i < hitNames.size(); ++i ) std::cout << " " << hitNames[i]; + std::cout << std::endl; + } + } + } +}; // end namescape cbrc + + +int main( int argc, char** argv ){ + std::string usage( "Usage: " ); + usage += argv[0]; + usage += " WoLFPSORTfile blastResultFile [lg] BlastScoreThreshold"; + if( (argc < 4) || (argc > 5) ){ + std::cout << usage << "\nError: wrong number of arguments\n"; + exit( -1 ); + } + int curArg = 1; + std::ifstream trainStream( argv[curArg++] ); + if( !trainStream ){ + std::cout << " could not open file " << argv[curArg-1] << std::endl; + exit( -1 ); + } + std::ifstream blastResultsStream( argv[curArg++] ); + if( !blastResultsStream ){ + std::cout << " could not open file " << argv[curArg-1] << std::endl; + exit( -1 ); + } + double eValueThreshold; + if( strcmp( argv[curArg], "lg" ) ){ + eValueThreshold = cbrc::perlish::toDouble( argv[curArg] ); + }else{ + if( argc != 5 ){ + std::cout << usage << "\nError: wrong number of arguments\n"; + exit( -1 ); + } + eValueThreshold = pow( 2, cbrc::perlish::toDouble( argv[++curArg] ) ); + } + std::cerr << __FILE__ << ":" << __LINE__ << " eValueThreshold: " << eValueThreshold << std::endl; + cbrc::filterSameClassHighBlast( trainStream, blastResultsStream, + eValueThreshold ); + return 1; +} + diff --git a/pool/shard001/C++/0022295_TcpComm.cpp b/pool/shard001/C++/0022295_TcpComm.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c92030ba94ff8f12e15c2447350fc69b0d3facf8 --- /dev/null +++ b/pool/shard001/C++/0022295_TcpComm.cpp @@ -0,0 +1,242 @@ +#include "TcpComm.h" + +#ifndef WINCE +#include +#include +#endif + +#ifdef WIN32 + +#ifndef WINCE +#include +#endif + +#define ERRNO WSAGetLastError() +#define RESET_ERRNO WSASetLastError(0) +#undef EWOULDBLOCK +#define EWOULDBLOCK WSAEWOULDBLOCK +#undef EINPROGRESS +#define EINPROGRESS WSAEINPROGRESS +#define NON_BLOCK(socket) ioctlsocket(socket, FIONBIO, (u_long*) "NONE") +#define CLOSE(socket) closesocket(socket) + +class _WSAFramework +{ +public: + _WSAFramework() + { + WORD wVersionRequested = MAKEWORD(1, 0); + WSADATA wsaData; + WSAStartup(wVersionRequested, &wsaData); + } + ~_WSAFramework() {WSACleanup();} +} _wsaFramework; + +#else + +#include +#include +#include +#include +#include + +#define ERRNO errno +#define RESET_ERRNO errno = 0 +#define NON_BLOCK(socket) fcntl(socket,F_SETFL,O_NONBLOCK) +#define CLOSE(socket) close(socket) + +#endif + +TcpComm::TcpComm(const char* ip, int port, int maxPackageSendSize, int maxPackageReceiveSize) : + createSocket(0), + transferSocket(0), + overallBytesSent(0), + overallBytesReceived(0), + maxPackageSendSize(maxPackageSendSize), + maxPackageReceiveSize(maxPackageReceiveSize), + wasConnected(false) +{ + address.sin_family = AF_INET; + address.sin_port = htons(port); + if(ip) // connect as client? + address.sin_addr.s_addr = inet_addr(ip); + else + { + createSocket = socket(AF_INET, SOCK_STREAM, 0); + ASSERT(createSocket > 0); + int val = 1; + setsockopt(createSocket, SOL_SOCKET, SO_REUSEADDR, (char*) &val, sizeof(val)); + address.sin_addr.s_addr = INADDR_ANY; + VERIFY(bind(createSocket, (sockaddr*) &address, sizeof(sockaddr_in)) == 0); + VERIFY(listen(createSocket, SOMAXCONN) == 0); + NON_BLOCK(createSocket); + } + checkConnection(); +} + +TcpComm::~TcpComm() +{ + if(connected()) + closeTransferSocket(); + if(createSocket > 0) + CLOSE(createSocket); +} + +bool TcpComm::checkConnection() +{ + if(!connected()) + { +#ifndef WIN32 + unsigned int addrlen = sizeof(sockaddr_in); +#else + int addrlen = sizeof(sockaddr_in); +#endif + + if(createSocket) + transferSocket = accept(createSocket, (sockaddr*) &address, &addrlen); + else if(!wasConnected) + { + transferSocket = socket(AF_INET, SOCK_STREAM, 0); + ASSERT(connected()); + if(connect(transferSocket, (sockaddr*) &address, sizeof(sockaddr_in)) != 0) + { + CLOSE(transferSocket); + transferSocket = 0; + } + } + + if(connected()) + { + wasConnected = true; + NON_BLOCK(transferSocket); // switch socket to nonblocking +#ifdef MACOSX + int yes = 1; + VERIFY(!setsockopt(transferSocket, SOL_SOCKET, SO_NOSIGPIPE, &yes, sizeof(yes))); +#endif + if(maxPackageSendSize) + VERIFY(!setsockopt(transferSocket, SOL_SOCKET, SO_SNDBUF, (char*)&maxPackageSendSize, sizeof(maxPackageSendSize))); + if(maxPackageReceiveSize) + VERIFY(!setsockopt(transferSocket, SOL_SOCKET, SO_RCVBUF, (char*)&maxPackageReceiveSize, sizeof(maxPackageReceiveSize))); + return true; + } + else + return false; + } + else + return true; +} + +void TcpComm::closeTransferSocket() +{ + CLOSE(transferSocket); + transferSocket = 0; +} + +bool TcpComm::receive(unsigned char* buffer, int size, bool wait) +{ + if(!checkConnection()) + return false; + + if(!wait) + { + RESET_ERRNO; +#ifndef WIN32 + int received = recv(transferSocket, (char*) buffer, size, MSG_PEEK); + if(received < size) + { + if(!received || (received < 0 && ERRNO != EWOULDBLOCK && ERRNO != EINPROGRESS)) + closeTransferSocket(); + return false; + } +#else + char c; + int received = recv(transferSocket, &c, 1, MSG_PEEK); + if(!received || (received < 0 && ERRNO != EWOULDBLOCK && ERRNO != EINPROGRESS) || + ioctlsocket(transferSocket, FIONREAD, (u_long*) &received) != 0) + { + closeTransferSocket(); + return false; + } + else if(received == 0) + return false; +#endif + } + + int received = 0; + while(received < size) + { + RESET_ERRNO; + + int received2 = recv(transferSocket, (char*) buffer + received, + size - received, 0); + + if(!received2 || (received2 < 0 && ERRNO != EWOULDBLOCK && ERRNO != EINPROGRESS)) // error during reading of package + { + closeTransferSocket(); + return false; + } + else if(ERRNO == EWOULDBLOCK || ERRNO == EINPROGRESS) // wait for the rest + { + received2 = 0; + timeval timeout; + timeout.tv_sec = 0; + timeout.tv_usec = 100000; + fd_set rset; + FD_ZERO(&rset); + FD_SET(transferSocket, &rset); + if(select(transferSocket + 1, &rset, 0, 0, &timeout) == -1) + { + closeTransferSocket(); + return false; // error while waiting + } + } + received += received2; + overallBytesReceived += received2; + } + return true; // ok, data received +} + +int TcpComm::receiveSys(void* buffer, unsigned int len, int flags) +{ + return recv(transferSocket, (char*) buffer, len, flags); +} + +bool TcpComm::send(const unsigned char* buffer, int size) +{ + if(!checkConnection()) + return false; + + RESET_ERRNO; + int sent = ::send(transferSocket, (const char*) buffer, size, 0); + if(sent > 0) + { + overallBytesSent += sent; + while(sent < size && (ERRNO == EWOULDBLOCK || ERRNO == EINPROGRESS || ERRNO == 0)) + { + timeval timeout; + timeout.tv_sec = 0; + timeout.tv_usec = 100000; + fd_set wset; + FD_ZERO(&wset); + FD_SET(transferSocket, &wset); + RESET_ERRNO; + if(select(transferSocket + 1, 0, &wset, 0, &timeout) == -1) + break; + RESET_ERRNO; + int sent2 = ::send(transferSocket, (const char*) buffer + sent, size - sent, 0); + if(sent2 >= 0) + { + sent += sent2; + overallBytesSent += sent; + } + } + } + + if(ERRNO == 0 && sent == size) + return true; + else + { + closeTransferSocket(); + return false; + } +} diff --git a/pool/shard001/C++/0022297_Deonion.cpp b/pool/shard001/C++/0022297_Deonion.cpp new file mode 100644 index 0000000000000000000000000000000000000000..255d681d4348560bc8a0b5d10e4b024b373882eb --- /dev/null +++ b/pool/shard001/C++/0022297_Deonion.cpp @@ -0,0 +1,145 @@ +/* + * Ctrl-Cut - Laser cutter toolchain + * See LICENSE file + * Copyright (C) 2011 Amir Hassan and Marius kintel + */ + + +#include "util/Logger.hpp" +#include "cut/graph/Traverse.hpp" +#include "cut/geom/SegmentTree.hpp" +#include "cut/geom/Route.hpp" +#include "cut/geom/algorithms/Algorithms.hpp" + +typedef SegmentGraphImpl UniqueSegmentGraph; +typedef UniqueSegmentGraph::Vertex Vertex; +typedef UniqueSegmentGraph::Edge Edge; +typedef std::map::iterator IndexIter; + +void walkTheEdge(Route& skins, UniqueSegmentGraph& graph, const Edge lastEdge, const Vertex outV) +{ + Edge nextEdge; + Segment lastSegment = graph[lastEdge]; + Point lastPoint = graph[outV]; + + graph.remove_edge(lastEdge); + float lastSlope; + + if(lastPoint == lastSegment[0]) + lastSlope = lastSegment.getSlope(); + else if(lastPoint == lastSegment[1]) + lastSlope = lastSegment.getSlope(true); + else + assert(false); + + float minSlopeDiff = (CC_PI * 2); + float candidateSlope; + double slopeDiff; + bool found = false; + + BOOST_FOREACH(Edge candidate , boost::out_edges(outV, graph)) { + Segment& segment = graph[candidate]; + + //skip identical segment + if(segment == lastSegment) + continue; + + if(segment[0] != lastPoint) + candidateSlope = segment.getSlope(true); + else + candidateSlope = segment.getSlope(); + + slopeDiff = lastSlope - candidateSlope; + + if(slopeDiff < 0.01) + slopeDiff += CC_PI * 2; + + /*std::cerr << *segment << std::endl; + std::cerr << candidateSlope << std::endl;*/ + + //save the edge with the least clockwise angle (= least slop_diff) + if (slopeDiff < minSlopeDiff) { + minSlopeDiff = slopeDiff; + nextEdge = candidate; + found = true; + } + } + + if (found) { + Segment& seg = graph[nextEdge]; + if(!concat(skins, seg)) + append(skins,seg); + + //graph.index.erase(seg.first); + //graph.index.erase(seg.second); + walkTheEdge(skins, graph, nextEdge, get_opposite(graph, nextEdge, outV)); + } + + //polyline fully consumed +} + +bool find_steapest(Edge& found, const Vertex& v, const UniqueSegmentGraph& g) { + // Find next clockwise segment + float steapest = 2 * CC_PI; + bool f = false; + + BOOST_FOREACH (const Edge candidate, boost::out_edges(v, g)){ + const Segment& seg = g[candidate]; + float steapness = CC_PI - seg.getSlope(); + + if(steapness < 0) + steapness += (2 * CC_PI); + + if (steapness < steapest) { + steapest = steapness; + found = candidate; + f=true; + } + } + return f; +} + +void traverse_onion(const Route& src, Route& skins) +{ + LOG_DEBUG(src.size()); + + UniqueSegmentGraph g; + for(const SegmentPtr seg : segments(src)) { + g.addSegment(*seg.get()); + } + + // points are sorted first by x then by y. therefore the + // first point in the index must be the most left + while (!g.index.empty()) { + Point most_left_point = (*g.index.begin()).first; + Vertex most_left_vertex = (*g.index.begin()).second; + + Edge steapest; + + if(!find_steapest(steapest, most_left_vertex, g)) { + //dangling vertex + g.index.erase(g.index.begin()); + continue; + } + + const Vertex next_vertex = get_opposite(g,steapest, most_left_vertex); + const Point& next_point = g[next_vertex]; + + const Segment& steapest_seg = g[steapest]; + if(!concat(skins, steapest_seg)) + append(skins,steapest_seg); + + // g.index.erase(g.index.begin()); + + if(next_point.y < most_left_point.y || (next_point.y == most_left_point.y && next_point.x > most_left_point.x)) { + walkTheEdge(skins, g, steapest, next_vertex); + } + else { + walkTheEdge(skins, g, steapest, most_left_vertex); + } + + } + + reverse(skins.begin(), skins.end()); + LOG_DEBUG(skins.size()); +} diff --git a/pool/shard001/C++/0022300_main.cpp b/pool/shard001/C++/0022300_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c2efc0412b662df6c52691e057f1e908d67c3080 --- /dev/null +++ b/pool/shard001/C++/0022300_main.cpp @@ -0,0 +1,130 @@ +/*============================================================================= + Copyright (c) 2001-2011 Joel de Guzman + Copyright (c) 2001-2011 Hartmut Kaiser + + 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) +=============================================================================*/ +/////////////////////////////////////////////////////////////////////////////// +// +// Not a calculator anymore, right? :-) +// +// [ JDG April 10, 2007 ] spirit2 +// [ JDG February 18, 2011 ] Pure attributes. No semantic actions. +// [ HK June 3, 2011 ] Adding lexer +// +/////////////////////////////////////////////////////////////////////////////// + +#include "config.hpp" +#include "function.hpp" +#include "vm.hpp" +#include "compiler.hpp" +#include "lexer.hpp" +#include +#include + +/////////////////////////////////////////////////////////////////////////////// +// Main program +/////////////////////////////////////////////////////////////////////////////// +int main(int argc, char **argv) +{ + char const* filename; + if (argc > 1) + { + filename = argv[1]; + } + else + { + std::cerr << "Error: No input file provided." << std::endl; + return 1; + } + + std::ifstream in(filename, std::ios_base::in); + + if (!in) + { + std::cerr << "Error: Could not open input file: " + << filename << std::endl; + return 1; + } + + std::string source_code; // We will read the contents here. + in.unsetf(std::ios::skipws); // No white space skipping! + std::copy( + std::istream_iterator(in), + std::istream_iterator(), + std::back_inserter(source_code)); + + typedef std::string::const_iterator base_iterator_type; + typedef client::lexer::conjure_tokens lexer_type; + typedef lexer_type::iterator_type iterator_type; + + lexer_type lexer; // Our lexer + + base_iterator_type first = source_code.begin(); + base_iterator_type last = source_code.end(); + + iterator_type iter = lexer.begin(first, last); + iterator_type end = lexer.end(); + + client::vmachine vm; // Our virtual machine + client::ast::function_list ast; // Our AST + + client::error_handler + error_handler(first, last); // Our error handler + client::parser::function + function(error_handler, lexer); // Our parser + client::code_gen::compiler + compiler(error_handler); // Our compiler + + // note: we don't need a skipper + bool success = parse(iter, end, +function, ast); + + std::cout << "-------------------------\n"; + + if (success && iter == end) + { + if (compiler(ast)) + { + boost::shared_ptr + p = compiler.find_function("main"); + if (!p) + return 1; + + int nargs = argc-2; + if (p->nargs() != nargs) + { + std::cerr << "Error: main function requires " << p->nargs() << " arguments." << std::endl; + std::cerr << nargs << " supplied." << std::endl; + return 1; + } + + std::cout << "Success\n"; + std::cout << "-------------------------\n"; + std::cout << "Assembler----------------\n\n"; + compiler.print_assembler(); + + // Push the arguments into our stack + for (int i = 0; i < nargs; ++i) + vm.get_stack()[i] = boost::lexical_cast(argv[i+2]); + + // Call the interpreter + int r = vm.execute(compiler.get_code()); + + std::cout << "-------------------------\n"; + std::cout << "Result: " << r << std::endl; + std::cout << "-------------------------\n\n"; + } + else + { + std::cout << "Compile failure\n"; + } + } + else + { + std::cout << "Parse failure\n"; + } + return 0; +} + + diff --git a/pool/shard001/C++/0022317_debug.cpp b/pool/shard001/C++/0022317_debug.cpp new file mode 100644 index 0000000000000000000000000000000000000000..da9adc50e5cd0aeb3b6ab49aa4db38fc56e60dcc --- /dev/null +++ b/pool/shard001/C++/0022317_debug.cpp @@ -0,0 +1,104 @@ +/***************************************************************************** + + This file is part of Modelica C Compiler. + + Modelica C Compiler 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. + + Modelica C Compiler 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 Modelica C Compiler. If not, see . + +******************************************************************************/ + +#include + +#include +#include +#include +#include + +static const char *enableFlags = NULL; // controls which DEBUG messages are printed + +void debugInit(const char *flagList) { + enableFlags = flagList; +} + +bool debugIsEnabled(char flag) { + if (enableFlags != NULL) + return (strchr(enableFlags, flag) != 0) + || (strchr(enableFlags, '+') != 0); + else + return false; +} + +void DEBUG(char flag, const char *format, ...) { + if (debugIsEnabled(flag)) { + va_list ap; + va_start(ap, format); + vfprintf(stdout, format, ap); + fflush(stdout); + va_end(ap); + } +} + +bool isDebugParam(char *param) { + if (strcmp(param, "c") == 0) { + return true; + } + if (strcmp(param, "a") == 0) { + return true; + } + if (strcmp(param, "s") == 0) { + return true; + } + if (strcmp(param, "g") == 0) { + return true; + } + return false; +} + +void ERROR(const char *format, ...) { + va_list ap; + va_start(ap, format); + const char *error_string = "Error: "; + char *new_format = (char *) malloc(sizeof(char) * strlen(error_string) + (strlen(format))); + strcpy(new_format, error_string); + strcat(new_format, format); + vfprintf(stderr, new_format, ap); + fprintf(stderr,"\n"); + fflush(stderr); + va_end(ap); + exit(EXIT_FAILURE); +} + +void ERROR_UNLESS(bool condition, const char *format, ...) { + if(!condition) { + va_list ap; + va_start(ap, format); + ERROR(format, ap); + va_end(ap); + } +} + +void WARNING(const char *format, ...) { + va_list ap; + va_start(ap, format); + const char *error_string = "Warning: "; + char *new_format = (char *) malloc(sizeof(char) * strlen(error_string) + (strlen(format))); + strcpy(new_format, error_string); + strcat(new_format, format); + vfprintf(stderr, new_format, ap); + fprintf(stderr,"\n"); + fflush(stderr); + free(new_format); + va_end(ap); +} + + diff --git a/pool/shard001/C++/0022320_Update.cpp b/pool/shard001/C++/0022320_Update.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a92724ac16f28f1a17b7fc905dea15018f6ec47b --- /dev/null +++ b/pool/shard001/C++/0022320_Update.cpp @@ -0,0 +1,141 @@ +/* + + Copyright (C) 2007 Gregory Smith + and the "Aleph One" developers. + + 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. + + This license is contained in the file "COPYING", + which is included with this source code; it is available online at + http://www.gnu.org/licenses/gpl.html + + Checks for updates online + +*/ + +#include "Update.h" +#include "SDL_net.h" +#include +#include +#include "alephversion.h" + +Update *Update::m_instance = 0; + +Update::Update() : m_status(NoUpdateAvailable), m_thread(0) +{ + StartUpdateCheck(); +} + +Update::~Update() +{ + if (m_thread) + { + int status; + SDL_WaitThread(m_thread, &status); + m_thread = 0; + } +} + +int Update::update_thread(void *p) +{ + Update *update = static_cast(p); + return update->Thread(); +} + +void Update::StartUpdateCheck() +{ + if (m_status == CheckingForUpdate) return; + if (m_thread) + { + int status; + SDL_WaitThread(m_thread, &status); + m_thread = 0; + } + + m_status = CheckingForUpdate; + m_new_date_version.clear(); + m_new_display_version.clear(); + + m_thread = SDL_CreateThread(update_thread, this); + if (!m_thread) + { + m_status = UpdateCheckFailed; + } +} + +int Update::Thread() +{ + IPaddress ip; + if (SDLNet_ResolveHost(&ip, A1_UPDATE_HOST, 80) < 0) + { + m_status = UpdateCheckFailed; + return 1; + } + + TCPsocket sock = SDLNet_TCP_Open(&ip); + if (!sock) + { + m_status = UpdateCheckFailed; + return 2; + } + + char request[1024]; + sprintf(request, "GET /update_check/%s.php HTTP/1.1\r\nHost: %s\r\nConnection: close\r\n\r\n", A1_UPDATE_PLATFORM, A1_UPDATE_HOST); + + if (SDLNet_TCP_Send(sock, request, strlen(request)) < strlen(request)) + { + m_status = UpdateCheckFailed; + return 3; + } + + // ghs: SHOULD but doesn't: + // handle Location: header + // handle chunked transfers? + + const int MAX_REPLY = 8192; + char reply[MAX_REPLY]; + + int len = SDLNet_TCP_Recv(sock, reply, MAX_REPLY); + if (len < 0) + { + m_status = UpdateCheckFailed; + return 4; + } + + reply[len] = 0; + + char *line = strtok(reply, "\r\n"); + while (line) + { + if (strncmp(line, "A1_DATE_VERSION: ", strlen("A1_DATE_VERSION: ")) == 0) + { + m_new_date_version.assign(line + strlen("A1_DATE_VERSION: ")); + } + else if (strncmp(line, "A1_DISPLAY_VERSION: ", strlen("A1_DISPLAY_VERSION: ")) == 0) + { + m_new_display_version.assign(line + strlen("A1_DISPLAY_VERSION: ")); + } + line = strtok(0, "\r\n"); + } + + if (m_new_date_version.size()) + { + m_status = m_new_date_version.compare(A1_DATE_VERSION) > 0 ? UpdateAvailable : NoUpdateAvailable; + return 0; + } + else + { + m_status = UpdateCheckFailed; + return 5; + } +} + + diff --git a/pool/shard001/C++/0022322_Logger.cpp b/pool/shard001/C++/0022322_Logger.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f45b42b42671ba3b850410c38721673b784ed7e4 --- /dev/null +++ b/pool/shard001/C++/0022322_Logger.cpp @@ -0,0 +1,43 @@ +#include "utils/Logger.h" + +namespace Logger { + +const int maxVerbosityLvl = 3; + +std::ofstream logfile_default; + +bool isLogToFile = false; + +/// Global verbosity level for output. +#ifndef NDEBUG +// Default to maximum verbosity level when in debug mode +int gVerbosityLvl = maxVerbosityLvl; +#else +int gVerbosityLvl = 0; +#endif // NDEBUG + +void setVerbosityLevel (int lvl) { + if (lvl < 5) + gVerbosityLvl = lvl; +} + +void setLogMethod (bool isFile) { + isLogToFile = isFile ; +} + +void setLogFile (const std::string &file ) { + print( 0, " Opening ", file, " for logging. " ); + logfile_default.open( file ); +} + +void closeFile() { + if ( logfile_default.is_open() ) + logfile_default.close(); + + if ( isLogToFile ) { + print( 0, "Logging file closed." ); + isLogToFile = false; + } +} + +} diff --git a/pool/shard001/C++/0022327_utilities.cpp b/pool/shard001/C++/0022327_utilities.cpp new file mode 100644 index 0000000000000000000000000000000000000000..19a3b346091b18e3a24a88ff4328c2bb38d72dd9 --- /dev/null +++ b/pool/shard001/C++/0022327_utilities.cpp @@ -0,0 +1,310 @@ +/* + * Copyright 2011, 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 "common.h" + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/*************** + * AdaptiveMap * + ***************/ + +jlong Java_com_googlecode_leptonica_android_AdaptiveMap_nativeBackgroundNormMorph(JNIEnv *env, + jclass clazz, + jlong nativePix, + jint reduction, + jint size, + jint bgval) { + // Normalizes the background of each element in pixa. + + PIX *pixs = (PIX *) nativePix; + PIX *pixd = pixBackgroundNormMorph(pixs, NULL, (l_int32) reduction, (l_int32) size, + (l_int32) bgval); + + return (jlong) pixd; +} + +jlong Java_com_googlecode_leptonica_android_AdaptiveMap_nativePixContrastNorm(JNIEnv *env, + jclass clazz, + jlong nativePix, + jint sizeX, + jint sizeY, + jint minDiff, + jint smoothX, + jint smoothY) { + + PIX *pixs = (PIX *) nativePix; + PIX *pixd = pixContrastNorm(NULL, pixs, (l_int32) sizeX, (l_int32) sizeY, + (l_int32) minDiff, (l_int32) smoothX, (l_int32) smoothY); + + return (jlong) pixd; +} + +/************ + * Binarize * + ************/ + +jlong Java_com_googlecode_leptonica_android_Binarize_nativeOtsuAdaptiveThreshold(JNIEnv *env, + jclass clazz, + jlong nativePix, + jint sizeX, + jint sizeY, + jint smoothX, + jint smoothY, + jfloat scoreFract) { + + PIX *pixs = (PIX *) nativePix; + PIX *pixd; + + if (pixOtsuAdaptiveThreshold(pixs, (l_int32) sizeX, (l_int32) sizeY, (l_int32) smoothX, + (l_int32) smoothY, (l_float32) scoreFract, NULL, &pixd)) { + return (jlong) 0; + } + + return (jlong) pixd; +} + +jlong Java_com_googlecode_leptonica_android_Binarize_nativeSauvolaBinarizeTiled(JNIEnv *env, + jclass clazz, + jlong nativePix, + jint whsize, + jfloat factor, + jint nx, + jint ny) { + + PIX *pixs = (PIX *) nativePix; + PIX *pixd; + + if (pixSauvolaBinarizeTiled(pixs, (l_int32) whsize, (l_float32) factor, (l_int32) nx, + (l_int32) ny, NULL, &pixd)) { + return (jlong) 0; + } + + return (jlong) pixd; +} + +/******** + * Clip * + ********/ + +jlong Java_com_googlecode_leptonica_android_Clip_nativeClipRectangle(JNIEnv *env, jclass clazz, + jlong nativePix, jlong nativeBox) { + + PIX *pixs = (PIX *) nativePix; + BOX *box = (BOX *) nativeBox; + PIX *pixd; + pixd = pixClipRectangle(pixs,box,NULL); + return (jlong) pixd; +} + +/*********** + * Convert * + ***********/ + +jlong Java_com_googlecode_leptonica_android_Convert_nativeConvertTo8(JNIEnv *env, jclass clazz, + jlong nativePix) { + PIX *pixs = (PIX *) nativePix; + PIX *pixd = pixConvertTo8(pixs, FALSE); + + return (jlong) pixd; +} + +/******** + * Edge * + ********/ + +jlong Java_com_googlecode_leptonica_android_Edge_nativePixSobelEdgeFilter(JNIEnv *env, + jclass clazz, + jlong nativePix, + jint orientFlag) { + PIX *pixs = (PIX *) nativePix; + PIX *pixd = pixSobelEdgeFilter(pixs, (l_int32) orientFlag); + + return (jlong) pixd; +} + +/*********** + * Enhance * + ***********/ + +jlong Java_com_googlecode_leptonica_android_Enhance_nativeUnsharpMasking(JNIEnv *env, jclass clazz, + jlong nativePix, + jint halfwidth, + jfloat fract) { + PIX *pixs = (PIX *) nativePix; + PIX *pixd = pixUnsharpMasking(pixs, (l_int32) halfwidth, (l_float32) fract); + + return (jlong) pixd; +} + +/************* + * GrayQuant * + *************/ + +jlong Java_com_googlecode_leptonica_android_GrayQuant_nativePixThresholdToBinary(JNIEnv *env, jclass clazz, + jlong nativePix, jint thresh) { + PIX *pixs = (PIX *) nativePix; + PIX *pixd = pixThresholdToBinary(pixs, (l_int32) thresh); + + return (jlong) pixd; +} + +/********** + * JpegIO * + **********/ + +jbyteArray Java_com_googlecode_leptonica_android_JpegIO_nativeCompressToJpeg(JNIEnv *env, + jclass clazz, + jlong nativePix, + jint quality, + jboolean progressive) { + PIX *pix = (PIX *) nativePix; + + l_uint8 *data; + size_t size; + + if (pixWriteMemJpeg(&data, &size, pix, (l_int32) quality, progressive == JNI_TRUE ? 1 : 0)) { + LOGE("Failed to write JPEG data"); + + return NULL; + } + + // TODO Can we just use the byte array directly? + jbyteArray array = env->NewByteArray(size); + env->SetByteArrayRegion(array, 0, size, (jbyte *) data); + + free(data); + + return array; +} + +/************ + * MorphApp * + ************/ + +jlong Java_com_googlecode_leptonica_android_MorphApp_nativePixTophat(JNIEnv *env, jclass clazz, + jlong nativePix, jint hsize, + jint vsize, jint type) { + PIX *pixs = (PIX *) nativePix; + PIX *pixd = pixTophat(pixs, (l_int32) hsize, (l_int32) vsize, (l_int32) type); + + return (jlong) pixd; +} + +jlong Java_com_googlecode_leptonica_android_MorphApp_nativePixFastTophat(JNIEnv *env, jclass clazz, + jlong nativePix, jint xsize, + jint ysize, jint type) { + PIX *pixs = (PIX *) nativePix; + PIX *pixd = pixFastTophat(pixs, (l_int32) xsize, (l_int32) ysize, (l_int32) type); + + return (jlong) pixd; +} + +/********* + * Scale * + *********/ + +jlong Java_com_googlecode_leptonica_android_Scale_nativeScaleGeneral(JNIEnv *env, jclass clazz, + jlong nativePix, jfloat scaleX, + jfloat scaleY, jfloat sharpfract, jint sharpwidth) { + PIX *pixs = (PIX *) nativePix; + PIX *pixd = pixScaleGeneral(pixs, (l_float32) scaleX, (l_float32) scaleY,(l_float32) sharpfract, (l_int32) sharpwidth); + return (jlong) pixd; +} + +jlong Java_com_googlecode_leptonica_android_Scale_nativeScale(JNIEnv *env, jclass clazz, + jlong nativePix, jfloat scaleX, + jfloat scaleY) { + PIX *pixs = (PIX *) nativePix; + PIX *pixd = pixScale(pixs, (l_float32) scaleX, (l_float32) scaleY); + + return (jlong) pixd; +} + +/******** + * Skew * + ********/ + +jfloat Java_com_googlecode_leptonica_android_Skew_nativeFindSkew(JNIEnv *env, jclass clazz, + jlong nativePix, jfloat sweepRange, + jfloat sweepDelta, + jint sweepReduction, + jint searchReduction, + jfloat searchMinDelta) { + // Corrects the rotation of each element in pixa to 0 degrees. + + PIX *pixs = (PIX *) nativePix; + + l_float32 angle, conf; + + if (!pixFindSkewSweepAndSearch(pixs, &angle, &conf, (l_int32) sweepReduction, + (l_int32) searchReduction, (l_float32) sweepRange, + (l_int32) sweepDelta, (l_float32) searchMinDelta)) { + if (conf <= 0) { + return (jfloat) 0; + } + + return (jfloat) angle; + } + + return (jfloat) 0; +} + +/********** + * Rotate * + **********/ + +jlong Java_com_googlecode_leptonica_android_Rotate_nativeRotate(JNIEnv *env, jclass clazz, + jlong nativePix, jfloat degrees, + jboolean quality, jboolean resize) { + PIX *pixd; + PIX *pixs = (PIX *) nativePix; + + l_float32 deg2rad = 3.1415926535 / 180.0; + l_float32 radians = degrees * deg2rad; + l_int32 w, h, bpp, type; + + pixGetDimensions(pixs, &w, &h, &bpp); + + if (bpp == 1 && quality == JNI_TRUE) { + pixd = pixRotateBinaryNice(pixs, radians, L_BRING_IN_WHITE); + } else { + type = quality == JNI_TRUE ? L_ROTATE_AREA_MAP : L_ROTATE_SAMPLING; + w = (resize == JNI_TRUE) ? w : 0; + h = (resize == JNI_TRUE) ? h : 0; + pixd = pixRotate(pixs, radians, type, L_BRING_IN_WHITE, w, h); + } + + return (jlong) pixd; +} + +jlong Java_com_googlecode_leptonica_android_Rotate_nativeRotateOrth(JNIEnv *env, jclass clazz, + jlong nativePix, jint quads) { + + PIX *pixs = (PIX *) nativePix; + PIX *pixd; + pixd = pixRotateOrth(pixs,(int)quads); + return (jlong) pixd; +} + +#ifdef __cplusplus +} +#endif /* __cplusplus */ diff --git a/pool/shard001/C++/0022331_ScrollingCoordinatorBlackBerry.cpp b/pool/shard001/C++/0022331_ScrollingCoordinatorBlackBerry.cpp new file mode 100644 index 0000000000000000000000000000000000000000..39d902711c84184f55867c971fd680c685ad939e --- /dev/null +++ b/pool/shard001/C++/0022331_ScrollingCoordinatorBlackBerry.cpp @@ -0,0 +1,78 @@ +/* + * Copyright (C) 2013 Research In Motion Limited. 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 "ScrollingCoordinatorBlackBerry.h" + +#include "Frame.h" +#include "FrameView.h" +#include "LayerWebKitThread.h" +#include "Page.h" +#include "PlatformLayer.h" +#include "RenderLayerCompositor.h" +#include "RenderView.h" + +namespace WebCore { + +ScrollingCoordinatorBlackBerry::ScrollingCoordinatorBlackBerry(Page* page) + : ScrollingCoordinator(page) +{ +} + +void ScrollingCoordinatorBlackBerry::setLayerIsContainerForFixedPositionLayers(GraphicsLayer* layer, bool isContainer) +{ + // We don't want to set this for the main frame, the main frame would be treated like a subframe + // by the LayerRenderer which would result in incorrect positioning. + if (m_page->mainFrame() && scrollLayerForFrameView(m_page->mainFrame()->view()) == layer) + isContainer = false; + + if (layer->platformLayer()) + layer->platformLayer()->setIsContainerForFixedPositionLayers(isContainer); +} + +void ScrollingCoordinatorBlackBerry::setLayerIsFixedToContainerLayer(GraphicsLayer* layer, bool isFixed) +{ + if (layer->platformLayer()) + layer->platformLayer()->setFixedPosition(isFixed); +} + +void ScrollingCoordinatorBlackBerry::setLayerFixedToContainerLayerEdge(GraphicsLayer* layer, bool fixedToTop, bool fixedToLeft) +{ + if (!layer->platformLayer()) + return; + + layer->platformLayer()->setFixedToTop(fixedToTop); + layer->platformLayer()->setFixedToLeft(fixedToLeft); +} + +void ScrollingCoordinatorBlackBerry::frameViewLayoutUpdated(FrameView* frameView) +{ + if (GraphicsLayer* scrollLayer = scrollLayerForFrameView(frameView)) { + scrollLayer->platformLayer()->setFrameContentsSize(frameView->contentsSize()); + scrollLayer->platformLayer()->setFrameVisibleRect(frameView->visibleContentRect()); + } +} + +} diff --git a/pool/shard001/C++/0022333_model.cpp b/pool/shard001/C++/0022333_model.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a8fbb6cf360b1642573f35f29a8bc89c67b39089 --- /dev/null +++ b/pool/shard001/C++/0022333_model.cpp @@ -0,0 +1,132 @@ +#include "model.h" +#include "material.h" +#include "mesh.h" + +#include +#include +#include + +Model::Model(const Matrix &transform, std::vector> &meshes) + : m_transform(transform), m_transform_is_dirty(true), m_scale(Vector3d(1, 1, 1)) +{ + for(auto &mesh : meshes) { + m_meshes.push_back(std::move(mesh)); + } +} + +Vector3d Model::min_bound() const +{ + Vector3d min(DBL_MAX, DBL_MAX, DBL_MAX); + + for(auto &mesh : m_meshes) { + for(auto &vertice : mesh->m_vertices) { + if(vertice.x() < min.x()) + min.x() = vertice.x(); + if(vertice.y() < min.y()) + min.y() = vertice.y(); + if(vertice.z() < min.z()) + min.z() = vertice.z(); + } + } + + return min; +} +Vector3d Model::max_bound() const +{ + Vector3d max(-DBL_MAX, -DBL_MAX, -DBL_MAX); + + for(auto &mesh : m_meshes) { + for(auto &vertice : mesh->m_vertices) { + if(vertice.x() > max.x()) + max.x() = vertice.x(); + if(vertice.y() > max.y()) + max.y() = vertice.y(); + if(vertice.z() > max.z()) + max.z() = vertice.z(); + } + } + + return max; +} + +void Model::set_translation(const Vector3d &translation) +{ + if(translation != m_translation) { + m_translation = translation; + m_transform_is_dirty = true; + } +} + +void Model::set_rotation(const Vector3d &rotation) +{ + if(rotation != m_rotation) { + m_rotation = rotation; + m_transform_is_dirty = true; + } +} + +void Model::set_scale(const Vector3d &scale) +{ + if(scale != m_scale) { + m_scale = scale; + m_transform_is_dirty = true; + } +} + +Vector3d Model::translation() const +{ + return m_translation; +} + +Vector3d Model::rotation() const +{ + return m_rotation; +} + +Vector3d Model::scale() const +{ + return m_scale; +} + +void Model::update_transform(bool force_update) +{ + if(m_transform_is_dirty || force_update) { + m_transform_is_dirty = false; + + Matrix scale_matrix; + Matrix rotation_x_matrix; + Matrix rotation_y_matrix; + Matrix rotation_z_matrix; + Matrix translation_matrix; + + Matrix::CreateScale(m_scale.x(), m_scale.y(), m_scale.z(), &scale_matrix); + Matrix::CreateRotationX(m_rotation.x(), &rotation_x_matrix); + Matrix::CreateRotationY(m_rotation.y(), &rotation_y_matrix); + Matrix::CreateRotationZ(m_rotation.z(), &rotation_z_matrix); + Matrix::CreateTranslation(m_translation, &translation_matrix); + + Matrix rotation_matrix = rotation_x_matrix * rotation_y_matrix * rotation_z_matrix; + + m_transform = scale_matrix * rotation_matrix * translation_matrix; + + for(auto &mesh : m_meshes) { + mesh->transform_vertices(m_transform, rotation_matrix); // TODO: Hur hanteras skalning med normaler? Är translation det enda som ska ur transformen? + } + } +} + +void Model::print_memory_usage() const +{ + size_t size = sizeof(Model); + std::set materials; + size_t materials_size = 0; + + for(auto &mesh : m_meshes) { + size += mesh->memory_size(); + if(materials.insert(mesh->m_material.get()).second) { + materials_size += mesh->m_material->memory_size(); + } + } + + std::cout << "Memory usage: " << size / (1024*1024) << " Mb. Materials: " << materials_size / (1024*1024) << " Mb.\n"; +} \ No newline at end of file diff --git a/pool/shard001/C++/0022341_bounding_sphere.cpp b/pool/shard001/C++/0022341_bounding_sphere.cpp new file mode 100644 index 0000000000000000000000000000000000000000..260690e1cdfd19b22bbd0e26604ddb11070b7ae4 --- /dev/null +++ b/pool/shard001/C++/0022341_bounding_sphere.cpp @@ -0,0 +1,173 @@ +// Copyright mogemimi. Distributed under the MIT license. + +#include "pomdog/math/bounding_sphere.h" +#include "pomdog/basic/conditional_compilation.h" +#include "pomdog/math/bounding_box.h" +#include "pomdog/math/containment_type.h" +#include "pomdog/math/plane.h" +#include "pomdog/math/ray.h" +#include "pomdog/utility/assert.h" + +POMDOG_SUPPRESS_WARNINGS_GENERATED_BY_STD_HEADERS_BEGIN +#include +POMDOG_SUPPRESS_WARNINGS_GENERATED_BY_STD_HEADERS_END + +namespace pomdog { + +BoundingSphere::BoundingSphere(const Vector3& center, float radius) + : Center(center) + , Radius(radius) +{ + POMDOG_ASSERT(radius >= 0); +} + +ContainmentType BoundingSphere::Contains(const Vector3& point) const +{ + auto distanceSquared = math::DistanceSquared(point, Center); + auto radiusSquared = Radius * Radius; + if (distanceSquared > radiusSquared) { + return ContainmentType::Disjoint; + } + else if (distanceSquared < radiusSquared) { + return ContainmentType::Contains; + } + return ContainmentType::Intersects; +} + +ContainmentType BoundingSphere::Contains(const BoundingBox& box) const +{ + bool inside = true; + for (auto& corner : box.GetCorners()) { + if (this->Contains(corner) == ContainmentType::Disjoint) { + inside = false; + break; + } + } + if (inside) { + return ContainmentType::Contains; + } + if (this->Intersects(box)) { + return ContainmentType::Intersects; + } + return ContainmentType::Disjoint; +} + +ContainmentType BoundingSphere::Contains(const BoundingSphere& sphere) const +{ + auto distance = math::Distance(this->Center, sphere.Center); + if (distance > this->Radius + sphere.Radius) { + return ContainmentType::Disjoint; + } + if (distance + sphere.Radius < this->Radius) { + return ContainmentType::Contains; + } + return ContainmentType::Intersects; +} + +bool BoundingSphere::Intersects(const BoundingBox& box) const +{ + return box.Intersects(*this); +} + +bool BoundingSphere::Intersects(const BoundingSphere& sphere) const +{ + auto distance = math::Distance(this->Center, sphere.Center); + return distance <= this->Radius + sphere.Radius; +} + +PlaneIntersectionType BoundingSphere::Intersects(const Plane& plane) const +{ + return plane.Intersects(*this); +} + +std::optional BoundingSphere::Intersects(const Ray& ray) const +{ + return ray.Intersects(*this); +} + +BoundingSphere +BoundingSphere::CreateFromPoints(const Vector3* points, std::size_t pointCount) noexcept +{ + POMDOG_ASSERT(points != nullptr); + POMDOG_ASSERT(pointCount > 0); + auto accessor = [&](std::size_t i) -> Vector3 { return points[i]; }; + return CreateFromPoints(std::move(accessor), pointCount); +} + +BoundingSphere +BoundingSphere::CreateFromPoints(std::function points, std::size_t pointCount) noexcept +{ + POMDOG_ASSERT(points != nullptr); + POMDOG_ASSERT(pointCount > 0); + + // NOTE: Compute bounding sphere using Jack Ritter's algorithm. + std::size_t maxX = 0; + std::size_t maxY = 0; + std::size_t maxZ = 0; + std::size_t minX = 0; + std::size_t minY = 0; + std::size_t minZ = 0; + + for (std::size_t i = 0; i < pointCount; i++) { + const auto& p = points(i); + if (p.X < points(minX).X) { + minX = i; + } + if (p.X > points(maxX).X) { + maxX = i; + } + if (p.Y < points(minY).Y) { + minY = i; + } + if (p.Y > points(maxY).Y) { + maxY = i; + } + if (p.Z < points(minZ).Z) { + minZ = i; + } + if (p.Z > points(maxZ).Z) { + maxZ = i; + } + } + + const auto distX = math::DistanceSquared(points(maxX), points(minX)); + const auto distY = math::DistanceSquared(points(maxY), points(minY)); + const auto distZ = math::DistanceSquared(points(maxZ), points(minZ)); + + std::size_t max = maxX; + std::size_t min = minX; + if (distY > distX && distY > distZ) { + max = maxY; + min = minY; + } + else if (distZ > distX && distZ > distY) { + max = maxZ; + min = minZ; + } + + auto center = (points(max) + points(min)) * 0.5f; + auto radius = math::Distance(points(max), center); + auto radiusSq = radius * radius; + + // NOTE: Compute strict bounding sphere. + for (std::size_t i = 0; i < pointCount; i++) { + const auto p = points(i); + const auto diff = p - center; + const auto distanceSq = math::LengthSquared(diff); + if (distanceSq > radiusSq) { + const auto distance = std::sqrt(distanceSq); + const auto direction = diff / distance; + const auto g = center - radius * direction; + center = (g + p) * 0.5f; + radius = math::Distance(p, center); + radiusSq = radius * radius; + } + } + + BoundingSphere sphere; + sphere.Center = center; + sphere.Radius = radius; + return sphere; +} + +} // namespace pomdog diff --git a/pool/shard001/C++/0022343_General.cpp b/pool/shard001/C++/0022343_General.cpp new file mode 100644 index 0000000000000000000000000000000000000000..314a4bbfa068a161014ec7c642a345bd8faf0102 --- /dev/null +++ b/pool/shard001/C++/0022343_General.cpp @@ -0,0 +1,42 @@ + +/** + * General Setting + * ----------------------------------------- + * + * - Define view + * - Set/get General Settings + * - Define device of cue etc + * + * @author Victor Algaba + */ + + + + +#include +#include "General.h" +#include "bass.h" + +General::General(QDialog *parent ) + :QDialog(parent) +{ + setupUi(this); + setModal(true); + + #ifdef Q_OS_WIN32 + setWindowFlags( Qt::Tool); + #endif + + //define size of form + QSize fixedSize(this->width(),this->height()); + setMinimumSize(fixedSize); + setMaximumSize(fixedSize); + setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed); + + listWidget->setCurrentRow(0); + // stackedWidget->setCurrentIndex(0); + + + // connect(BtnSalir,SIGNAL(clicked()),this, SLOT(ClickSalir())); + +} diff --git a/pool/shard001/C++/0022356_local_ntp_browsertest.cc b/pool/shard001/C++/0022356_local_ntp_browsertest.cc new file mode 100644 index 0000000000000000000000000000000000000000..5201abc658c2c00f52d66f7382359e0000d398e8 --- /dev/null +++ b/pool/shard001/C++/0022356_local_ntp_browsertest.cc @@ -0,0 +1,88 @@ +// 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 "base/prefs/pref_service.h" +#include "base/strings/utf_string_conversions.h" +#include "chrome/browser/browser_process.h" +#include "chrome/browser/search/search.h" +#include "chrome/browser/ui/search/instant_test_utils.h" +#include "chrome/browser/ui/tabs/tab_strip_model.h" +#include "chrome/common/pref_names.h" +#include "chrome/common/url_constants.h" +#include "chrome/test/base/in_process_browser_test.h" +#include "chrome/test/base/ui_test_utils.h" +#include "content/public/browser/web_contents.h" +#include "ui/base/resource/resource_bundle.h" + +class LocalNTPTest : public InProcessBrowserTest, + public InstantTestBase { + public: + LocalNTPTest() {} + + protected: + virtual void SetUpInProcessBrowserTestFixture() OVERRIDE { + chrome::EnableInstantExtendedAPIForTesting(); + ASSERT_TRUE(https_test_server().Start()); + GURL instant_url = https_test_server().GetURL( + "files/local_ntp_browsertest.html?strk=1&"); + InstantTestBase::Init(instant_url); + } +}; + +IN_PROC_BROWSER_TEST_F(LocalNTPTest, LocalNTPJavascriptTest) { + ASSERT_NO_FATAL_FAILURE(SetupInstant(browser())); + FocusOmniboxAndWaitForInstantNTPSupport(); + + ui_test_utils::NavigateToURLWithDisposition( + browser(), + instant_url(), + NEW_FOREGROUND_TAB, + ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB | + ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION); + content::WebContents* active_tab = + browser()->tab_strip_model()->GetActiveWebContents(); + ASSERT_TRUE(chrome::IsInstantNTP(active_tab)); + bool success = false; + ASSERT_TRUE(GetBoolFromJS(active_tab, "!!runTests()", &success)); + EXPECT_TRUE(success); +} + +// Flaky on Linux Tests bot. +#if defined(OS_LINUX) +#define MAYBE_NTPRespectsBrowserLanguageSetting DISABLED_NTPRespectsBrowserLanguageSetting +#else +#define MAYBE_NTPRespectsBrowserLanguageSetting NTPRespectsBrowserLanguageSetting +#endif +IN_PROC_BROWSER_TEST_F(LocalNTPTest, MAYBE_NTPRespectsBrowserLanguageSetting) { + // Make sure the default language is not French. + std::string default_locale = g_browser_process->GetApplicationLocale(); + EXPECT_NE("fr", default_locale); + + // Switch browser language to French. + std::string loaded_locale = + ui::ResourceBundle::GetSharedInstance().ReloadLocaleResources("fr"); + EXPECT_EQ("fr", loaded_locale); + g_browser_process->SetApplicationLocale(loaded_locale); + PrefService* prefs = g_browser_process->local_state(); + prefs->SetString(prefs::kApplicationLocale, loaded_locale); + + // Setup Instant. + ASSERT_NO_FATAL_FAILURE(SetupInstant(browser())); + + // The second argument says to use only the local overlay and NTP. + instant()->SetInstantEnabled(false, true); + FocusOmniboxAndWaitForInstantNTPSupport(); + + // Open a new tab. + ui_test_utils::NavigateToURLWithDisposition( + browser(), + GURL(chrome::kChromeUINewTabURL), + NEW_FOREGROUND_TAB, + ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB); + + // Verify that the NTP is in French. + content::WebContents* active_tab = + browser()->tab_strip_model()->GetActiveWebContents(); + EXPECT_EQ(ASCIIToUTF16("Nouvel onglet"), active_tab->GetTitle()); +} diff --git a/pool/shard001/C++/0022357_ClTransposeKernel.cpp b/pool/shard001/C++/0022357_ClTransposeKernel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bdce2a2f5cdbbdeacfc2e609b105dd4d807be075 --- /dev/null +++ b/pool/shard001/C++/0022357_ClTransposeKernel.cpp @@ -0,0 +1,124 @@ +/* + * Copyright (c) 2017-2021 Arm Limited. + * + * SPDX-License-Identifier: MIT + * + * 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 "src/gpu/cl/kernels/ClTransposeKernel.h" + +#include "arm_compute/core/CL/CLHelpers.h" +#include "arm_compute/core/CL/CLKernelLibrary.h" +#include "arm_compute/core/CL/ICLTensor.h" +#include "arm_compute/core/Helpers.h" +#include "arm_compute/core/TensorInfo.h" +#include "arm_compute/core/Utils.h" +#include "arm_compute/core/Validate.h" +#include "arm_compute/core/utils/misc/ShapeCalculator.h" +#include "src/core/CL/CLValidate.h" +#include "src/core/helpers/AutoConfiguration.h" +#include "src/core/helpers/WindowHelpers.h" +#include "support/Cast.h" +#include "support/StringSupport.h" + +namespace arm_compute +{ +namespace opencl +{ +namespace kernels +{ +ClTransposeKernel::ClTransposeKernel() +{ + _type = CLKernelType::ELEMENTWISE; +} + +void ClTransposeKernel::configure(const CLCompileContext &compile_context, const ITensorInfo *src, ITensorInfo *dst) +{ + ARM_COMPUTE_ERROR_ON_NULLPTR(src, dst); + + // Output auto initialization if not yet initialized + const TensorShape dst_shape = misc::shape_calculator::compute_transposed_shape(*src); + auto_init_if_empty(*dst, src->clone()->set_tensor_shape(dst_shape)); + + ARM_COMPUTE_ERROR_THROW_ON(ClTransposeKernel::validate(src, dst)); + auto padding_info = get_padding_info({ src, dst }); + + // Create kernel + const unsigned int vec_size_x = adjust_vec_size(max_cl_vector_width / src->element_size(), src->dimension(0)); + const int vec_size_x_leftovers = src->dimension(0) % vec_size_x; + const unsigned int vec_size_y = adjust_vec_size(max_cl_vector_width / src->element_size(), src->dimension(1)); + const int vec_size_y_leftovers = src->dimension(1) % vec_size_y; + + CLBuildOptions build_opts; + build_opts.add_option("-DDATA_TYPE_IN_BYTES=" + support::cpp11::to_string(src->element_size())); + build_opts.add_option("-DVEC_SIZE_X=" + support::cpp11::to_string(vec_size_x)); + build_opts.add_option("-DVEC_SIZE_LEFTOVER_X=" + support::cpp11::to_string(vec_size_x_leftovers)); + build_opts.add_option("-DVEC_SIZE_Y=" + support::cpp11::to_string(vec_size_y)); + build_opts.add_option("-DVEC_SIZE_LEFTOVER_Y=" + support::cpp11::to_string(vec_size_y_leftovers)); + + _kernel = create_kernel(compile_context, "transpose", build_opts.options()); + + // Configure kernel window + Window win = calculate_max_window(*src, Steps(vec_size_x, vec_size_y)); + ICLKernel::configure_internal(win, cl::NDRange(2, 8)); + ARM_COMPUTE_ERROR_ON(has_padding_changed(padding_info)); +} + +Status ClTransposeKernel::validate(const ITensorInfo *src, const ITensorInfo *dst) +{ + ARM_COMPUTE_RETURN_ERROR_ON_NULLPTR(src, dst); + ARM_COMPUTE_RETURN_ERROR_ON_F16_UNSUPPORTED(src); + ARM_COMPUTE_RETURN_ERROR_ON(src->data_type() == DataType::UNKNOWN); + ARM_COMPUTE_RETURN_ERROR_ON_MSG(src->num_dimensions() > 2, "Transpose up to 2-D src tensor is supported"); + + // Validate configured dst + if(dst->total_size() != 0) + { + const TensorInfo dst_info = src->clone()->set_tensor_shape(misc::shape_calculator::compute_transposed_shape(*src)); + ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_SHAPES(dst, &dst_info); + + ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_QUANTIZATION_INFO(src, dst); + ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(src, dst); + } + + return Status{}; +} + +void ClTransposeKernel::run_op(ITensorPack &tensors, const Window &window, cl::CommandQueue &queue) +{ + ARM_COMPUTE_ERROR_ON_UNCONFIGURED_KERNEL(this); + ARM_COMPUTE_ERROR_ON_MISMATCHING_WINDOWS(ICLKernel::window(), window); + + const auto src = utils::cast::polymorphic_downcast(tensors.get_const_tensor(TensorType::ACL_SRC)); + auto dst = utils::cast::polymorphic_downcast(tensors.get_tensor(TensorType::ACL_DST)); + + Window slice = window.first_slice_window_2D(); + + do + { + unsigned int idx = 0; + add_2D_tensor_argument(idx, src, slice); + add_2D_tensor_argument(idx, dst, slice); + enqueue(queue, *this, slice, lws_hint()); + } + while(window.slide_window_slice_2D(slice)); +} +} // namespace kernels +} // namespace opencl +} // namespace arm_compute \ No newline at end of file diff --git a/pool/shard001/C++/0022360_AlibavaTimeCutProcessor.cc b/pool/shard001/C++/0022360_AlibavaTimeCutProcessor.cc new file mode 100644 index 0000000000000000000000000000000000000000..977b11dab532d53430fdaea3d0909ae381d6fe96 --- /dev/null +++ b/pool/shard001/C++/0022360_AlibavaTimeCutProcessor.cc @@ -0,0 +1,163 @@ +/* + * Created by Eda Yildirim + * (2014 DESY) + * + * email:eda.yildirim@cern.ch + */ + + +// alibava includes ".h" +#include "AlibavaTimeCutProcessor.h" +#include "AlibavaRunHeaderImpl.h" +#include "AlibavaEventImpl.h" +#include "ALIBAVA.h" +#include "AlibavaPedNoiCalIOManager.h" + + +// marlin includes ".h" +#include "marlin/Processor.h" +#include "marlin/Exceptions.h" +#include "marlin/Global.h" + +#if defined(USE_AIDA) || defined(MARLIN_USE_AIDA) +// aida includes <.h> +#include +#include +#endif + +// lcio includes <.h> +#include +#include +#include +#include +#include +#include +#include + + +// ROOT includes ".h" +#include "TH1D.h" + +// system includes <> +#include +#include +#include +#include + +using namespace std; +using namespace lcio; +using namespace marlin; +using namespace alibava; + + +AlibavaTimeCutProcessor::AlibavaTimeCutProcessor () : +AlibavaBaseProcessor("AlibavaTimeCutProcessor"), +_timecutmin(0.0), +_timecutmax(100.0), +_numberOfMaskedEvents(0), +_hMaskedEventsNumberName("EventNumberOfMaskedEvents") +{ + + // modify processor description + _description = + "AlibavaTimeCutProcessor masks the events if their TDC time value is not in the range specified by TimeCutMin and TimeCutMax "; + + registerProcessorParameter ("TimeCutMin", + "The minimum tdc time that is acceptable to use that Event", + _timecutmin , float(0.0)); + + registerProcessorParameter ("TimeCutMax", + "The maximum tdc time that is acceptable to use that Event", + _timecutmax , float(100.0)); + +} + + +void AlibavaTimeCutProcessor::init () { + streamlog_out ( MESSAGE4 ) << "Running init" << endl; + + // this method is called only once even when the rewind is active + // usually a good idea to + printParameters (); + + +} +void AlibavaTimeCutProcessor::processRunHeader (LCRunHeader * rdr) { + streamlog_out ( MESSAGE4 ) << "Running processRunHeader" << endl; + + // Add processor name to the runheader + auto_ptr arunHeader ( new AlibavaRunHeaderImpl(rdr)) ; + arunHeader->addProcessor(type()); + + _numberOfMaskedEvents = 0; + + bookHistos(); +} + +void AlibavaTimeCutProcessor::processEvent (LCEvent * anEvent) { + + //if ( anEvent->getEventNumber() % 1000 == 0 ) + // streamlog_out ( MESSAGE4 ) << "Looping events "<getEventNumber() << endl; + + AlibavaEventImpl * alibavaEvent = static_cast (anEvent); + + float eventTime = alibavaEvent->getEventTime(); + //filling the TDC distr histo + TH1D * hTDC = dynamic_cast(_rootObjectMap["hTDC"]); + hTDC->Fill(eventTime); + + streamlog_out(DEBUG0)<<"Event Number: "<< anEvent->getEventNumber()<<" Event time: "< getTimeCutMax() ){ + streamlog_out(DEBUG0)<< "Event time is not in the specified range."<maskEvent(); + streamlog_out(DEBUG0)<<"The event masked!"<getEventNumber(); + + if (TH1D * histo = dynamic_cast(_rootObjectMap[_hMaskedEventsNumberName])) + histo->Fill(eventnum); + +} + + +void AlibavaTimeCutProcessor::bookHistos(){ + + AIDAProcessor::tree(this)->cd(this->name()); + + TH1D * _hMaskedEventsNumber = new TH1D (_hMaskedEventsNumberName.c_str(),"", 2, 0, 1000000); + _rootObjectMap.insert(make_pair(_hMaskedEventsNumberName, _hMaskedEventsNumber)); + _hMaskedEventsNumber->SetTitle("Event Number of Masked Events; Number of Entries;Event Number"); + + TH1D * hTDC = new TH1D ("hTDC","", 202, -1, 200); + _rootObjectMap.insert(make_pair("hTDC", hTDC)); + hTDC->SetTitle("TDC distribution amond all events; Time [ns]; Number of events"); + + streamlog_out ( MESSAGE1 ) << "End of Booking histograms. " << endl; +} + + diff --git a/pool/shard001/C++/0022368_output_custom_factory.cc b/pool/shard001/C++/0022368_output_custom_factory.cc new file mode 100644 index 0000000000000000000000000000000000000000..91692ebea10c3f3993222b4cdf2606fdbd049da1 --- /dev/null +++ b/pool/shard001/C++/0022368_output_custom_factory.cc @@ -0,0 +1,69 @@ +/** Copyright 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 Roland Olbricht et al. + * + * This file is part of Overpass_API. + * + * Overpass_API 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. + * + * Overpass_API is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with Overpass_API. If not, see . + */ + +#include "../frontend/output_handler_parser.h" +#include "output_custom.h" + + +#ifdef HAVE_CONFIG_H +#include +#undef VERSION +#endif + +#ifdef HAVE_CUSTOM_OUTPUT + + +class Output_Custom_Generator : public Output_Handler_Parser +{ +public: + Output_Custom_Generator() : Output_Handler_Parser("custom") {} + + Output_Handler* new_output_handler(const std::map< std::string, std::string >& input_params, + Tokenizer_Wrapper* token, Error_Output* error_output); + + static Output_Custom_Generator singleton; +}; + + +Output_Custom_Generator Output_Custom_Generator::singleton; + + +Output_Handler* Output_Custom_Generator::new_output_handler(const std::map< std::string, std::string >& input_params, + Tokenizer_Wrapper* token, Error_Output* error_output) +{ + std::map< std::string, std::string >::const_iterator redirect_it = input_params.find("redirect"); + + std::map< std::string, std::string >::const_iterator url_it = input_params.find("url"); + std::string url = (url_it == input_params.end() ? + "https://www.openstreetmap.org/browse/{{{type}}}/{{{id}}}" : url_it->second); + + std::map< std::string, std::string >::const_iterator template_it = input_params.find("template"); + std::string template_name = (template_it == input_params.end() ? "default.wiki" : template_it->second); + // sanity check for template_name + if (template_name.find("/") != std::string::npos) + { + if (error_output) + error_output->add_encoding_error("Parameter \"template\" must not contain slashes."); + template_name = ""; + } + + return new Output_Custom(redirect_it == input_params.end() || redirect_it->second != "no", + template_name, url); +} + +#endif diff --git a/pool/shard001/C++/0022372_sg_StereoSpatAlgorithm.cpp b/pool/shard001/C++/0022372_sg_StereoSpatAlgorithm.cpp new file mode 100644 index 0000000000000000000000000000000000000000..eca25aa17eccddc31773943386b489e6a029e5c7 --- /dev/null +++ b/pool/shard001/C++/0022372_sg_StereoSpatAlgorithm.cpp @@ -0,0 +1,152 @@ +/* + This file is part of SpatGRIS. + + Developers: Samuel Béland, Olivier Bélanger, Nicolas Masson + + SpatGRIS 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. + + SpatGRIS 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 SpatGRIS. If not, see . +*/ + +#include "sg_StereoSpatAlgorithm.hpp" +#include "sg_DummySpatAlgorithm.hpp" +#include "sg_StaticMap.hpp" +#include "sg_StrongArray.hpp" +#include "sg_TaggedAudioBuffer.hpp" + +//============================================================================== +void StereoSpatAlgorithm::updateSpatData(source_index_t const sourceIndex, SourceData const & sourceData) noexcept +{ + jassert(!isProbablyAudioThread()); + + if (sourceData.directOut) { + return; + } + + // using fast = juce::dsp::FastMathApproximations; + + auto & queue{ mData[sourceIndex].gainsQueue }; + auto * ticket{ queue.acquire() }; + auto & gains{ ticket->get() }; + + if (sourceData.position) { + auto const x{ std::clamp(sourceData.position->getCartesian().x, -1.0f, 1.0f) + * (1.0f - sourceData.azimuthSpan) }; + + auto const fromZeroToPi{ (x + 1.0f) * HALF_PI.get() }; + + auto const leftGain{ std::cos(fromZeroToPi) * 0.5f + 0.5f }; + auto const rightGain{ std::cos(PI.get() - fromZeroToPi) * 0.5f + 0.5f }; + + gains[0] = std::pow(leftGain, 0.5f); + gains[1] = std::pow(rightGain, 0.5f); + } else { + gains[0] = 0.0f; + gains[1] = 0.0f; + } + + queue.setMostRecent(ticket); +} + +//============================================================================== +void StereoSpatAlgorithm::process(AudioConfig const & config, + SourceAudioBuffer & sourcesBuffer, + SpeakerAudioBuffer & /*speakersBuffer*/, + juce::AudioBuffer & stereoBuffer, + SourcePeaks const & sourcePeaks, + [[maybe_unused]] SpeakersAudioConfig const * altSpeakerConfig) +{ + ASSERT_AUDIO_THREAD; + jassert(!altSpeakerConfig); + jassert(stereoBuffer.getNumChannels() == 2); + + auto const & gainInterpolation{ config.spatGainsInterpolation }; + auto const gainFactor{ std::pow(gainInterpolation, 0.1f) * 0.0099f + 0.99f }; + + auto const numSamples{ sourcesBuffer.getNumSamples() }; + for (auto const & source : config.sourcesAudioConfig) { + if (source.value.isMuted || source.value.directOut || sourcePeaks[source.key] < SMALL_GAIN) { + continue; + } + + auto & data{ mData[source.key] }; + + data.gainsQueue.getMostRecent(data.currentGains); + if (data.currentGains == nullptr) { + continue; + } + auto const & gains{ data.currentGains->get() }; + + auto & lastGains{ data.lastGains }; + auto const * inputSamples{ sourcesBuffer[source.key].getReadPointer(0) }; + + static constexpr std::array SPEAKERS{ 0, 1 }; + auto * const * const buffers{ stereoBuffer.getArrayOfWritePointers() }; + + for (auto const & speaker : SPEAKERS) { + auto & currentGain{ lastGains[speaker] }; + auto const & targetGain{ gains[speaker] }; + auto * outputSamples{ buffers[speaker] }; + if (gainInterpolation == 0.0f) { + // linear interpolation over buffer size + auto const gainSlope = (targetGain - currentGain) / narrow(numSamples); + if (targetGain < SMALL_GAIN && currentGain < SMALL_GAIN) { + // this is not going to produce any more sounds! + continue; + } + for (int sampleIndex{}; sampleIndex < numSamples; ++sampleIndex) { + currentGain += gainSlope; + outputSamples[sampleIndex] += inputSamples[sampleIndex] * currentGain; + } + } else { + // log interpolation with 1st order filter + for (int sampleIndex{}; sampleIndex < numSamples; ++sampleIndex) { + currentGain = targetGain + (currentGain - targetGain) * gainFactor; + if (currentGain < SMALL_GAIN && targetGain < SMALL_GAIN) { + // If the gain is near zero and the target gain is also near zero, this means that + // currentGain will no ever increase over this buffer + break; + } + outputSamples[sampleIndex] += inputSamples[sampleIndex] * currentGain; + } + } + } + } + + // Apply gain compensation. + auto const compensation{ std::pow(10.0f, (narrow(config.sourcesAudioConfig.size()) - 1.0f) * -0.005f) }; + stereoBuffer.applyGain(0, numSamples, compensation); +} + +//============================================================================== +juce::Array StereoSpatAlgorithm::getTriplets() const noexcept +{ + JUCE_ASSERT_MESSAGE_THREAD; + jassertfalse; + return juce::Array{}; +} + +//============================================================================== +std::unique_ptr StereoSpatAlgorithm::make(SpeakerSetup const & speakerSetup, + SourcesData const & sources) +{ + JUCE_ASSERT_MESSAGE_THREAD; + + return std::make_unique(speakerSetup, sources); +} + +//============================================================================== +StereoSpatAlgorithm::StereoSpatAlgorithm(SpeakerSetup const & speakerSetup, SourcesData const & sources) +{ + JUCE_ASSERT_MESSAGE_THREAD; + fixDirectOutsIntoPlace(sources, speakerSetup); +} diff --git a/pool/shard001/C++/0022376_conststr.cpp b/pool/shard001/C++/0022376_conststr.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9c2bc4887ead2a8afc37d1682856d78f6e9d0371 --- /dev/null +++ b/pool/shard001/C++/0022376_conststr.cpp @@ -0,0 +1,43 @@ +/* vim:ts=4:sw=4:et:sts=4: + * + * Copyright 2016 Thunder422. All rights reserved. + * Distributed under GNU General Public License Version 3 + * (See accompanying file LICENSE or ) + */ + +#include "code.h" +#include "conststr.h" +#include "executer.h" +#include "recreator.h" + + +WordType ConstStrDictionary::add(const std::string &string) +{ + auto entry = Dictionary::add(string); + if (!entry.exists) { + str_values.emplace_back(new std::string(string)); + } + return entry.operand; +} + + +void recreateConstStr(Recreator &recreator) +{ + auto string = std::string {'"'}; + for (auto c : recreator.getConstStrOperand()) { + string += c; + if (c == '"') { + string += c; + } + } + string += '"'; + recreator.push(string); +} + +void executeConstStr(Executer &executer) +{ + auto operand = executer.getOperand(); + executer.pushConstStr(operand); +} + +Code const_str_code {recreateConstStr, executeConstStr}; diff --git a/pool/shard001/C++/0022377_z3dprimitiverenderer.cpp b/pool/shard001/C++/0022377_z3dprimitiverenderer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ccb788e1cbbe0169354ae5a3cf494f056395c198 --- /dev/null +++ b/pool/shard001/C++/0022377_z3dprimitiverenderer.cpp @@ -0,0 +1,239 @@ +#include "zglew.h" +#include "z3dprimitiverenderer.h" + +#include "z3dmesh.h" +#include "z3dgpuinfo.h" + +Z3DPrimitiveRenderer::Z3DPrimitiveRenderer(QObject *parent) + : QObject(parent) + , m_rendererBase(NULL) + , m_initialized(false) + , m_needLighting(false) + , m_useDisplayList(false) + , m_respectRendererBaseCoordScale(true) + , m_hardwareSupportVAO(Z3DGpuInfoInstance.isVAOSupported()) + , m_VAO(0) + , m_pickingVAO(0) + , m_privateVAO(0) +{ +} + +Z3DPrimitiveRenderer::~Z3DPrimitiveRenderer() +{ +} + +void Z3DPrimitiveRenderer::initialize() +{ + if (m_initialized) { + LERROR() << getClassName() << "already initialized"; + return; + } + if (m_hardwareSupportVAO) { + glGenVertexArrays(1, &m_VAO); + glGenVertexArrays(1, &m_pickingVAO); + glGenVertexArrays(1, &m_privateVAO); + } +} + +void Z3DPrimitiveRenderer::deinitialize() +{ + if (!m_initialized) { + LERROR() << getClassName() << "not initialized"; + return; + } + if (m_hardwareSupportVAO) { + glDeleteVertexArrays(1, &m_VAO); + glDeleteVertexArrays(1, &m_pickingVAO); + glDeleteVertexArrays(1, &m_privateVAO); + } +} + +void Z3DPrimitiveRenderer::addParameter(ZParameter ¶) +{ + addParameter(¶); +} + +void Z3DPrimitiveRenderer::addParameter(ZParameter *para) +{ + m_parameters.push_back(para); +} + +std::vector Z3DPrimitiveRenderer::getParameters() +{ + return m_parameters; +} + +QString Z3DPrimitiveRenderer::generateHeader() +{ + return m_rendererBase->generateHeader(); +} + +void Z3DPrimitiveRenderer::renderScreenQuad(const Z3DShaderProgram &shader, bool depthAlwaysPass) +{ + if (!shader.isLinked()) + return; + + if (depthAlwaysPass) + glDepthFunc(GL_ALWAYS); + + if (m_hardwareSupportVAO) { + glBindVertexArray(m_privateVAO); + } + + GLfloat vertices[] = {-1.f, 1.f, 0.f, //top left corner + -1.f, -1.f, 0.f, //bottom left corner + 1.f, 1.f, 0.f, //top right corner + 1.f, -1.f, 0.f}; // bottom right rocner + GLint attr_vertex = shader.attributeLocation("attr_vertex"); + + GLuint bufObjects[1]; + glGenBuffers(1, bufObjects); + + glEnableVertexAttribArray(attr_vertex); + glBindBuffer(GL_ARRAY_BUFFER, bufObjects[0]); + glBufferData(GL_ARRAY_BUFFER, 3*4*sizeof(GLfloat), vertices, GL_STATIC_DRAW); + glVertexAttribPointer(attr_vertex, 3, GL_FLOAT, GL_FALSE, 0, 0); + + glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); + + glBindBuffer(GL_ARRAY_BUFFER, 0); + glDeleteBuffers(1, bufObjects); + + glDisableVertexAttribArray(attr_vertex); + + if (m_hardwareSupportVAO) { + glBindVertexArray(0); + } + + if (depthAlwaysPass) + glDepthFunc(GL_LESS); +} + +void Z3DPrimitiveRenderer::renderTriangleList(const Z3DShaderProgram &shader, const Z3DTriangleList &mesh) +{ + if (mesh.empty() || !shader.isLinked()) + return; + + const std::vector& vertices = mesh.getVertices(); + const std::vector& textureCoordinates1D = mesh.get1DTextureCoordinates(); + const std::vector& textureCoordinates2D = mesh.get2DTextureCoordinates(); + const std::vector& textureCoordinates3D = mesh.get3DTextureCoordinates(); + const std::vector& normals = mesh.getNormals(); + const std::vector& colors = mesh.getColors(); + const std::vector& triangleIndexes = mesh.getIndices(); + GLenum type = mesh.getTriangleListType(); + + if (m_hardwareSupportVAO) { + glBindVertexArray(m_privateVAO); + } + + GLint attr_vertex = shader.attributeLocation("attr_vertex"); + GLint attr_1dTexCoord0 = shader.attributeLocation("attr_1dTexCoord0"); + GLint attr_2dTexCoord0 = shader.attributeLocation("attr_2dTexCoord0"); + GLint attr_3dTexCoord0 = shader.attributeLocation("attr_3dTexCoord0"); + GLint attr_normal = shader.attributeLocation("attr_normal"); + GLint attr_color = shader.attributeLocation("attr_color"); + + GLsizei bufObjectsSize = 1; // vertex + if (attr_1dTexCoord0 != -1 && !textureCoordinates1D.empty()) + bufObjectsSize++; + if (attr_2dTexCoord0 != -1 && !textureCoordinates2D.empty()) + bufObjectsSize++; + if (attr_3dTexCoord0 != -1 && !textureCoordinates3D.empty()) + bufObjectsSize++; + if (attr_normal != -1 && !normals.empty()) + bufObjectsSize++; + if (attr_color != -1 && !colors.empty()) + bufObjectsSize++; + if (!triangleIndexes.empty()) + bufObjectsSize++; + + GLuint *bufObjects = new GLuint[bufObjectsSize]; + glGenBuffers(bufObjectsSize, bufObjects); + + int bufIdx = 0; + glEnableVertexAttribArray(attr_vertex); + glBindBuffer(GL_ARRAY_BUFFER, bufObjects[bufIdx++]); + glBufferData(GL_ARRAY_BUFFER, vertices.size()*3*sizeof(GLfloat), &(vertices[0]), GL_STATIC_DRAW); + glVertexAttribPointer(attr_vertex, 3, GL_FLOAT, GL_FALSE, 0, 0); + + if (attr_1dTexCoord0 != -1 && !textureCoordinates1D.empty()) { + glEnableVertexAttribArray(attr_1dTexCoord0); + glBindBuffer(GL_ARRAY_BUFFER, bufObjects[bufIdx++]); + glBufferData(GL_ARRAY_BUFFER, textureCoordinates1D.size()*1*sizeof(GLfloat), &(textureCoordinates1D[0]), GL_STATIC_DRAW); + glVertexAttribPointer(attr_1dTexCoord0, 1, GL_FLOAT, GL_FALSE, 0, 0); + } + + if (attr_2dTexCoord0 != -1 && !textureCoordinates2D.empty()) { + glEnableVertexAttribArray(attr_2dTexCoord0); + glBindBuffer(GL_ARRAY_BUFFER, bufObjects[bufIdx++]); + glBufferData(GL_ARRAY_BUFFER, textureCoordinates2D.size()*2*sizeof(GLfloat), &(textureCoordinates2D[0]), GL_STATIC_DRAW); + glVertexAttribPointer(attr_2dTexCoord0, 2, GL_FLOAT, GL_FALSE, 0, 0); + } + + if (attr_3dTexCoord0 != -1 && !textureCoordinates3D.empty()) { + glEnableVertexAttribArray(attr_3dTexCoord0); + glBindBuffer(GL_ARRAY_BUFFER, bufObjects[bufIdx++]); + glBufferData(GL_ARRAY_BUFFER, textureCoordinates3D.size()*3*sizeof(GLfloat), &(textureCoordinates3D[0]), GL_STATIC_DRAW); + glVertexAttribPointer(attr_3dTexCoord0, 3, GL_FLOAT, GL_FALSE, 0, 0); + } + + if (attr_normal != -1 && !normals.empty()) { + glEnableVertexAttribArray(attr_normal); + glBindBuffer(GL_ARRAY_BUFFER, bufObjects[bufIdx++]); + glBufferData(GL_ARRAY_BUFFER, normals.size()*3*sizeof(GLfloat), &(normals[0]), GL_STATIC_DRAW); + glVertexAttribPointer(attr_normal, 3, GL_FLOAT, GL_FALSE, 0, 0); + } + + if (attr_color != -1 && !colors.empty()) { + glEnableVertexAttribArray(attr_color); + glBindBuffer(GL_ARRAY_BUFFER, bufObjects[bufIdx++]); + glBufferData(GL_ARRAY_BUFFER, colors.size()*4*sizeof(GLfloat), &(colors[0]), GL_STATIC_DRAW); + glVertexAttribPointer(attr_color, 4, GL_FLOAT, GL_FALSE, 0, 0); + } + + if (triangleIndexes.empty()) { + glDrawArrays(type, 0, vertices.size()); + } else { + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bufObjects[bufIdx++]); + glBufferData(GL_ELEMENT_ARRAY_BUFFER, triangleIndexes.size()*sizeof(GLuint), &(triangleIndexes[0]), GL_STATIC_DRAW); + glDrawElements(type, triangleIndexes.size(), GL_UNSIGNED_INT, 0); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); + } + + glBindBuffer(GL_ARRAY_BUFFER, 0); + glDeleteBuffers(bufObjectsSize, bufObjects); + delete bufObjects; + + glDisableVertexAttribArray(attr_vertex); + if (attr_1dTexCoord0 != -1 && !textureCoordinates1D.empty()) + glDisableVertexAttribArray(attr_1dTexCoord0); + if (attr_2dTexCoord0 != -1 && !textureCoordinates2D.empty()) + glDisableVertexAttribArray(attr_2dTexCoord0); + if (attr_3dTexCoord0 != -1 && !textureCoordinates3D.empty()) + glDisableVertexAttribArray(attr_3dTexCoord0); + if (attr_normal != -1 && !normals.empty()) + glDisableVertexAttribArray(attr_normal); + if (attr_color != -1 && !colors.empty()) + glDisableVertexAttribArray(attr_color); + + if (m_hardwareSupportVAO) { + glBindVertexArray(0); + } +} + +void Z3DPrimitiveRenderer::invalidateOpenglRenderer() +{ + if (m_useDisplayList) + emit openglRendererInvalid(); +} + +void Z3DPrimitiveRenderer::invalidateOpenglPickingRenderer() +{ + if (m_useDisplayList) + emit openglPickingRendererInvalid(); +} + +void Z3DPrimitiveRenderer::coordScalesChanged() +{ +} diff --git a/pool/shard001/C++/0022380_TiledTileLayer.cpp b/pool/shard001/C++/0022380_TiledTileLayer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bfaeb4e34b22563d2964854ada9e88983fd9a63c --- /dev/null +++ b/pool/shard001/C++/0022380_TiledTileLayer.cpp @@ -0,0 +1,268 @@ +// Copyright (c) 2015 fjz13. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. +#include "MedusaPreCompiled.h" +#include "TiledTileLayer.h" +#include "Core/Compress/ZipReader.h" +#include "Core/Coder/Crypt/Base64Decoder.h" +#include "Core/Log/Log.h" +#include "TiledTilesetRef.h" +#include "TiledMap.h" +#include "Node/Layer/NormalLayer.h" +#include "TiledTileset.h" +#include "Node/NodeFactory.h" +#include "CoreLib/Common/pugixml/pugixml.hpp" +#include "TiledMapInstantiateInfo.h" +#include "Node/Input/InputDispatcher.h" + +MEDUSA_BEGIN; +TiledTileLayer::TiledTileLayer() +{ +} + +TiledTileLayer::~TiledTileLayer() +{ +} + +bool TiledTileLayer::Parse(const pugi::xml_node& node) +{ + RETURN_FALSE_IF_FALSE(ITiledLayer::Parse(node)); + + pugi::xml_node dataNode = node.child("data"); + StringRef encodingStr = dataNode.attribute("encoding").as_string(nullptr); + StringRef compressionStr = dataNode.attribute("compression").as_string(nullptr); + StringRef text = dataNode.child_value(); + uint jump = 0; + for (; jump < text.Length(); jump++) + { + BREAK_IF(StdString::IsAlpha(text[jump])); + } + + text = text.SubString(jump); //skip "\n " + + if (encodingStr == "base64") + { + Base64Decoder decoder; + MemoryData data = decoder.Code(text); + MemoryData resultData; + if (compressionStr == "gzip") + { +#ifdef MEDUSA_UNZIP + resultData = ZipReader::DecompressGZIP(data, mSize.Area() * sizeof(uint)); +#endif + + } + else if (compressionStr == "zlib") + { +#ifdef MEDUSA_ZLIB + // Use zlib to uncompress the tile layer into the temporary array of tiles. + uLongf outlen = mSize.Area() * sizeof(uint); + resultData = MemoryData::Alloc(outlen); + int err = uncompress(resultData.MutableData(), &outlen, data.Data(), data.Size()); + if (err != 0) + { + Log::FormatError("decompression error:{}", err); + return false; + } +#endif + } + else if (compressionStr.IsEmpty()) + { + resultData = data; + } + else + { + Log::FormatError("Unsupported compression type:{}", compressionStr.c_str()); + return false; + } + + const uint* buffer = (const uint*)resultData.Data(); + InitializeTiles(); + + //the decoded data is an array of 32 - bit integers. + uint tileCount = mSize.Area(); + FOR_EACH_UINT32(i, tileCount) + { + uint globalId = buffer[i]; + TiledTileRef& tileRef = MutableTile(i); + + const TiledTilesetRef* tilesetRef = mMap->FindTilesetContainsGlobalId(globalId); + tileRef.Initialize(Point2I(i%mSize.Width, AdjustY(i / mSize.Height)), globalId, tilesetRef); + tileRef.SetLayer(this); + } + } + else if (encodingStr == "csv") + { + int index = 0; + List outValues; + StringParser::SplitToValues(text, StringRef(","), outValues); + for (auto globalId : outValues) + { + TiledTileRef& tileRef = MutableTile(index); + const TiledTilesetRef* tileset = mMap->FindTilesetContainsGlobalId(globalId); + tileRef.Initialize(Point2I(index%mSize.Width, AdjustY(index / mSize.Height)), globalId, tileset); + tileRef.SetLayer(this); + ++index; + } + + } + else if (encodingStr == "xml") + { + int index = 0; + for (auto tileNode : node.children()) + { + uint globalId = tileNode.attribute("gid").as_uint(0); + TiledTileRef& tileRef = MutableTile(index); + const TiledTilesetRef* tileset = mMap->FindTilesetContainsGlobalId(globalId); + tileRef.Initialize(Point2I(index%mSize.Width, AdjustY(index / mSize.Height)), globalId, tileset); + tileRef.SetLayer(this); + ++index; + } + } + else + { + Log::FormatError("Unsupported encoding type:{}", encodingStr.c_str()); + return false; + } + + AnalyzeTiles(); + + return true; +} + +void TiledTileLayer::InitializeTiles() +{ + mTiles.ForceReserveCount(mSize.Area()); +} + +void TiledTileLayer::AnalyzeTiles() +{ + mHasSingleTexture = true; + TextureAtlasPage* uniqueTexturePage = nullptr; + + for (const auto& tileRef : mTiles) + { + auto* tile = tileRef.Tile(); + CONTINUE_IF_NULL(tile); + auto* texturePage = tile->Page(); + CONTINUE_IF_NULL(texturePage); + + if (uniqueTexturePage == nullptr) + { + uniqueTexturePage = texturePage; + } + else if (uniqueTexturePage != texturePage) + { + mHasSingleTexture = false; + return; + } + } + +} + +INode* TiledTileLayer::Instantiate(NodeInstantiateInfo* instantiateInfo /*= nullptr*/)const +{ + TiledMapInstantiateInfo* mapInstantiateInfo = (TiledMapInstantiateInfo*)instantiateInfo; + + InstantiateMode mode = InstantiateMode::None; + if (instantiateInfo != nullptr) + { + mode = instantiateInfo->Mode; + } + + if (mode == InstantiateMode::None) + { + mode = mInstantiateMode; //use config rendering mode + } + + if (!mHasSingleTexture) + { + mode = InstantiateMode::Sprite; + } + + + INode* curLayer = nullptr; + if (instantiateInfo != nullptr) + { + curLayer = instantiateInfo->ParentNode; + } + + if (curLayer == nullptr) + { + StringRef layerClassName = mInstantiateLayer; + if (layerClassName.IsEmpty()) + { + layerClassName = NormalLayer::ClassNameStatic(); + } + + curLayer = NodeFactory::Instance().Create(layerClassName); + } + + Point2I offset = Point2I::Zero; + if (instantiateInfo != nullptr) + { + offset = mapInstantiateInfo->Offset; + } + switch (mode) + { + case InstantiateMode::None: + case InstantiateMode::Mesh: + { + //create quad mesh + /*for (const auto& tileRef : mTiles) + { + + }*/ + } + + break; + case InstantiateMode::Sprite: + for (const auto& tileRef : mTiles) + { + INode* node = tileRef.Instantiate(instantiateInfo); + if (node != nullptr) + { + Point2I tilePos = tileRef.Position()+offset; + curLayer->AddChild(node); + Point2F pos = mPosition; + pos.X += tilePos.X*mMap->TileSize().Width; + pos.Y += tilePos.Y*mMap->TileSize().Height; //from top down + node->SetPosition(pos); + } + } + break; + default: + break; + } + + curLayer->SetName(mName); + curLayer->SetOpacity(mOpacity); + curLayer->SetState(mRunningState); + curLayer->SetVisible(mIsVisible); + curLayer->MutableInput().Enable(mInputEnabled); + + if (mapInstantiateInfo != nullptr&&mapInstantiateInfo->UpdateSize) + { + Size2F newSize = mMap->PixelSize(); + newSize.Width += mapInstantiateInfo->Offset.X*mMap->Width(); + newSize.Height += mapInstantiateInfo->Offset.Y*mMap->Height(); + curLayer->SetSize(newSize); + curLayer->SetStretch(Stretch::None); //not stretch + } + + +#ifdef MEDUSA_SCRIPT + if (!mScriptFile.IsEmpty()) + { + curLayer->TryAddScriptFile(mScriptFile); + } +#endif + + return curLayer; + +} + + + + +MEDUSA_END; \ No newline at end of file diff --git a/pool/shard001/C++/0022382_FailoverRouteTest.cpp b/pool/shard001/C++/0022382_FailoverRouteTest.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b1e2f4b492758584da1904840046d085192f6c6d --- /dev/null +++ b/pool/shard001/C++/0022382_FailoverRouteTest.cpp @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + */ +#include +#include + +#include + +#include "mcrouter/lib/McReply.h" +#include "mcrouter/lib/McRequest.h" +#include "mcrouter/lib/routes/FailoverRoute.h" +#include "mcrouter/lib/test/RouteHandleTestUtil.h" + +using namespace facebook::memcache; + +using std::make_shared; +using std::vector; + +TEST(failoverRouteTest, success) { + vector> test_handles{ + make_shared(GetRouteTestData(mc_res_found, "a")), + make_shared(GetRouteTestData(mc_res_found, "b")), + make_shared(GetRouteTestData(mc_res_found, "c")) + }; + + TestRouteHandle> rh( + get_route_handles(test_handles)); + + auto reply = rh.route(McRequest("0"), McOperation()); + EXPECT_TRUE(toString(reply.value()) == "a"); +} + +TEST(failoverRouteTest, once) { + vector> test_handles{ + make_shared(GetRouteTestData(mc_res_timeout, "a")), + make_shared(GetRouteTestData(mc_res_found, "b")), + make_shared(GetRouteTestData(mc_res_found, "c")) + }; + + TestRouteHandle> rh( + get_route_handles(test_handles)); + + auto reply = rh.route(McRequest("0"), McOperation()); + EXPECT_TRUE(toString(reply.value()) == "b"); +} + +TEST(failoverRouteTest, twice) { + vector> test_handles{ + make_shared(GetRouteTestData(mc_res_timeout, "a")), + make_shared(GetRouteTestData(mc_res_timeout, "b")), + make_shared(GetRouteTestData(mc_res_found, "c")) + }; + + TestRouteHandle> rh( + get_route_handles(test_handles)); + + auto reply = rh.route(McRequest("0"), McOperation()); + EXPECT_TRUE(toString(reply.value()) == "c"); +} + +TEST(failoverRouteTest, fail) { + vector> test_handles{ + make_shared(GetRouteTestData(mc_res_timeout, "a")), + make_shared(GetRouteTestData(mc_res_timeout, "b")), + make_shared(GetRouteTestData(mc_res_timeout, "c")) + }; + + TestRouteHandle> rh( + get_route_handles(test_handles)); + + auto reply = rh.route(McRequest("0"), McOperation()); + + /* Will return the last reply when ran out of targets */ + EXPECT_EQ(toString(reply.value()), "c"); +} diff --git a/pool/shard001/C++/0022383_moc_html5applicationviewer.cpp b/pool/shard001/C++/0022383_moc_html5applicationviewer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..89acf1e448903935be393019cbbd6cd109edc6c9 --- /dev/null +++ b/pool/shard001/C++/0022383_moc_html5applicationviewer.cpp @@ -0,0 +1,88 @@ +/**************************************************************************** +** Meta object code from reading C++ file 'html5applicationviewer.h' +** +** Created by: The Qt Meta Object Compiler version 67 (Qt 5.0.2) +** +** WARNING! All changes made in this file will be lost! +*****************************************************************************/ + +#include "../untitled/html5applicationviewer/html5applicationviewer.h" +#include +#include +#if !defined(Q_MOC_OUTPUT_REVISION) +#error "The header file 'html5applicationviewer.h' doesn't include ." +#elif Q_MOC_OUTPUT_REVISION != 67 +#error "This file was generated using the moc from 5.0.2. It" +#error "cannot be used with the include files from this version of Qt." +#error "(The moc has changed too much.)" +#endif + +QT_BEGIN_MOC_NAMESPACE +struct qt_meta_stringdata_Html5ApplicationViewer_t { + QByteArrayData data[1]; + char stringdata[24]; +}; +#define QT_MOC_LITERAL(idx, ofs, len) \ + Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ + offsetof(qt_meta_stringdata_Html5ApplicationViewer_t, stringdata) + ofs \ + - idx * sizeof(QByteArrayData) \ + ) +static const qt_meta_stringdata_Html5ApplicationViewer_t qt_meta_stringdata_Html5ApplicationViewer = { + { +QT_MOC_LITERAL(0, 0, 22) + }, + "Html5ApplicationViewer\0" +}; +#undef QT_MOC_LITERAL + +static const uint qt_meta_data_Html5ApplicationViewer[] = { + + // content: + 7, // revision + 0, // classname + 0, 0, // classinfo + 0, 0, // methods + 0, 0, // properties + 0, 0, // enums/sets + 0, 0, // constructors + 0, // flags + 0, // signalCount + + 0 // eod +}; + +void Html5ApplicationViewer::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) +{ + Q_UNUSED(_o); + Q_UNUSED(_id); + Q_UNUSED(_c); + Q_UNUSED(_a); +} + +const QMetaObject Html5ApplicationViewer::staticMetaObject = { + { &QWidget::staticMetaObject, qt_meta_stringdata_Html5ApplicationViewer.data, + qt_meta_data_Html5ApplicationViewer, qt_static_metacall, 0, 0} +}; + + +const QMetaObject *Html5ApplicationViewer::metaObject() const +{ + return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; +} + +void *Html5ApplicationViewer::qt_metacast(const char *_clname) +{ + if (!_clname) return 0; + if (!strcmp(_clname, qt_meta_stringdata_Html5ApplicationViewer.stringdata)) + return static_cast(const_cast< Html5ApplicationViewer*>(this)); + return QWidget::qt_metacast(_clname); +} + +int Html5ApplicationViewer::qt_metacall(QMetaObject::Call _c, int _id, void **_a) +{ + _id = QWidget::qt_metacall(_c, _id, _a); + if (_id < 0) + return _id; + return _id; +} +QT_END_MOC_NAMESPACE diff --git a/pool/shard001/C++/0022386_packet_peer.cpp b/pool/shard001/C++/0022386_packet_peer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..16c73c26e77fbc5dca5f4f11f3a5b985f4832aa6 --- /dev/null +++ b/pool/shard001/C++/0022386_packet_peer.cpp @@ -0,0 +1,295 @@ +/*************************************************************************/ +/* packet_peer.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2017 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 "packet_peer.h" + +#include "io/marshalls.h" +#include "project_settings.h" +/* helpers / binders */ + +PacketPeer::PacketPeer() { + + allow_object_decoding = false; + last_get_error = OK; +} + +void PacketPeer::set_allow_object_decoding(bool p_enable) { + + allow_object_decoding = p_enable; +} + +bool PacketPeer::is_object_decoding_allowed() const { + + return allow_object_decoding; +} + +Error PacketPeer::get_packet_buffer(PoolVector &r_buffer) const { + + const uint8_t *buffer; + int buffer_size; + Error err = get_packet(&buffer, buffer_size); + if (err) + return err; + + r_buffer.resize(buffer_size); + if (buffer_size == 0) + return OK; + + PoolVector::Write w = r_buffer.write(); + for (int i = 0; i < buffer_size; i++) + w[i] = buffer[i]; + + return OK; +} + +Error PacketPeer::put_packet_buffer(const PoolVector &p_buffer) { + + int len = p_buffer.size(); + if (len == 0) + return OK; + + PoolVector::Read r = p_buffer.read(); + return put_packet(&r[0], len); +} + +Error PacketPeer::get_var(Variant &r_variant) const { + + const uint8_t *buffer; + int buffer_size; + Error err = get_packet(&buffer, buffer_size); + if (err) + return err; + + return decode_variant(r_variant, buffer, buffer_size, NULL, allow_object_decoding); +} + +Error PacketPeer::put_var(const Variant &p_packet) { + + int len; + Error err = encode_variant(p_packet, NULL, len, !allow_object_decoding); // compute len first + if (err) + return err; + + if (len == 0) + return OK; + + uint8_t *buf = (uint8_t *)alloca(len); + ERR_FAIL_COND_V(!buf, ERR_OUT_OF_MEMORY); + err = encode_variant(p_packet, buf, len, !allow_object_decoding); + ERR_FAIL_COND_V(err, err); + + return put_packet(buf, len); +} + +Variant PacketPeer::_bnd_get_var() const { + Variant var; + get_var(var); + + return var; +}; + +Error PacketPeer::_put_packet(const PoolVector &p_buffer) { + return put_packet_buffer(p_buffer); +} +PoolVector PacketPeer::_get_packet() const { + + PoolVector raw; + last_get_error = get_packet_buffer(raw); + return raw; +} + +Error PacketPeer::_get_packet_error() const { + + return last_get_error; +} + +void PacketPeer::_bind_methods() { + + ClassDB::bind_method(D_METHOD("get_var"), &PacketPeer::_bnd_get_var); + ClassDB::bind_method(D_METHOD("put_var", "var"), &PacketPeer::put_var); + ClassDB::bind_method(D_METHOD("get_packet"), &PacketPeer::_get_packet); + ClassDB::bind_method(D_METHOD("put_packet", "buffer"), &PacketPeer::_put_packet); + ClassDB::bind_method(D_METHOD("get_packet_error"), &PacketPeer::_get_packet_error); + ClassDB::bind_method(D_METHOD("get_available_packet_count"), &PacketPeer::get_available_packet_count); + + ClassDB::bind_method(D_METHOD("set_allow_object_decoding", "enable"), &PacketPeer::set_allow_object_decoding); + ClassDB::bind_method(D_METHOD("is_object_decoding_allowed"), &PacketPeer::is_object_decoding_allowed); +}; + +/***************/ + +void PacketPeerStream::_set_stream_peer(REF p_peer) { + + ERR_FAIL_COND(p_peer.is_null()); + set_stream_peer(p_peer); +} + +void PacketPeerStream::_bind_methods() { + + ClassDB::bind_method(D_METHOD("set_stream_peer", "peer"), &PacketPeerStream::_set_stream_peer); + ClassDB::bind_method(D_METHOD("set_input_buffer_max_size", "max_size_bytes"), &PacketPeerStream::set_input_buffer_max_size); + ClassDB::bind_method(D_METHOD("set_output_buffer_max_size", "max_size_bytes"), &PacketPeerStream::set_output_buffer_max_size); + ClassDB::bind_method(D_METHOD("get_input_buffer_max_size"), &PacketPeerStream::get_input_buffer_max_size); + ClassDB::bind_method(D_METHOD("get_output_buffer_max_size"), &PacketPeerStream::get_output_buffer_max_size); +} + +Error PacketPeerStream::_poll_buffer() const { + + ERR_FAIL_COND_V(peer.is_null(), ERR_UNCONFIGURED); + + int read = 0; + Error err = peer->get_partial_data(&input_buffer[0], ring_buffer.space_left(), read); + if (err) + return err; + if (read == 0) + return OK; + + int w = ring_buffer.write(&input_buffer[0], read); + ERR_FAIL_COND_V(w != read, ERR_BUG); + + return OK; +} + +int PacketPeerStream::get_available_packet_count() const { + + _poll_buffer(); + + uint32_t remaining = ring_buffer.data_left(); + + int ofs = 0; + int count = 0; + + while (remaining >= 4) { + + uint8_t lbuf[4]; + ring_buffer.copy(lbuf, ofs, 4); + uint32_t len = decode_uint32(lbuf); + remaining -= 4; + ofs += 4; + if (len > remaining) + break; + remaining -= len; + ofs += len; + count++; + } + + return count; +} + +Error PacketPeerStream::get_packet(const uint8_t **r_buffer, int &r_buffer_size) const { + + ERR_FAIL_COND_V(peer.is_null(), ERR_UNCONFIGURED); + _poll_buffer(); + + int remaining = ring_buffer.data_left(); + ERR_FAIL_COND_V(remaining < 4, ERR_UNAVAILABLE); + uint8_t lbuf[4]; + ring_buffer.copy(lbuf, 0, 4); + remaining -= 4; + uint32_t len = decode_uint32(lbuf); + ERR_FAIL_COND_V(remaining < (int)len, ERR_UNAVAILABLE); + + ring_buffer.read(lbuf, 4); //get rid of first 4 bytes + ring_buffer.read(&input_buffer[0], len); // read packet + + *r_buffer = &input_buffer[0]; + r_buffer_size = len; + return OK; +} + +Error PacketPeerStream::put_packet(const uint8_t *p_buffer, int p_buffer_size) { + + ERR_FAIL_COND_V(peer.is_null(), ERR_UNCONFIGURED); + Error err = _poll_buffer(); //won't hurt to poll here too + + if (err) + return err; + + if (p_buffer_size == 0) + return OK; + + ERR_FAIL_COND_V(p_buffer_size < 0, ERR_INVALID_PARAMETER); + ERR_FAIL_COND_V(p_buffer_size + 4 > output_buffer.size(), ERR_INVALID_PARAMETER); + + encode_uint32(p_buffer_size, &output_buffer[0]); + uint8_t *dst = &output_buffer[4]; + for (int i = 0; i < p_buffer_size; i++) + dst[i] = p_buffer[i]; + + return peer->put_data(&output_buffer[0], p_buffer_size + 4); +} + +int PacketPeerStream::get_max_packet_size() const { + + return output_buffer.size(); +} + +void PacketPeerStream::set_stream_peer(const Ref &p_peer) { + + //ERR_FAIL_COND(p_peer.is_null()); + + if (p_peer.ptr() != peer.ptr()) { + ring_buffer.advance_read(ring_buffer.data_left()); // reset the ring buffer + }; + + peer = p_peer; +} + +void PacketPeerStream::set_input_buffer_max_size(int p_max_size) { + + //warning may lose packets + ERR_EXPLAIN("Buffer in use, resizing would cause loss of data"); + ERR_FAIL_COND(ring_buffer.data_left()); + ring_buffer.resize(nearest_shift(p_max_size + 4)); + input_buffer.resize(next_power_of_2(p_max_size + 4)); +} + +int PacketPeerStream::get_input_buffer_max_size() const { + + return input_buffer.size() - 4; +} + +void PacketPeerStream::set_output_buffer_max_size(int p_max_size) { + + output_buffer.resize(next_power_of_2(p_max_size + 4)); +} + +int PacketPeerStream::get_output_buffer_max_size() const { + + return output_buffer.size() - 4; +} + +PacketPeerStream::PacketPeerStream() { + + int rbsize = GLOBAL_GET("network/limits/packet_peer_stream/max_buffer_po2"); + + ring_buffer.resize(rbsize); + input_buffer.resize(1 << rbsize); + output_buffer.resize(1 << rbsize); +} diff --git a/pool/shard001/C++/0022393_marker.cpp b/pool/shard001/C++/0022393_marker.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f40d5effa8af1afabe82ad4c8af900fe12f73c41 --- /dev/null +++ b/pool/shard001/C++/0022393_marker.cpp @@ -0,0 +1,92 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * + * * + * Item marker interface program for EW-Database * + * Copyright (C) 2016 Łukasz "Kuszki" Dróżdż l.drozdz@openmailbox.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 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 http://www.gnu.org/licenses/. * + * * + * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +int main(int argc, char *argv[]) +{ + QCoreApplication a(argc, argv); int i = 0; + QFile Output; QTextStream Stream(&Output); + QUdpSocket* Socket = new QUdpSocket(&a); + QFile File(argv[1]); QByteArray Array; + QString Database; int Port(0); + + qsrand(QDateTime::currentMSecsSinceEpoch()); + Stream.setCodec(QTextCodec::codecForLocale()); + + if (File.open(QFile::ReadOnly | QFile::Text)) while (!File.atEnd()) + { + const QString Line = QString::fromLocal8Bit(File.readLine()); ++i; + + if (i == 2) + { + Output.setFileName(Line.trimmed()); + Output.open(QFile::WriteOnly | QFile::Text); + } + else if (i == 3) + { + Database = Line.trimmed(); + } + } + + if (!Database.isEmpty()) + { + QSettings Settings("EW-Database"); + Settings.beginGroup("Sockets"); + + for (const auto& K : Settings.childGroups()) if (!Port) + { + if (Database.contains(K, Qt::CaseInsensitive)) + { + Settings.beginGroup(K); + Port = Settings.value("marker").toInt(); + Settings.endGroup(); + } + } + + if (Port) while (!Socket->bind(QHostAddress::LocalHost, qrand() & 0xFFFF)); + } + + if (Output.isOpen()) + { + Socket->writeDatagram(QString::number(Socket->localPort()).toUtf8(), + QHostAddress::LocalHost, Port); + + Stream << "0 4\nKOD\n**\n"; + } + + a.connect(Socket, &QUdpSocket::readyRead, [&Socket, &Stream, &Array, &a] (void) -> void + { + Array.resize(Socket->pendingDatagramSize()); + Socket->readDatagram(Array.data(), Array.size()); + + Stream << Array; if (Array.endsWith("\n\n")) a.quit(); + }); + + QTimer::singleShot(10000, &a, &QCoreApplication::quit); return a.exec(); +} diff --git a/pool/shard001/C++/0022399_header_unittest.cc b/pool/shard001/C++/0022399_header_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..d0aba162eaaae374a323f73277c79ae3ecf0bcc5 --- /dev/null +++ b/pool/shard001/C++/0022399_header_unittest.cc @@ -0,0 +1,157 @@ +// 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/domain_reliability/header.h" + +#include "base/strings/string_number_conversions.h" +#include "base/strings/string_split.h" +#include "base/strings/stringprintf.h" +#include "components/domain_reliability/config.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace domain_reliability { +namespace { + +class DomainReliabilityHeaderTest : public testing::Test { + protected: + DomainReliabilityHeaderTest() {} + ~DomainReliabilityHeaderTest() override {} + + void Parse(std::string value) { + parsed_ = DomainReliabilityHeader::Parse(value); + } + + const DomainReliabilityHeader* parsed() const { return parsed_.get(); } + + private: + scoped_ptr parsed_; +}; + +bool CheckReportUris(const char* pipe_separated_expected_report_uris, + const ScopedVector& actual_report_uris) { + if (!pipe_separated_expected_report_uris) + return actual_report_uris.empty(); + + std::vector expected_report_uri_strings = + SplitString(pipe_separated_expected_report_uris, + "|", + base::KEEP_WHITESPACE, + base::SPLIT_WANT_ALL); + if (expected_report_uri_strings.size() != actual_report_uris.size()) + return false; + + for (size_t i = 0; i < actual_report_uris.size(); ++i) { + if (actual_report_uris[i]->spec() != expected_report_uri_strings[i]) + return false; + } + + return true; +} + +TEST_F(DomainReliabilityHeaderTest, SetConfig) { + static const struct { + const char* header; + const char* pipe_separated_report_uris; + int64_t max_age_in_seconds; + bool include_subdomains; + const char* description; + } test_cases[] = { + { "report-uri=https://a/; max-age=5", + "https://a/", 5, false, + "register" }, + { "report-uri=\"https://a/\"; max-age=5", + "https://a/", 5, false, + "register with quoted report-uri" }, + { "report-uri=; max-age=5", + "https://a/", 5, false, + "register with bracketed report-uri" }, + { "report-uri=https://a/ https://b/; max-age=5", + "https://a/|https://b/", 5, false, + "register with two report-uris" }, + { "report-uri=https://a/; max-age=5; includeSubdomains", + "https://a/", 5, true, + "register with includeSubdomains" }, + }; + + for (const auto& test_case : test_cases) { + std::string assert_prefix = base::StringPrintf( + "Valid set-config NEL header \"%s\" (%s) incorrectly parsed as ", + test_case.header, + test_case.description); + Parse(test_case.header); + EXPECT_FALSE(parsed()->IsParseError()) << assert_prefix << "invalid."; + EXPECT_FALSE(parsed()->IsClearConfig()) << assert_prefix << "clear-config."; + if (parsed()->IsParseError() || parsed()->IsClearConfig()) + continue; + EXPECT_TRUE(parsed()->IsSetConfig()); + + std::string assert_message = + assert_prefix + "\"" + parsed()->ToString() + "\""; + EXPECT_TRUE(CheckReportUris(test_case.pipe_separated_report_uris, + parsed()->config().collectors)) + << assert_message; + EXPECT_EQ(test_case.max_age_in_seconds, + parsed()->max_age().InSeconds()) + << assert_message; + EXPECT_EQ(test_case.include_subdomains, + parsed()->config().include_subdomains) + << assert_message; + } +} + +TEST_F(DomainReliabilityHeaderTest, ClearConfig) { + static const struct { + const char* header; + const char* description; + } test_cases[] = { + { "max-age=0", "unregister" }, + { "report-uri=https://a/; max-age=0", "unregister with report-uri" }, + { "max-age=0; includeSubdomains", "unregister with includeSubdomains" }, + }; + + for (const auto& test_case : test_cases) { + std::string assert_prefix = base::StringPrintf( + "Valid clear-config NEL header \"%s\" (%s) incorrectly parsed as ", + test_case.header, + test_case.description); + Parse(test_case.header); + EXPECT_FALSE(parsed()->IsParseError()) << assert_prefix << "invalid."; + EXPECT_FALSE(parsed()->IsSetConfig()) << assert_prefix << "set-config."; + } +} + +TEST_F(DomainReliabilityHeaderTest, Error) { + static const struct { + const char* header; + const char* description; + } test_cases[] = { + { "", "empty" }, + { "max-age=5", "report-uri missing with non-zero max-age" }, + { "report-uri; max-age=5", "report-uri has no value" }, + { "report-uri=; max-age=5", "report-uri value is empty" }, + { "report-uri=http://a/; max-age=5", "report-uri is insecure" }, + { "report-uri=https://a/ http://b/; max-age=5", + "one report-uri of two is insecure" }, + { "report-uri=\"https://a/; max-age=5", "report-uri is unbalanced" }, + { "report-uri=https://a/\"; max-age=5", "report-uri is unbalanced" }, + { "report-uri=; max-age=5", "report-uri is unbalanced" }, + { "report-uri=https://a/", "max-age is missing" }, + { "report-uri=https://a/; max-age", "max-age has no value" }, + { "report-uri=https://a/; max-age=", "max-age value is empty" }, + { "report-uri=https://a/; max-age=a", "max-age is entirely non-numeric" }, + { "report-uri=https://a/; max-age=5a", "max-age is partly non-numeric" }, + { "report-uri=https://a/; max-age=5 5", "max-age has multiple values" }, + }; + + for (const auto& test_case : test_cases) { + Parse(test_case.header); + EXPECT_TRUE(parsed()->IsParseError()) + << "Invalid NEL header \"" << test_case.header << "\" (" + << test_case.description << ") incorrectly parsed as valid."; + } +} + +} // namespace +} // namespace domain_reliability diff --git a/pool/shard001/C++/0022401_Calendar.cpp b/pool/shard001/C++/0022401_Calendar.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7c7edb8d119f280947454c6df1185d919029ef2c --- /dev/null +++ b/pool/shard001/C++/0022401_Calendar.cpp @@ -0,0 +1,141 @@ +#include +#include + +#include + +#include "Calendar.hpp" +#include "Config.hpp" + + +void fork_and_run(char* cmdline) +{ + if (strlen(cmdline)) { + if (fork() == 0) { + execl("/bin/sh", "/bin/sh", "-c", cmdline, NULL); + _exit(0); + } + } +} + +void monthChangedCb(GtkCalendar *calendar, gpointer cls) +{ + if (cls) { + ((Calendar*)cls)->markToday(); + } +} +void dayDoubleClickCb(GtkCalendar *calendar, gpointer cls) +{ + if (cls) { + ((Calendar*)cls)->runExternalViewer(); + } +} + + +Calendar::Calendar() +{ + widget = gtk_calendar_new(); + + Config* config = Config::getInstance(); + g_object_set(widget, + "show-heading", true, + "show-day-names", true, + "show-details", false, + "show-week-numbers", config->show_week_numbers, + NULL); + if (config->mark_today) { + // Store today date to be able to mark it after month changes. + gtk_calendar_get_date((GtkCalendar*)widget, + &today_year, &today_month, &today_day); + markToday(); + g_signal_connect(widget, "month-changed", + GCallback(monthChangedCb), (gpointer)this); + } + g_signal_connect(widget, "day-selected-double-click", + GCallback(dayDoubleClickCb), (gpointer)this); + + gtk_widget_show(widget); +} + +Calendar::~Calendar() +{ + gtk_widget_destroy(widget); +} + +void Calendar::nextYear() +{ + _change(1, 0); +} +void Calendar::prevYear() +{ + _change(-1, 0); +} + +void Calendar::nextMonth() +{ + _change(0, 1); +} +void Calendar::prevMonth() +{ + _change(0, -1); +} + +void Calendar::_change(int year_offset, int month_offset) +{ + int year, month; + gtk_calendar_get_date((GtkCalendar*)widget, (guint*)&year, (guint*)&month, NULL); + month += month_offset; + if (month > 11) { + month = 0; + year_offset++; + } else if (month < 0) { + month = 11; + year_offset--; + } + year += year_offset; + gtk_calendar_select_month((GtkCalendar*)widget, (guint)month, (guint)year); +} + +bool Calendar::markToday() +{ + guint year, month; + gtk_calendar_get_date((GtkCalendar*)widget, &year, &month, NULL); + if (year == today_year && month == today_month) { + gtk_calendar_mark_day((GtkCalendar*)widget, today_day); + return true; + } else { + gtk_calendar_unmark_day((GtkCalendar*)widget, today_day); + return false; + } +} + +void Calendar::goToday() +{ + gtk_calendar_select_month((GtkCalendar*)widget, today_month, today_year); + gtk_calendar_select_day((GtkCalendar*)widget, today_day); +} + +bool Calendar::runExternalViewer() +{ + Config* config = Config::getInstance(); + size_t len = config->external_viewer.length(); + if (len > 0) { + int year, month, day; + gtk_calendar_get_date((GtkCalendar*)widget, + (guint*)&year, (guint*)&month, (guint*)&day); + struct tm date; + date.tm_year = year - 1900; + date.tm_mon = month; + date.tm_mday = day; + date.tm_sec = date.tm_min = date.tm_hour = date.tm_wday + = date.tm_yday = date.tm_isdst = 0; + + size_t buf_size = len + 64; + char* cmd = new char[buf_size]; + strftime(cmd, buf_size, config->external_viewer.c_str(), &date); + fork_and_run(cmd); + delete[] cmd; + return true; + } else { + return false; + } +} diff --git a/pool/shard001/C++/0022405_graph.cpp b/pool/shard001/C++/0022405_graph.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2d210c65bad94f5ddacb5e38ab3c9a5da5174516 --- /dev/null +++ b/pool/shard001/C++/0022405_graph.cpp @@ -0,0 +1,55 @@ +#include "graph.h" + +Graph::Graph() { + int i, j; + for(i = 0; i < 250; ++i) + for(j = 0; j < 250; ++j) + matriz[i][j] = ' '; +} + +void Graph::addVvertex(char data, int i, int j) { + matriz[i][j] = data; +} + +void Graph::clear() { + int i, j; + for(i = 0; i < 250; ++i) + for(j = 0; j < 250; ++j) + matriz[i][j] = ' '; +} + +char Graph::getValue(int i, int j) { + return matriz[i][j]; +} + +void Graph::setValue(char data, int i, int j) { + matriz[i][j] = data; +} + +int Graph::getManhattanHeuristic(int i, int j) { + return 10*(fabs(xFim - i) + fabs(yFim - j)); +} + +void Graph::setInit(int i, int j) { + xInicio = i; + yInicio = j; +} + +void Graph::setEnd(int i, int j) { + xFim = i; + yFim = j; +} + +int *Graph::getInit() { + int *pos = new int[2]; + pos[0] = xInicio; + pos[1] = yInicio; + return pos; +} + +int *Graph::getEnd() { + int *pos = new int[2]; + pos[0] = xFim; + pos[1] = yFim; + return pos; +} diff --git a/pool/shard001/C++/0022410_main.cpp b/pool/shard001/C++/0022410_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b470aa65e8561d821063733f2f298d91c2fc35eb --- /dev/null +++ b/pool/shard001/C++/0022410_main.cpp @@ -0,0 +1,201 @@ +#include +#include +#include "fbtext.h" +#include "fastmath.h" +#include "gps.h" +#include "page.h" +#include "laser.h" +#include "fbtimer.h" +#include "clockutil.h" +#include "celestial.h" +#include "gpio.h" +#include "keysin.h" +#include "uart.h" +#include "scroller.h" +#include "string.h" +#include "flare.h" +#include "flarelist.h" +#include "skyplot.h" +#include "p_config_int.h" +#include "p_config_long.h" +#include "p_config_bool.h" +#include "p_tracker.h" +#include "p_starfinder.h" +#include "p_planetfinder.h" +#include "p_info.h" +#include "p_debug.h" +#include "p_calibrate_coarse.h" +#include "p_calibrate_3star.h" + +FBTimer fbt; +CLaser* laser; +CPage* tracker_page; +CKeysIn* ki; +bool stepper_active_holding = false; +bool debug_flare_imminent = false; + +#ifdef NO_XPORT +unsigned short pwm_values[PWM_NUM/2]; +unsigned short gpio_directions[(GPIO_NUM+15)/16]; +unsigned short gpio_values[(GPIO_NUM+15)/16]; +#endif + + +class DisplayUpdateTimerEvent : public FBTimerEvent { +public: + DisplayUpdateTimerEvent() : FBTimerEvent(0, 0, 0, 512) {} + virtual void Run(FBTimer* timer) { + long secs = timer->GetTimeSeconds(); + long difftime = secs - event_time_secs; + if (difftime > 1 || difftime < -1) { + SetNextScheduledTime(secs + 1, 0); + } + UpdateTimeLeftClockDisplay(false); + } +} display_updater; + + +class TurretUpdateTimerEvent : public FBTimerEvent { +public: + TurretUpdateTimerEvent() : FBTimerEvent(0, 0, 0, 64) {} + + virtual void Run(FBTimer* timer) { + long secs = timer->GetTimeSeconds(); + long difftime = secs - event_time_secs; + if (difftime > 1 || difftime < -1) { + SetNextScheduledTime(secs + 1, 0); + } + TurretPoll(); + } + +} turret_updater; + + +extern "C" +int main(void) +{ + txtClear(); + + // Create menus + txtPrint("Creating menus.\n"); + + main_menu_page = new CMenuPage("Main Menu"); + tracker_page = new CTrackerPage("Flare Tracker"); + CMenuPage* calib_menu_page = new CMenuPage("Calibration"); + CMenuPage* config_menu_page = new CMenuPage("Settings"); + CPage* calib_3star_page = new CCalibrate3StarPage("3-Star Calibration"); + + main_menu_page->AddItem(tracker_page); + main_menu_page->AddItem(new CStarFinderPage("Star Finder")); + main_menu_page->AddItem(new CPlanetFinderPage("Planet Finder")); + main_menu_page->AddItem(calib_menu_page); + main_menu_page->AddItem(new CInfoPage("Info Page")); + main_menu_page->AddItem(config_menu_page); + main_menu_page->AddItem(new CDebugPage("Debug Page")); + + calib_menu_page->AddItem(new CCalibrateCoarsePage("Coarse Calibration")); + calib_menu_page->AddItem(calib_3star_page); + + config_menu_page->AddItem(new CConfigIntPage("Day Clock Brightness", &daytime_clock_pwm, 0, 255)); + config_menu_page->AddItem(new CConfigIntPage("Night Clock Brightness", &nighttime_clock_pwm, 0, 255)); + config_menu_page->AddItem(new CConfigIntPage("Slow Laser Table Speed", &turret_speed_low, 1, 100)); + config_menu_page->AddItem(new CConfigIntPage("Fast Laser Table Speed", &turret_speed_high, 1, 100)); + config_menu_page->AddItem(new CConfigBoolPage("Active Stepper Holding", &stepper_active_holding)); + config_menu_page->AddItem(new CConfigBoolPage("Make Imminent Flare", &debug_flare_imminent)); + config_menu_page->AddItem(new CConfigLongPage("Laser Azimuth Backlash", &turret_azimuth_backlash, 1, 9999)); + config_menu_page->AddItem(new CConfigLongPage("Laser Altitude Backlash", &turret_altitude_backlash, 1, 9999)); + + current_page = tracker_page; + + + // set first 31 GPIO bits to output + GPIO_DDR(0) = 0xffff; + GPIO_DDR(1) = 0x0fff; + GPIO_DDR(2) = 0x0f00; + GPIO_DATA(0) = 0x0000; + GPIO_DATA(1) = 0x0000; + GPIO_DATA(2) = 0x0000; + GpioSetDirOutbound(FLARE_ALERT_PIN, true); + GpioSetDirOutbound(KLAXON_PIN, true); + + // Clock brightness. + PWM_DATA(0) = 0x0f00; + + fm_benchmark(); + + txtPrint("Init GPS Serial link.\n"); + gps_uart.SetBaudRate(4800); +#ifdef NO_XPORT + gps_uart.ReadBufStuff("$GPRMC,071458,A,3714.1938,N,12153.8619,W,0.0,241.0,070804,14.9,E,A*36\r\n"); +#endif + + txtPrint("Init Turret Serial link.\n"); + turret_uart.SetBaudRate(9600); + millisleep(128); + turret_uart.WriteString("4!"); + millisleep(512); + turret_uart.WriteString("0H"); + millisleep(128); + turret_uart.WriteString("3O"); + millisleep(128); + turret_uart.WriteString("B32000P"); + + txtPrint("Init Scroller Serial link.\n"); + scroller_uart.SetBaudRate(9600); + millisleep(128); + scroller.PageWrite(1, 0, SC_COLOR_LIME, "C.L.I.V.E. v2.0CelestialLaserIdentification /VisualisationExperiment"); + sleep(1); + scroller.Init(1); + sleep(3); + + txtPrint("Init keypads.\n"); + ki = new CKeysIn(); + + txtPrint("Init sky object caches.\n"); + InitSkyCaches(); + + txtPrint("Test clock digits.\n"); + scroller.PageWrite(1, 0, SC_COLOR_BRIGHT_GREEN, "Initialize Clock"); + sleep(1); + TestClockDisplay(); + fbt.ScheduleEvent(&display_updater); + + txtPrint("Init laser table.\n"); + scroller.PageWrite(1, 0, SC_COLOR_BRIGHT_GREEN, "Initialize Laser"); + fbt.ScheduleEvent(&turret_updater); + sleep(2); + laser = new CLaser(); + laser->SetBeamState(BEAM_ON); + + scroller.PageWrite(1, 0, SC_COLOR_BRIGHT_GREEN, "Initialize GPS"); + sleep(3); + txtClear(); + + long seconds = 0; + long lastseconds = 0; + while (1) { + GetGpsInfoFromSerial(); + UpdateSkyCaches(); + laser->SetActiveHolding(stepper_active_holding); + if (debug_flare_imminent) { + debug_flare_imminent = false; + delete FlareList[0]; + FlareList[0] = new CFlare(seconds + 135, 0, 45.0, 45.0, 0); + nextflare = NULL; + } + CheckForNextFlare(laser); + ki->Poll(); + HandleKeys(); + seconds = time(); + if (seconds != lastseconds) { + if ((seconds & 0x0fff) == 0) { // Every 1h 8m 16s + UpdateSunRiseSet(seconds, my_latitude, my_longitude); + } + UpdateClockBrightness(); + UpdateDisplay(); + lastseconds = seconds; + } + } +} + + diff --git a/pool/shard001/C++/0022411_document.cc b/pool/shard001/C++/0022411_document.cc new file mode 100644 index 0000000000000000000000000000000000000000..fac7398855caa382c4d8b8d79586aaef2e64f909 --- /dev/null +++ b/pool/shard001/C++/0022411_document.cc @@ -0,0 +1,66 @@ +/* TODO : Manage File problems ! + */ +/* +** A program to convert the XML rendered by KWord into LATEX. +** +** Copyright (C) 2000, 2003 Robert JACOLIN +** +** 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. +** +** To receive a copy of the GNU Library General Public License, write to the +** Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. +** +*/ + +#include + +#include "document.h" + +Document::Document(const KoStore* in, QString fileOut): + XmlParser(in), _file(fileOut), _in( in ) +{ + //kDebug(30522) << fileIn; + kDebug(30522) << fileOut; + _filename = fileOut; + //setFileHeader(_fileHeader); + //setRoot(&_document); + Config::instance()->setEmbeded(false); + //analyze_config(config); +} + +Document::~Document() +{ + +} + +void Document::analyze() +{ + QDomNode node; + node = init(); + kDebug(30522) <<"ANALYZE A DOC"; + _document.analyze(node); + kDebug(30522) <<"END ANALYZE"; +} + +void Document::generate() +{ + if(_file.open(QIODevice::WriteOnly)) + { + kDebug(30522) <<"GENERATION"; + _out.setDevice(&_file); + _document.generate(_out, !isEmbeded()); + //_out << getDocument(); + _file.close(); + } + else + kDebug(30522) <<"Can't use the file ..."; +} diff --git a/pool/shard001/C++/0022414_initterm.cpp b/pool/shard001/C++/0022414_initterm.cpp new file mode 100644 index 0000000000000000000000000000000000000000..36ce4155e1cdf0930f06b1d4aea48d922bf3325f --- /dev/null +++ b/pool/shard001/C++/0022414_initterm.cpp @@ -0,0 +1,82 @@ +// initterm.cpp + +// based on: +// LIBCTINY - Matt Pietrek 2001 +// MSDN Magazine, January 2001 + +// 08/12/06 (mv) + +#include +#include +#include "libct.h" + +#pragma section(".CRT$XCA", read, write) +#pragma data_seg(".CRT$XCA") // start of ctor section +_PVFV __xc_a[] = {0}; + +#pragma section(".CRT$XCZ", read, write) +#pragma data_seg(".CRT$XCZ") // end of ctor section +_PVFV __xc_z[] = {0}; + +#pragma data_seg() +#pragma comment(linker, "/merge:.CRT=.rdata") + +BEGIN_EXTERN_C + +void _initterm(_PVFV *pfbegin, _PVFV *pfend) +{ + // walk the table of function pointers from the bottom up, until + // the end is encountered. Do not skip the first entry. The initial + // value of pfbegin points to the first valid entry. Do not try to + // execute what pfend points to. Only entries before pfend are valid. + while (pfbegin < pfend) + { + if (*pfbegin != 0) + (**pfbegin)(); + ++pfbegin; + } +} + + +static _PVFV *atexitlist = 0; +static unsigned int max_atexit_entries = 0; +static unsigned int cur_atexit_entries = 0; + +void _init_atexit() +{ + max_atexit_entries = 128; + atexitlist = (_PVFV*)calloc(max_atexit_entries, sizeof(_PVFV*)); +} + +int atexit(_PVFV func) +{ + if (cur_atexit_entries < max_atexit_entries) + { + atexitlist[cur_atexit_entries++] = func; + return 0; + } + + return -1; +} + +void _doexit() +{ + if (cur_atexit_entries) + { + // Use ptr math to find the end of the array + _initterm(atexitlist, atexitlist + cur_atexit_entries); + } +} + +void exit(int code) +{ + _doexit(); + ExitProcess(code); +} + +int _purecall() +{ + ExitProcess((UINT)-1); +} + +END_EXTERN_C \ No newline at end of file diff --git a/pool/shard001/C++/0022418_flushAndInsert.cpp b/pool/shard001/C++/0022418_flushAndInsert.cpp new file mode 100644 index 0000000000000000000000000000000000000000..104e43ac568a67e6ace7304fcac0f29ece6e8552 --- /dev/null +++ b/pool/shard001/C++/0022418_flushAndInsert.cpp @@ -0,0 +1,158 @@ +/*BEGIN_LEGAL +Intel Open Source License + +Copyright (c) 2002-2013 Intel Corporation. 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 Intel Corporation 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 INTEL 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. +END_LEGAL */ +// +// ORIGINAL_AUTHOR: Kim Hazelwood +// +// This tool tells you what traces reappear after a code cache +// flush. It can be used to identify long-lived traces in a program. +// Note: you must limit the code cache size to trigger flushes +// Sample usage: +// pin -xyzzy -limit_code_cache 131072 -t flushAndInsert -- /bin/ls + +#include "pin.H" +#include "portability.H" +#include "utils.H" +#include +#include +#include + +using namespace std; + +/* ================================================================== */ +/* Global Variables */ +/* ================================================================== */ +int flushes; +int insertions; +ofstream TraceFile; + +/* ===================================================================== */ +/* Commandline Switches */ +/* ===================================================================== */ + +KNOB KnobHelp(KNOB_MODE_WRITEONCE, "pintool", + "hh", "0", "Print help message (command-line switches)"); +KNOB KnobOutputFile(KNOB_MODE_WRITEONCE, "pintool", + "o", "flushAndInsert.out", "specify trace file name"); +KNOB KnobPid(KNOB_MODE_WRITEONCE, "pintool", + "p", "0", "append pid to output"); + +/* ================================================================== */ +/* + Clear the cache flush count +*/ +VOID InitCounters() +{ + string logFileName = KnobOutputFile.Value(); + if( KnobPid ) + logFileName += "." + decstr( getpid_portable() ); + TraceFile.open(logFileName.c_str()); + + insertions = 0; + flushes = 0; +} + +/* ================================================================== */ +/* + Print details of traces as they are inserted +*/ +VOID WatchTraces(TRACE trace, VOID *v) +{ + insertions++; + TraceFile << "Code cache insertion #" << insertions; + TraceFile << "\torig pc=0x" << hex << TRACE_Address(trace); + TraceFile << "\tcache pc=0x" << hex << TRACE_CodeCacheAddress(trace); + TraceFile << "\ttrace size (cache)=" << TRACE_CodeCacheSize(trace); + TraceFile << " (BBL=" << TRACE_NumBbl(trace) << " Ins=" << TRACE_NumIns(trace) << ")" << endl; +} +/* ================================================================== */ +/* + When notified by Pin that the cache is full, perform a flush and + tell the user about it. +*/ +VOID FlushOnFull(UINT32 trace_size, UINT32 stub_size) +{ + TraceFile << "Trying to insert trace size " << trace_size << " and exit stub size " << stub_size << "... "; + flushes++; + CODECACHE_FlushCache(); + TraceFile << " SWOOSH! (" << flushes << ")" << endl; +} + +/* ================================================================== */ +/* + Print details at the end of the run +*/ +VOID PrintDetailsOnExit(INT32 code, VOID *v) +{ + int traces = CODECACHE_NumTracesInCache(); + int stubs = CODECACHE_NumExitStubsInCache(); + int compensation = traces - stubs; + traces = traces - compensation; + + TraceFile << endl << "------------------------" << endl; + TraceFile << dec << traces << " traces" << endl; + TraceFile << stubs << " exit stubs" << endl; + TraceFile << compensation << " compensations" << endl; + TraceFile << (traces+stubs+compensation) << " total regions in the code cache" << endl; + TraceFile << endl << flushes << " flushes!" << endl; + TraceFile << "#eof" << endl; + TraceFile.close(); +} + + +/* ================================================================== */ +/* + Initialize and begin program execution under the control of Pin +*/ +int main(INT32 argc, CHAR **argv) +{ + if (PIN_Init(argc, argv) || KnobHelp) return Usage(); + + // Initialize some counters we're using in this tool + InitCounters(); + + // Register a routine that gets called when the cache is first initialized + CODECACHE_AddCacheInitFunction(PrintInitInfo, 0); + + // Register a routine that gets called every time the cache is full + CODECACHE_AddFullCacheFunction(FlushOnFull, 0); + + // Register a routine that gets called when a trace is + // inserted into the codecache + CODECACHE_AddTraceInsertedFunction(WatchTraces, 0); + + // Register a routine that gets called when the program ends + PIN_AddFiniFunction(PrintDetailsOnExit, 0); + + PIN_StartProgram(); // Never returns + + return 0; +} + diff --git a/pool/shard001/C++/0022425_depthwise_conv.cc b/pool/shard001/C++/0022425_depthwise_conv.cc new file mode 100644 index 0000000000000000000000000000000000000000..b6c65c47c6a598a74dd1f8cee2f5f0f701787d9f --- /dev/null +++ b/pool/shard001/C++/0022425_depthwise_conv.cc @@ -0,0 +1,164 @@ +/* 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/lite/delegates/gpu/gl/kernels/depthwise_conv.h" + +#include +#include + +#include "absl/memory/memory.h" +#include "tensorflow/lite/delegates/gpu/common/convert.h" +#include "tensorflow/lite/delegates/gpu/common/operations.h" +#include "tensorflow/lite/delegates/gpu/common/shape.h" +#include "tensorflow/lite/delegates/gpu/common/status.h" +#include "tensorflow/lite/delegates/gpu/common/types.h" +#include "tensorflow/lite/delegates/gpu/common/util.h" +#include "tensorflow/lite/delegates/gpu/gl/node_shader.h" +#include "tensorflow/lite/delegates/gpu/gl/variable.h" +#include "tensorflow/lite/delegates/gpu/gl/workgroups/ideal_workgroup_picker.h" + +namespace tflite { +namespace gpu { +namespace gl { +namespace { + +class DepthwiseConvolution : public NodeShader { + public: + absl::Status GenerateCode(const GenerationContext& ctx, + GeneratedCode* generated_code) const final { + if (ctx.input_shapes.size() != 1) { + return absl::UnimplementedError( + "DepthWise Convolution does not support more than 1 runtime tensor"); + } + const auto& attr = + absl::any_cast(ctx.op_attr); + auto weights = attr.weights.shape; + const int offsets_count = weights.h * weights.w; + const bool offsets_count_too_large = offsets_count > kMaxConstArraySize; + std::vector parameters; + if (offsets_count_too_large) { + parameters = { + {"input_data_0_h", static_cast(ctx.input_shapes[0][1])}, + {"input_data_0_w", static_cast(ctx.input_shapes[0][2])}, + {"padding_w", attr.padding.prepended.w}, + {"padding_h", attr.padding.prepended.h}, + {"dilation_w", attr.dilations.w}, + {"dilation_h", attr.dilations.h}, + {"kernel_w", weights.w}, + {"kernel_h", weights.h}, + {"src_depth", DivideRoundUp(weights.i, 4)}, + {"channel_multiplier", weights.o}, + {"stride", int2(attr.strides.w, attr.strides.h)}, + }; + } else { + std::vector offsets; + for (int h = 0; h < weights.h; ++h) { + for (int w = 0; w < weights.w; ++w) { + offsets.emplace_back(w * attr.dilations.w - attr.padding.prepended.w, + h * attr.dilations.h - attr.padding.prepended.h); + } + } + parameters = { + {"input_data_0_h", static_cast(ctx.input_shapes[0][1])}, + {"input_data_0_w", static_cast(ctx.input_shapes[0][2])}, + {"offsets_count", offsets_count}, + {"offsets", offsets}, + {"src_depth", DivideRoundUp(weights.i, 4)}, + {"channel_multiplier", weights.o}, + {"stride", int2(attr.strides.w, attr.strides.h)}, + }; + } + bool non_empty_padding = + attr.padding.appended.h != 0 || attr.padding.appended.w != 0 || + attr.padding.prepended.h != 0 || attr.padding.prepended.w != 0; + + std::vector> objects = { + {"weights", MakeReadonlyObject(ConvertToPIOHW4(attr.weights))}}; + + std::string source; + if (offsets_count_too_large) { + source = R"( + int offsets_count = $kernel_w$ * $kernel_h$; + int src_layer_offset = (gid.z % $channel_multiplier$) * 4; + int filter_offset = gid.z * $src_depth$ * offsets_count * 4; + int i = 0; + for (int ky = 0; ky < $kernel_h$; ky++) { + for (int kx = 0; kx < $kernel_w$; kx++, i++) { + ivec2 coord = gid.xy * $stride$ + ivec2(kx * $dilation_w$ - $padding_w$, ky * $dilation_h$ - $padding_h$);)"; + } else { + source = R"( + int offsets_count = $offsets_count$; + int src_layer_offset = (gid.z % $channel_multiplier$) * 4; + int filter_offset = gid.z * $src_depth$ * offsets_count * 4; + for (int i = 0; i < offsets_count; ++i) { + ivec2 coord = gid.xy * $stride$ + $offsets[i]$;)"; + } + if (non_empty_padding) { + source += R"( + if (coord.x < 0 || coord.y < 0 || + coord.x >= $input_data_0_w$ || coord.y >= $input_data_0_h$) { + continue; + })"; + } + source += R"( + int src_layer = gid.z / $channel_multiplier$; + vec4 input_ = $input_data_0[coord.x, coord.y, src_layer]$; + vec4 input_shifted = vec4( + input_[(src_layer_offset + 0) / $channel_multiplier$], + input_[(src_layer_offset + 1) / $channel_multiplier$], + input_[(src_layer_offset + 2) / $channel_multiplier$], + input_[(src_layer_offset + 3) / $channel_multiplier$] + ); + int filter_offset = gid.z * offsets_count + i; + value_0 += input_shifted * $weights[filter_offset]$; + } +)"; + if (offsets_count_too_large) { + source += R"( + } +)"; + } + if (!attr.bias.data.empty()) { + source += "value_0 += $bias[gid.z]$;\n"; + objects.push_back({"bias", MakeReadonlyObject(attr.bias.data)}); + } + *generated_code = { + /*parameters=*/std::move(parameters), + /*objects=*/std::move(objects), + /*shared_variables=*/{}, + /*workload=*/uint3(), + /*workgroup=*/ + GetIdealWorkgroupIfPossible( + *ctx.gpu_info, OperationType::DEPTHWISE_CONVOLUTION, + HW(attr.weights.shape.h, attr.weights.shape.w), attr.strides, + OHWI(attr.weights.shape.o, ctx.input_shapes[0][1], + ctx.input_shapes[0][2], ctx.input_shapes[0][3])), + /*source_code=*/std::move(source), + /*input=*/IOStructure::ONLY_DEFINITIONS, + /*output=*/IOStructure::AUTO, + }; + return absl::OkStatus(); + } +}; + +} // namespace + +std::unique_ptr NewDepthwiseConvolutionNodeShader() { + return absl::make_unique(); +} + +} // namespace gl +} // namespace gpu +} // namespace tflite diff --git a/pool/shard001/C++/0022426_155.cpp b/pool/shard001/C++/0022426_155.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c26eddf16a4af9029a6004b87300161c7d7160d0 --- /dev/null +++ b/pool/shard001/C++/0022426_155.cpp @@ -0,0 +1,82 @@ +/* + To generate a size n network, we consider the ways to combine a size i + network with a size j network in both parallel and series with i >= j, i + j = + n and i, j != n. This way we consider every size n network at least once, + and for each n we collect the distinct overall capacitances. Notice that + there is some dynamic programming involved, as the possible overall + capacitances for smaller network sizes is cached and retrieved when + determining the possible overall capacitances for the current network size. + + Also in principle, we can use any fixed capacitance and don't have to stick + to 60 micro Farads. So we denote our fixed capacitance as 1. This way, when + we combine fractions, we can ensure that the numerator and denominator + remains as small as possible. + + It turns out that with fixed capacitance 1, all related variables can fit + within unsigned int even while neglecting the GCD step of adding fractions. + As such, we can totally skip the GCD part of adding fractions and define our + own struct with a custom < operator that considers a / b < c / d <=> ad < bc + for use by std::set when checking for order. +*/ + +#include +#include +#include + +struct q_t +{ + unsigned int n, d; + q_t(unsigned int const &_n, unsigned int const &_d) : n(_n), d(_d) { } + + bool operator<(q_t const &rhs) const + { + return this->n * rhs.d < this->d * rhs.n; + } +}; + +int main() +{ + std::set all_values = { + { q_t(1, 1) } + }; + + std::vector> values = { + { }, + { q_t(1, 1) } + }; + + for (int n = 2; n <= 18; n++) + { + values.emplace_back(); + int i = n - 1; + int j = 1; + while (i >= j) + { + for (q_t const &a : values[i]) + { + for (q_t const &b : values[j]) + { + int v = a.n * b.d + a.d * b.n; + q_t parallel(v, a.d * b.d); + q_t series(a.n * b.n, v); + + if (all_values.find(parallel) == all_values.end()) + { + values.back().emplace(parallel); + all_values.emplace(parallel); + } + + if (all_values.find(series) == all_values.end()) + { + values.back().emplace(series); + all_values.emplace(series); + } + } + } + i--; + j++; + } + } + + std::cout << all_values.size(); +} diff --git a/pool/shard001/C++/0022432_DSPJitMisc.cpp b/pool/shard001/C++/0022432_DSPJitMisc.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6da5b646f4b3d96eff0a8bac186ffac3ec658a05 --- /dev/null +++ b/pool/shard001/C++/0022432_DSPJitMisc.cpp @@ -0,0 +1,194 @@ +// Copyright 2013 Dolphin Emulator Project +// Licensed under GPLv2 +// Refer to the license.txt file included. + +#include "../DSPEmitter.h" +#include "../DSPIntUtil.h" + +using namespace Gen; + +// MRR $D, $S +// 0001 11dd ddds ssss +// Move value from register $S to register $D. +void DSPEmitter::mrr(const UDSPInstruction opc) +{ + u8 sreg = opc & 0x1f; + u8 dreg = (opc >> 5) & 0x1f; + + dsp_op_read_reg(sreg, EDX); + dsp_op_write_reg(dreg, EDX); + dsp_conditional_extend_accum(dreg); +} + +// LRI $D, #I +// 0000 0000 100d dddd +// iiii iiii iiii iiii +// Load immediate value I to register $D. +// +// DSPSpy discovery: This, and possibly other instructions that load a +// register, has a different behaviour in S40 mode if loaded to AC0.M: The +// value gets sign extended to the whole accumulator! This does not happen in +// S16 mode. +void DSPEmitter::lri(const UDSPInstruction opc) +{ + u8 reg = opc & DSP_REG_MASK; + u16 imm = dsp_imem_read(compilePC+1); + dsp_op_write_reg_imm(reg, imm); + dsp_conditional_extend_accum_imm(reg, imm); +} + +// LRIS $(0x18+D), #I +// 0000 1ddd iiii iiii +// Load immediate value I (8-bit sign extended) to accumulator register. +void DSPEmitter::lris(const UDSPInstruction opc) +{ + u8 reg = ((opc >> 8) & 0x7) + DSP_REG_AXL0; + u16 imm = (s8)opc; + dsp_op_write_reg_imm(reg, imm); + dsp_conditional_extend_accum_imm(reg, imm); +} + +//---- + +// NX +// 1000 -000 xxxx xxxx +// No operation, but can be extended with extended opcode. +// This opcode is supposed to do nothing - it's used if you want to use +// an opcode extension but not do anything. At least according to duddie. +void DSPEmitter::nx(const UDSPInstruction opc) +{ +} + +//---- + +// DAR $arD +// 0000 0000 0000 01dd +// Decrement address register $arD. +void DSPEmitter::dar(const UDSPInstruction opc) +{ + // g_dsp.r[opc & 0x3] = dsp_decrement_addr_reg(opc & 0x3); + decrement_addr_reg(opc & 0x3); + +} + +// IAR $arD +// 0000 0000 0000 10dd +// Increment address register $arD. +void DSPEmitter::iar(const UDSPInstruction opc) +{ + // g_dsp.r[opc & 0x3] = dsp_increment_addr_reg(opc & 0x3); + increment_addr_reg(opc & 0x3); +} + +// SUBARN $arD +// 0000 0000 0000 11dd +// Subtract indexing register $ixD from an addressing register $arD. +// used only in IPL-NTSC ucode +void DSPEmitter::subarn(const UDSPInstruction opc) +{ + // u8 dreg = opc & 0x3; + // g_dsp.r[dreg] = dsp_decrease_addr_reg(dreg, (s16)g_dsp.r[DSP_REG_IX0 + dreg]); + decrease_addr_reg(opc & 0x3); +} + +// ADDARN $arD, $ixS +// 0000 0000 0001 ssdd +// Adds indexing register $ixS to an addressing register $arD. +// It is critical for the Zelda ucode that this one wraps correctly. +void DSPEmitter::addarn(const UDSPInstruction opc) +{ + // u8 dreg = opc & 0x3; + // u8 sreg = (opc >> 2) & 0x3; + // g_dsp.r[dreg] = dsp_increase_addr_reg(dreg, (s16)g_dsp.r[DSP_REG_IX0 + sreg]); + + // From looking around it is always called with the matching index register + increase_addr_reg(opc & 0x3, (opc >> 2) & 0x3); +} + +//---- + + +void DSPEmitter::setCompileSR(u16 bit) +{ + + // g_dsp.r[DSP_REG_SR] |= bit + OpArg sr_reg; + gpr.getReg(DSP_REG_SR,sr_reg); + OR(16, sr_reg, Imm16(bit)); + gpr.putReg(DSP_REG_SR); + + compileSR |= bit; +} + +void DSPEmitter::clrCompileSR(u16 bit) +{ + + // g_dsp.r[DSP_REG_SR] &= bit + OpArg sr_reg; + gpr.getReg(DSP_REG_SR,sr_reg); + AND(16, sr_reg, Imm16(~bit)); + gpr.putReg(DSP_REG_SR); + + compileSR &= ~bit; +} +// SBCLR #I +// 0001 0011 aaaa aiii +// bit of status register $sr. Bit number is calculated by adding 6 to +// immediate value I. +void DSPEmitter::sbclr(const UDSPInstruction opc) +{ + u8 bit = (opc & 0x7) + 6; + + clrCompileSR(1 << bit); +} + +// SBSET #I +// 0001 0010 aaaa aiii +// Set bit of status register $sr. Bit number is calculated by adding 6 to +// immediate value I. +void DSPEmitter::sbset(const UDSPInstruction opc) +{ + u8 bit = (opc & 0x7) + 6; + + setCompileSR(1 << bit); +} + +// 1000 1bbb xxxx xxxx, bbb >= 010 +// This is a bunch of flag setters, flipping bits in SR. So far so good, +// but it's harder to know exactly what effect they have. +void DSPEmitter::srbith(const UDSPInstruction opc) +{ + switch ((opc >> 8) & 0xf) + { + // M0/M2 change the multiplier mode (it can multiply by 2 for free). + case 0xa: // M2 + clrCompileSR(SR_MUL_MODIFY); + break; + case 0xb: // M0 + setCompileSR(SR_MUL_MODIFY); + break; + + // If set, treat multiplicands as unsigned. + // If clear, treat them as signed. + case 0xc: // CLR15 + clrCompileSR(SR_MUL_UNSIGNED); + break; + case 0xd: // SET15 + setCompileSR(SR_MUL_UNSIGNED); + break; + + // Automatic 40-bit sign extension when loading ACx.M. + // SET40 changes something very important: see the LRI instruction above. + case 0xe: // SET16 (CLR40) + clrCompileSR(SR_40_MODE_BIT); + break; + + case 0xf: // SET40 + setCompileSR(SR_40_MODE_BIT); + break; + + default: + break; + } +} + diff --git a/pool/shard001/C++/0022436_takeoff.cpp b/pool/shard001/C++/0022436_takeoff.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2bde007358f1853f46d3101f56a7789809c7bf7b --- /dev/null +++ b/pool/shard001/C++/0022436_takeoff.cpp @@ -0,0 +1,160 @@ +/**************************************************************************** + * + * Copyright (c) 2013-2014 PX4 Development Team. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * 3. Neither the name PX4 nor the names of its contributors may be + * used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED + * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************/ +/** + * @file takeoff.cpp + * + * Helper class to Takeoff + * + * @author Lorenz Meier + */ + +#include "takeoff.h" +#include "navigator.h" + +Takeoff::Takeoff(Navigator *navigator) : + MissionBlock(navigator) +{ +} + +void +Takeoff::on_activation() +{ + set_takeoff_position(); +} + +void +Takeoff::on_active() +{ + struct position_setpoint_triplet_s *rep = _navigator->get_takeoff_triplet(); + + if (rep->current.valid) { + // reset the position + set_takeoff_position(); + + } else if (is_mission_item_reached() && !_navigator->get_mission_result()->finished) { + _navigator->get_mission_result()->finished = true; + _navigator->set_mission_result_updated(); + + // set loiter item so position controllers stop doing takeoff logic + set_loiter_item(&_mission_item); + struct position_setpoint_triplet_s *pos_sp_triplet = _navigator->get_position_setpoint_triplet(); + mission_apply_limitation(_mission_item); + mission_item_to_position_setpoint(_mission_item, &pos_sp_triplet->current); + _navigator->set_position_setpoint_triplet_updated(); + } +} + +void +Takeoff::set_takeoff_position() +{ + struct position_setpoint_triplet_s *rep = _navigator->get_takeoff_triplet(); + + float abs_altitude = 0.0f; + + float min_abs_altitude; + + if (_navigator->home_position_valid()) { //only use home position if it is valid + min_abs_altitude = _navigator->get_global_position()->alt + _navigator->get_takeoff_min_alt(); + + } else { //e.g. flow + min_abs_altitude = _navigator->get_takeoff_min_alt(); + } + + // Use altitude if it has been set. If home position is invalid use min_abs_altitude + if (rep->current.valid && PX4_ISFINITE(rep->current.alt) && _navigator->home_position_valid()) { + abs_altitude = rep->current.alt; + + // If the altitude suggestion is lower than home + minimum clearance, raise it and complain. + if (abs_altitude < min_abs_altitude) { + if (abs_altitude < min_abs_altitude - 0.1f) { // don't complain if difference is smaller than 10cm + mavlink_log_critical(_navigator->get_mavlink_log_pub(), + "Using minimum takeoff altitude: %.2f m", (double)_navigator->get_takeoff_min_alt()); + } + + abs_altitude = min_abs_altitude; + } + + } else { + // Use home + minimum clearance but only notify. + abs_altitude = min_abs_altitude; + mavlink_log_info(_navigator->get_mavlink_log_pub(), + "Using minimum takeoff altitude: %.2f m", (double)_navigator->get_takeoff_min_alt()); + } + + + if (abs_altitude < _navigator->get_global_position()->alt) { + // If the suggestion is lower than our current alt, let's not go down. + abs_altitude = _navigator->get_global_position()->alt; + mavlink_log_critical(_navigator->get_mavlink_log_pub(), "Already higher than takeoff altitude"); + } + + // set current mission item to takeoff + set_takeoff_item(&_mission_item, abs_altitude); + _navigator->get_mission_result()->finished = false; + _navigator->set_mission_result_updated(); + reset_mission_item_reached(); + + // convert mission item to current setpoint + struct position_setpoint_triplet_s *pos_sp_triplet = _navigator->get_position_setpoint_triplet(); + mission_apply_limitation(_mission_item); + mission_item_to_position_setpoint(_mission_item, &pos_sp_triplet->current); + + pos_sp_triplet->previous.valid = false; + pos_sp_triplet->current.yaw_valid = true; + pos_sp_triplet->next.valid = false; + + if (rep->current.valid) { + + // Go on and check which changes had been requested + if (PX4_ISFINITE(rep->current.yaw)) { + pos_sp_triplet->current.yaw = rep->current.yaw; + } + + // Set the current latitude and longitude even if they are NAN + // NANs are handled in FlightTaskAuto.cpp + pos_sp_triplet->current.lat = rep->current.lat; + pos_sp_triplet->current.lon = rep->current.lon; + + // mark this as done + memset(rep, 0, sizeof(*rep)); + } + + if (PX4_ISFINITE(pos_sp_triplet->current.lat) && PX4_ISFINITE(pos_sp_triplet->current.lon)) { + _navigator->set_can_loiter_at_sp(true); + + } else { + _navigator->set_can_loiter_at_sp(false); + } + + _navigator->set_position_setpoint_triplet_updated(); +} diff --git a/pool/shard001/C++/0022437_dlg_forgotpasswordrequest.cpp b/pool/shard001/C++/0022437_dlg_forgotpasswordrequest.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cb5f620cf4e4f199bd214587ef86a8c18666ee76 --- /dev/null +++ b/pool/shard001/C++/0022437_dlg_forgotpasswordrequest.cpp @@ -0,0 +1,77 @@ +#include "dlg_forgotpasswordrequest.h" + +#include "settingscache.h" + +#include +#include +#include +#include +#include +#include +#include + +DlgForgotPasswordRequest::DlgForgotPasswordRequest(QWidget *parent) : QDialog(parent) +{ + + QString lastfphost; + QString lastfpport; + QString lastfpplayername; + ServersSettings &servers = SettingsCache::instance().servers(); + lastfphost = servers.getHostname("server.cockatrice.us"); + lastfpport = servers.getPort("4747"); + lastfpplayername = servers.getPlayerName("Player"); + + if (!servers.getFPHostname().isEmpty() && !servers.getFPPort().isEmpty() && !servers.getFPPlayerName().isEmpty()) { + lastfphost = servers.getFPHostname(); + lastfpport = servers.getFPPort(); + lastfpplayername = servers.getFPPlayerName(); + } + + hostLabel = new QLabel(tr("&Host:")); + hostEdit = new QLineEdit(lastfphost); + hostLabel->setBuddy(hostEdit); + + portLabel = new QLabel(tr("&Port:")); + portEdit = new QLineEdit(lastfpport); + portLabel->setBuddy(portEdit); + + playernameLabel = new QLabel(tr("Player &name:")); + playernameEdit = new QLineEdit(lastfpplayername); + playernameLabel->setBuddy(playernameEdit); + + QGridLayout *grid = new QGridLayout; + grid->addWidget(hostLabel, 0, 0); + grid->addWidget(hostEdit, 0, 1); + grid->addWidget(portLabel, 1, 0); + grid->addWidget(portEdit, 1, 1); + grid->addWidget(playernameLabel, 2, 0); + grid->addWidget(playernameEdit, 2, 1); + + QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); + connect(buttonBox, SIGNAL(accepted()), this, SLOT(actOk())); + connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject())); + + QVBoxLayout *mainLayout = new QVBoxLayout; + mainLayout->addLayout(grid); + mainLayout->addWidget(buttonBox); + setLayout(mainLayout); + + setWindowTitle(tr("Forgot Password Request")); + setFixedHeight(sizeHint().height()); + setMinimumWidth(300); +} + +void DlgForgotPasswordRequest::actOk() +{ + if (playernameEdit->text().isEmpty()) { + QMessageBox::critical(this, tr("Forgot Password Request Warning"), tr("The player name can't be empty.")); + return; + } + + ServersSettings &servers = SettingsCache::instance().servers(); + servers.setFPHostName(hostEdit->text()); + servers.setFPPort(portEdit->text()); + servers.setFPPlayerName(playernameEdit->text()); + + accept(); +} diff --git a/pool/shard001/C++/0022442_setoutfallatdeepestpoint.cpp b/pool/shard001/C++/0022442_setoutfallatdeepestpoint.cpp new file mode 100644 index 0000000000000000000000000000000000000000..043dad45a2c5cd5b48ece94dafa5e6d6342c9476 --- /dev/null +++ b/pool/shard001/C++/0022442_setoutfallatdeepestpoint.cpp @@ -0,0 +1,86 @@ +/** + * @file + * @author Michael Mair + * @version 1.0 + * @section LICENSE + * + * This file is part of DynaMind + * + * Copyright (C) 2012 Michael Mair + + * 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 + +//DynaMind includes +#include +#include +#include +#include + +using namespace DM; + +DM_DECLARE_NODE_NAME(SetOutfallAtDeepestPoint,Sewersystems) + +SetOutfallAtDeepestPoint::SetOutfallAtDeepestPoint() +{ +} + +void SetOutfallAtDeepestPoint::init() +{ + S::ViewDefinitionHelper sd; + std::vector views; + + DM::View jview = sd.getCompleteView(S::JUNCTION,DM::MODIFY); + + views.push_back(jview); + views.push_back(sd.getCompleteView(S::OUTFALL,DM::MODIFY)); + views.push_back(sd.getCompleteView(S::CONDUIT,DM::MODIFY)); + + this->addData("Sewer", views); +} + +void SetOutfallAtDeepestPoint::run() +{ + this->sys = this->getData("Sewer"); + S::ViewDefinitionHelper sd; + DynamindBoostGraph::Compmap j = sys->getAllComponentsInView(sd.getView(DM::S::JUNCTION,DM::MODIFY)); + + float deepesthight; + Node *deepest = 0; + + for(DynamindBoostGraph::Compitr itr = j.begin(); itr != j.end(); ++itr) + { + Node* currentnode = static_cast(*itr); + + if(deepest==0 || deepesthight > currentnode->getZ()) + { + deepest = currentnode; + deepesthight = deepest->getZ(); + } + } + + if(deepest!=0) + { + Node *outfall = new Node(*deepest); + Edge *outfallconduit = new Edge(deepest,outfall); + outfallconduit->addAttribute("Diameter",0.15); + outfallconduit->addAttribute("Length",10); + sys->addComponentToView(outfall,sd.getView(DM::S::OUTFALL,DM::MODIFY)); + sys->addComponentToView(outfallconduit,sd.getView(DM::S::CONDUIT,DM::MODIFY)); + } +} diff --git a/pool/shard001/C++/0022445_discard.pass.cpp b/pool/shard001/C++/0022445_discard.pass.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d10b7c5e8a31df9f7f476f9d6218d8c0ccb79615 --- /dev/null +++ b/pool/shard001/C++/0022445_discard.pass.cpp @@ -0,0 +1,52 @@ +//===----------------------------------------------------------------------===// +// +// The LLVM Compiler Infrastructure +// +// This file is dual licensed under the MIT and the University of Illinois Open +// Source Licenses. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +// + +// template +// class discard_block_engine + +// void discard(unsigned long long z); + +#include +#include + +void +test1() +{ + std::ranlux24 e1; + std::ranlux24 e2 = e1; + assert(e1 == e2); + e1.discard(3); + assert(e1 != e2); + (void)e2(); + (void)e2(); + (void)e2(); + assert(e1 == e2); +} + +void +test2() +{ + std::ranlux48 e1; + std::ranlux48 e2 = e1; + assert(e1 == e2); + e1.discard(3); + assert(e1 != e2); + (void)e2(); + (void)e2(); + (void)e2(); + assert(e1 == e2); +} + +int main() +{ + test1(); + test2(); +} diff --git a/pool/shard001/C++/0022446_result.cc b/pool/shard001/C++/0022446_result.cc new file mode 100644 index 0000000000000000000000000000000000000000..9a1c8fba4eae58f09b613faf0dcd01beaec187d1 --- /dev/null +++ b/pool/shard001/C++/0022446_result.cc @@ -0,0 +1,125 @@ +/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab: + * + * Data Differential YATL (i.e. libtest) library + * + * Copyright (C) 2012-2013 Data Differential, http://datadifferential.com/ + * + * 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. + * + * * The names of its contributors may not 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 "libtest/yatlcon.h" +#include +#include + +namespace libtest { + +__test_result::__test_result(const char *file_arg, int line_arg, const char *func_arg): + _line(line_arg), + _file(file_arg), + _func(func_arg), + _error_message(NULL), + _error_message_size(0) +{ +} + +#ifndef __INTEL_COMPILER +# pragma GCC diagnostic ignored "-Wformat-nonliteral" +#endif +void __test_result::init(va_list args_) +{ + const char *format= va_arg(args_, const char *); + _error_message_size= vasprintf(&_error_message, format, args_); + assert(_error_message_size != -1); + if (_error_message_size > 0) + { + _error_message_size++; + } +} + +__test_result::~__test_result() throw() +{ + free(_error_message); +} + +__test_result::__test_result(const __test_result& other) : + _line(other._line), + _file(other._file), + _func(other._func), + _error_message_size(other._error_message_size) +{ + if (_error_message_size > 0) + { + _error_message= (char*) malloc(_error_message_size); + if (_error_message) + { + memcpy(_error_message, other._error_message, _error_message_size); + } + else + { + _error_message_size= -1; + } + } +} + +__success::__success(const char *file_arg, int line_arg, const char *func_arg): + __test_result(file_arg, line_arg, func_arg) +{ +} + +__skipped::__skipped(const char *file_arg, int line_arg, const char *func_arg, ...): + __test_result(file_arg, line_arg, func_arg) +{ + va_list args; + va_start(args, func_arg); + init(args); + va_end(args); +} + +__skipped::__skipped(const __skipped& other) : + __test_result(other) +{ +} + +__failure::__failure(const char *file_arg, int line_arg, const char *func_arg, ...) : + __test_result(file_arg, line_arg, func_arg) +{ + va_list args; + va_start(args, func_arg); + init(args); + va_end(args); +} + +__failure::__failure(const __failure& other) : + __test_result(other) +{ +} + + +} // namespace libtest diff --git a/pool/shard001/C++/0022447_openglwindow.cpp b/pool/shard001/C++/0022447_openglwindow.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6b227f71e7ab052a465454cacc8f612de5f1c1fc --- /dev/null +++ b/pool/shard001/C++/0022447_openglwindow.cpp @@ -0,0 +1,98 @@ +#include "openglwindow.h" + +#include +#include +#include + +#include "entity/entitymanager.h" +#include "texturemanager.h" + +#include "vertex.h" + +/******************************************************************************* + * OpenGL Events + ******************************************************************************/ + +void OpenGLWindow::updateScene() { + QOpenGLWindow::update(); +} + +std::unique_ptr OpenGLWindow::createTextureManager() { + makeCurrent(); + auto textureManager = std::make_unique(); + doneCurrent(); + return textureManager; +} + +std::unique_ptr OpenGLWindow::createEntityManager(TextureManager* textureManager) { + makeCurrent(); + auto entityManager = std::make_unique(textureManager); + doneCurrent(); + return entityManager; +} + +void OpenGLWindow::setEntityManager(EntityManager* entityManager) { + m_entityManager = entityManager; +} + +void OpenGLWindow::initializeGL() { + // Initialize OpenGL Backend + initializeOpenGLFunctions(); + + // Set global information + glClearColor(0.0f, 0.0f, 0.0f, 1.0f); + glEnable(GL_PROGRAM_POINT_SIZE); + + emit GLInitialized(); +} + +void OpenGLWindow::paintGL() { + glClear(GL_COLOR_BUFFER_BIT); + if (m_entityManager != nullptr) { + m_entityManager->drawEntities(this); + } +} + +void OpenGLWindow::teardownGL() { + // Actually destroy our OpenGL information + // do something here? +} + +/******************************************************************************* + * Private Helpers + ******************************************************************************/ + +void OpenGLWindow::printVersionInformation() { + QString glType; + QString glVersion; + QString glProfile; + + // Get Version Information + glType = (context()->isOpenGLES()) ? "OpenGL ES" : "OpenGL"; + glVersion = reinterpret_cast(glGetString(GL_VERSION)); + +// Get Profile Information +#define CASE(c) \ + case QSurfaceFormat::c: \ + glProfile = #c; \ + break + switch (format().profile()) { + CASE(NoProfile); + CASE(CoreProfile); + CASE(CompatibilityProfile); + } +#undef CASE + + // qPrintable() will print our QString w/o quotes around it. + qDebug() << qPrintable(glType) << qPrintable(glVersion) << "(" << qPrintable(glProfile) << ")"; +} + +void OpenGLWindow::mouseDoubleClickEvent(QMouseEvent* e) { + if (e->button() == Qt::LeftButton) { + close(); + } +} + +void OpenGLWindow::hideEvent(QHideEvent* /*event*/) { + emit onClose(); +} diff --git a/pool/shard001/C++/0022452_c64emu.cpp b/pool/shard001/C++/0022452_c64emu.cpp new file mode 100644 index 0000000000000000000000000000000000000000..311a77f110441f0913432865078eaac205e027ff --- /dev/null +++ b/pool/shard001/C++/0022452_c64emu.cpp @@ -0,0 +1,59 @@ +#include "c64emu.h" +#include +#include "Emulation.h" + +int main(int argc, char* argv[]) +{ + /* Set up SDL window */ + SDL_Window *main_window; + SDL_Init(SDL_INIT_VIDEO); + main_window = SDL_CreateWindow( + "C64 Emulator", + SDL_WINDOWPOS_UNDEFINED, + SDL_WINDOWPOS_UNDEFINED, + 800, + 600, + SDL_WINDOW_OPENGL + ); + + /* Check for errors */ + if (main_window == NULL) + { + printf("Error creating window: %s\n", SDL_GetError()); + return 1; + } + + /* Begin emulation */ + Emulation emu; + + emu.SetupRendering(main_window); + + while (1) { + SDL_Event e; + if (SDL_PollEvent(&e)) { + + // Handle keyboard events + if (e.type == SDL_KEYDOWN || e.type == SDL_KEYUP) + { + emu.SystemKeyboard.KeyEvent(e.key); + } + + + if (e.type == SDL_QUIT) { + break; + } + } + + emu.RunCycles(20000); + + emu.UpdateVideo(); + + SDL_Delay(1); + } + + /* End emulation */ + emu.TeardownRendering(); + SDL_DestroyWindow(main_window); + SDL_Quit(); + return 0; +} diff --git a/pool/shard001/C++/0022456_NOOP.cc b/pool/shard001/C++/0022456_NOOP.cc new file mode 100644 index 0000000000000000000000000000000000000000..859667494a7d5eed62577eee6ff1f0db2fce9994 --- /dev/null +++ b/pool/shard001/C++/0022456_NOOP.cc @@ -0,0 +1,40 @@ +#include "Logger/Log.h" + +#include "NOOP.h" + +using namespace SideCar; +using namespace SideCar::Algorithms; + +NOOP::NOOP(Controller& controller, Logger::Log& log) : Algorithm(controller, log) +{ + ; +} + +bool +NOOP::startup() +{ + registerProcessor(&NOOP::processVideo); + return Algorithm::startup(); +} + +bool +NOOP::processVideo(const Messages::Video::Ref& msg) +{ + static Logger::ProcLog log("processVideo", getLog()); + LOGINFO << std::endl; + Messages::Video::Ref out(Messages::Video::Make(getName(), msg)); + out->getData() = msg->getData(); + return send(out); +} + +extern "C" ACE_Svc_Export void* +FormatInfo(const IO::StatusBase& status, int role) +{ + return NULL; +} + +extern "C" ACE_Svc_Export Algorithm* +NOOPMake(Controller& controller, Logger::Log& log) +{ + return new NOOP(controller, log); +} diff --git a/pool/shard001/C++/0022467_config_test.cc b/pool/shard001/C++/0022467_config_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..62e5eb05163280928cf18a12cfd1475879a7ec76 --- /dev/null +++ b/pool/shard001/C++/0022467_config_test.cc @@ -0,0 +1,169 @@ +#include "test/mocks/local_info/mocks.h" +#include "test/mocks/server/factory_context.h" +#include "test/mocks/server/instance.h" +#include "test/test_common/registry.h" + +#include "contrib/envoy/extensions/filters/network/rocketmq_proxy/v3/rocketmq_proxy.pb.h" +#include "contrib/envoy/extensions/filters/network/rocketmq_proxy/v3/rocketmq_proxy.pb.validate.h" +#include "contrib/rocketmq_proxy/filters/network/source/config.h" +#include "gmock/gmock.h" +#include "gtest/gtest.h" + +using testing::_; +using testing::Return; +using testing::ReturnRef; + +namespace Envoy { +namespace Extensions { +namespace NetworkFilters { +namespace RocketmqProxy { + +using RocketmqProxyProto = envoy::extensions::filters::network::rocketmq_proxy::v3::RocketmqProxy; + +RocketmqProxyProto parseRocketmqProxyFromV3Yaml(const std::string& yaml) { + RocketmqProxyProto rocketmq_proxy; + TestUtility::loadFromYaml(yaml, rocketmq_proxy); + return rocketmq_proxy; +} + +class RocketmqFilterConfigTestBase { +public: + void testConfig(RocketmqProxyProto& config) { + Network::FilterFactoryCb cb; + EXPECT_NO_THROW({ cb = factory_.createFilterFactoryFromProto(config, context_); }); + Network::MockConnection connection; + EXPECT_CALL(connection, addReadFilter(_)); + cb(connection); + } + + NiceMock context_; + RocketmqProxyFilterConfigFactory factory_; +}; + +class RocketmqFilterConfigTest : public RocketmqFilterConfigTestBase, public testing::Test { +public: + ~RocketmqFilterConfigTest() override = default; +}; + +TEST_F(RocketmqFilterConfigTest, ValidateFail) { + NiceMock context; + EXPECT_THROW( + RocketmqProxyFilterConfigFactory().createFilterFactoryFromProto( + envoy::extensions::filters::network::rocketmq_proxy::v3::RocketmqProxy(), context), + ProtoValidationException); +} + +TEST_F(RocketmqFilterConfigTest, ValidProtoConfiguration) { + envoy::extensions::filters::network::rocketmq_proxy::v3::RocketmqProxy config{}; + config.set_stat_prefix("my_stat_prefix"); + NiceMock context; + RocketmqProxyFilterConfigFactory factory; + Network::FilterFactoryCb cb = factory.createFilterFactoryFromProto(config, context); + Network::MockConnection connection; + EXPECT_CALL(connection, addReadFilter(_)); + cb(connection); +} + +TEST_F(RocketmqFilterConfigTest, RocketmqProxyWithEmptyProto) { + NiceMock context; + RocketmqProxyFilterConfigFactory factory; + envoy::extensions::filters::network::rocketmq_proxy::v3::RocketmqProxy config = + *dynamic_cast( + factory.createEmptyConfigProto().get()); + config.set_stat_prefix("my_stat_prefix"); + Network::FilterFactoryCb cb = factory.createFilterFactoryFromProto(config, context); + Network::MockConnection connection; + EXPECT_CALL(connection, addReadFilter(_)); + cb(connection); +} + +TEST_F(RocketmqFilterConfigTest, RocketmqProxyWithFullConfig) { + const std::string yaml = R"EOF( + stat_prefix: rocketmq_incomming_stats + develop_mode: true + transient_object_life_span: + seconds: 30 + )EOF"; + RocketmqProxyProto config = parseRocketmqProxyFromV3Yaml(yaml); + testConfig(config); +} + +TEST_F(RocketmqFilterConfigTest, ProxyAddress) { + NiceMock context; + Server::Configuration::MockServerFactoryContext factory_context; + EXPECT_CALL(context, getServerFactoryContext()).WillRepeatedly(ReturnRef(factory_context)); + + LocalInfo::MockLocalInfo local_info; + EXPECT_CALL(factory_context, localInfo()).WillRepeatedly(ReturnRef(local_info)); + std::shared_ptr instance = + std::make_shared("logical", "physical"); + EXPECT_CALL(local_info, address()).WillRepeatedly(Return(instance)); + EXPECT_CALL(*instance, type()).WillRepeatedly(Return(Network::Address::Type::Ip)); + + Network::MockIp* ip = new Network::MockIp(); + EXPECT_CALL(*instance, ip()).WillRepeatedly(testing::Return(ip)); + + std::string address("1.2.3.4"); + EXPECT_CALL(*ip, addressAsString()).WillRepeatedly(ReturnRef(address)); + EXPECT_CALL(*ip, port()).WillRepeatedly(Return(1234)); + ConfigImpl::RocketmqProxyConfig proxyConfig; + ConfigImpl configImpl(proxyConfig, context); + + EXPECT_STREQ("1.2.3.4:1234", configImpl.proxyAddress().c_str()); + delete ip; +} + +TEST_F(RocketmqFilterConfigTest, ProxyAddressWithDefaultPort) { + NiceMock context; + Server::Configuration::MockServerFactoryContext factory_context; + EXPECT_CALL(context, getServerFactoryContext()).WillRepeatedly(ReturnRef(factory_context)); + + LocalInfo::MockLocalInfo local_info; + EXPECT_CALL(factory_context, localInfo()).WillRepeatedly(ReturnRef(local_info)); + std::shared_ptr instance = + std::make_shared("logical", "physical"); + EXPECT_CALL(local_info, address()).WillRepeatedly(Return(instance)); + EXPECT_CALL(*instance, type()).WillRepeatedly(Return(Network::Address::Type::Ip)); + + Network::MockIp* ip = new Network::MockIp(); + EXPECT_CALL(*instance, ip()).WillRepeatedly(testing::Return(ip)); + + std::string address("1.2.3.4"); + EXPECT_CALL(*ip, addressAsString()).WillRepeatedly(ReturnRef(address)); + EXPECT_CALL(*ip, port()).WillRepeatedly(Return(0)); + ConfigImpl::RocketmqProxyConfig proxyConfig; + ConfigImpl configImpl(proxyConfig, context); + + EXPECT_STREQ("1.2.3.4:10000", configImpl.proxyAddress().c_str()); + delete ip; +} + +TEST_F(RocketmqFilterConfigTest, ProxyAddressWithNonIpType) { + NiceMock context; + Server::Configuration::MockServerFactoryContext factory_context; + EXPECT_CALL(context, getServerFactoryContext()).WillRepeatedly(ReturnRef(factory_context)); + + LocalInfo::MockLocalInfo local_info; + EXPECT_CALL(factory_context, localInfo()).WillRepeatedly(ReturnRef(local_info)); + std::shared_ptr instance = + std::make_shared("logical", "physical"); + EXPECT_CALL(local_info, address()).WillRepeatedly(Return(instance)); + EXPECT_CALL(*instance, type()).WillRepeatedly(Return(Network::Address::Type::Pipe)); + + Network::MockIp* ip = new Network::MockIp(); + EXPECT_CALL(*instance, ip()).WillRepeatedly(testing::Return(ip)); + + std::string address("1.2.3.4"); + EXPECT_CALL(*ip, addressAsString()).WillRepeatedly(ReturnRef(address)); + EXPECT_CALL(*ip, port()).WillRepeatedly(Return(0)); + ConfigImpl::RocketmqProxyConfig proxyConfig; + ConfigImpl configImpl(proxyConfig, context); + + EXPECT_STREQ("physical", configImpl.proxyAddress().c_str()); + delete ip; +} + +} // namespace RocketmqProxy +} // namespace NetworkFilters +} // namespace Extensions +} // namespace Envoy diff --git a/pool/shard001/C++/0022478_oggflacfile.cpp b/pool/shard001/C++/0022478_oggflacfile.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9d9c303d7c079334bb672ebb5f972639fe1d9979 --- /dev/null +++ b/pool/shard001/C++/0022478_oggflacfile.cpp @@ -0,0 +1,276 @@ +/*************************************************************************** + copyright : (C) 2004-2005 by Allan Sandfeld Jensen + email : kde@carewolf.org + ***************************************************************************/ + +/*************************************************************************** + * 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 * + * * + * Alternatively, this file is available under the Mozilla Public * + * License Version 1.1. You may obtain a copy of the License at * + * http://www.mozilla.org/MPL/ * + ***************************************************************************/ + +#include +#include +#include + +#include +#include "oggflacfile.h" + +using namespace TagLib; +using TagLib::FLAC::Properties; + +class Ogg::FLAC::File::FilePrivate +{ +public: + FilePrivate() : + comment(0), + properties(0), + streamStart(0), + streamLength(0), + scanned(false), + hasXiphComment(false), + commentPacket(0) {} + + ~FilePrivate() + { + delete comment; + delete properties; + } + + Ogg::XiphComment *comment; + + Properties *properties; + ByteVector streamInfoData; + ByteVector xiphCommentData; + long streamStart; + long streamLength; + bool scanned; + + bool hasXiphComment; + int commentPacket; +}; + +//////////////////////////////////////////////////////////////////////////////// +// public members +//////////////////////////////////////////////////////////////////////////////// + +Ogg::FLAC::File::File(FileName file, bool readProperties, + Properties::ReadStyle propertiesStyle) : Ogg::File(file) +{ + d = new FilePrivate; + read(readProperties, propertiesStyle); +} + +Ogg::FLAC::File::File(IOStream *stream, bool readProperties, + Properties::ReadStyle propertiesStyle) : Ogg::File(stream) +{ + d = new FilePrivate; + read(readProperties, propertiesStyle); +} + +Ogg::FLAC::File::~File() +{ + delete d; +} + +Ogg::XiphComment *Ogg::FLAC::File::tag() const +{ + return d->comment; +} + +Properties *Ogg::FLAC::File::audioProperties() const +{ + return d->properties; +} + + +bool Ogg::FLAC::File::save() +{ + d->xiphCommentData = d->comment->render(false); + + // Create FLAC metadata-block: + + // Put the size in the first 32 bit (I assume no more than 24 bit are used) + + ByteVector v = ByteVector::fromUInt(d->xiphCommentData.size()); + + // Set the type of the metadata-block to be a Xiph / Vorbis comment + + v[0] = 4; + + // Append the comment-data after the 32 bit header + + v.append(d->xiphCommentData); + + // Save the packet at the old spot + // FIXME: Use padding if size is increasing + + setPacket(d->commentPacket, v); + + return Ogg::File::save(); +} + +//////////////////////////////////////////////////////////////////////////////// +// private members +//////////////////////////////////////////////////////////////////////////////// + +void Ogg::FLAC::File::read(bool readProperties, Properties::ReadStyle propertiesStyle) +{ + // Sanity: Check if we really have an Ogg/FLAC file + +/* + ByteVector oggHeader = packet(0); + + if (oggHeader.mid(28,4) != "fLaC") { + debug("Ogg::FLAC::File::read() -- Not an Ogg/FLAC file"); + setValid(false); + return; + }*/ + + // Look for FLAC metadata, including vorbis comments + + scan(); + + if (!d->scanned) { + setValid(false); + return; + } + + + if(d->hasXiphComment) + d->comment = new Ogg::XiphComment(xiphCommentData()); + else + d->comment = new Ogg::XiphComment; + + + if(readProperties) + d->properties = new Properties(streamInfoData(), streamLength(), propertiesStyle); +} + +ByteVector Ogg::FLAC::File::streamInfoData() +{ + scan(); + return d->streamInfoData; +} + +ByteVector Ogg::FLAC::File::xiphCommentData() +{ + scan(); + return d->xiphCommentData; +} + +long Ogg::FLAC::File::streamLength() +{ + scan(); + return d->streamLength; +} + +void Ogg::FLAC::File::scan() +{ + // Scan the metadata pages + + if(d->scanned) + return; + + if(!isValid()) + return; + + int ipacket = 0; + long overhead = 0; + + ByteVector metadataHeader = packet(ipacket); + if(metadataHeader.isNull()) + return; + + ByteVector header; + + if (!metadataHeader.startsWith("fLaC")) { + // FLAC 1.1.2+ + if (metadataHeader.mid(1,4) != "FLAC") return; + + if (metadataHeader[5] != 1) return; // not version 1 + + metadataHeader = metadataHeader.mid(13); + } + else { + // FLAC 1.1.0 & 1.1.1 + metadataHeader = packet(++ipacket); + + if(metadataHeader.isNull()) + return; + + } + + header = metadataHeader.mid(0,4); + // Header format (from spec): + // <1> Last-metadata-block flag + // <7> BLOCK_TYPE + // 0 : STREAMINFO + // 1 : PADDING + // .. + // 4 : VORBIS_COMMENT + // .. + // <24> Length of metadata to follow + + char blockType = header[0] & 0x7f; + bool lastBlock = (header[0] & 0x80) != 0; + uint length = header.mid(1, 3).toUInt(); + overhead += length; + + // Sanity: First block should be the stream_info metadata + + if(blockType != 0) { + debug("Ogg::FLAC::File::scan() -- Invalid Ogg/FLAC stream"); + return; + } + + d->streamInfoData = metadataHeader.mid(4,length); + + // Search through the remaining metadata + + while(!lastBlock) { + metadataHeader = packet(++ipacket); + + if(metadataHeader.isNull()) + return; + + header = metadataHeader.mid(0, 4); + blockType = header[0] & 0x7f; + lastBlock = (header[0] & 0x80) != 0; + length = header.mid(1, 3).toUInt(); + overhead += length; + + if(blockType == 1) { + // debug("Ogg::FLAC::File::scan() -- Padding found"); + } + else if(blockType == 4) { + // debug("Ogg::FLAC::File::scan() -- Vorbis-comments found"); + d->xiphCommentData = metadataHeader.mid(4, length); + d->hasXiphComment = true; + d->commentPacket = ipacket; + } + else if(blockType > 5) { + debug("Ogg::FLAC::File::scan() -- Unknown metadata block"); + } + } + + // End of metadata, now comes the datastream + d->streamStart = overhead; + d->streamLength = File::length() - d->streamStart; + + d->scanned = true; +} diff --git a/pool/shard001/C++/0022480_Error.cpp b/pool/shard001/C++/0022480_Error.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c7ac3a585649d37e658726a634a8c466a4882e2d --- /dev/null +++ b/pool/shard001/C++/0022480_Error.cpp @@ -0,0 +1,170 @@ +/* + * Copyright (C) 1999-2001 Harri Porten (porten@kde.org) + * Copyright (C) 2001 Peter Kelly (pmk@post.com) + * Copyright (C) 2003, 2004, 2005, 2006, 2008 Apple Inc. All rights reserved. + * Copyright (C) 2007 Eric Seidel (eric@webkit.org) + * + * 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" +#include "Error.h" + +#include "ConstructData.h" +#include "ErrorConstructor.h" +#include "ExceptionHelpers.h" +#include "FunctionPrototype.h" +#include "JSArray.h" +#include "JSFunction.h" +#include "JSGlobalObject.h" +#include "JSObject.h" +#include "JSString.h" +#include "NativeErrorConstructor.h" +#include "JSCInlines.h" +#include "SourceCode.h" + +#include + +namespace JSC { + +static const char* linePropertyName = "line"; +static const char* sourceURLPropertyName = "sourceURL"; + +JSObject* createError(JSGlobalObject* globalObject, const String& message) +{ + ASSERT(!message.isEmpty()); + return ErrorInstance::create(globalObject->vm(), globalObject->errorStructure(), message); +} + +JSObject* createEvalError(JSGlobalObject* globalObject, const String& message) +{ + ASSERT(!message.isEmpty()); + return ErrorInstance::create(globalObject->vm(), globalObject->evalErrorConstructor()->errorStructure(), message); +} + +JSObject* createRangeError(JSGlobalObject* globalObject, const String& message) +{ + ASSERT(!message.isEmpty()); + return ErrorInstance::create(globalObject->vm(), globalObject->rangeErrorConstructor()->errorStructure(), message); +} + +JSObject* createReferenceError(JSGlobalObject* globalObject, const String& message) +{ + ASSERT(!message.isEmpty()); + return ErrorInstance::create(globalObject->vm(), globalObject->referenceErrorConstructor()->errorStructure(), message); +} + +JSObject* createSyntaxError(JSGlobalObject* globalObject, const String& message) +{ + ASSERT(!message.isEmpty()); + return ErrorInstance::create(globalObject->vm(), globalObject->syntaxErrorConstructor()->errorStructure(), message); +} + +JSObject* createTypeError(JSGlobalObject* globalObject, const String& message) +{ + ASSERT(!message.isEmpty()); + return ErrorInstance::create(globalObject->vm(), globalObject->typeErrorConstructor()->errorStructure(), message); +} + +JSObject* createNotEnoughArgumentsError(JSGlobalObject* globalObject) +{ + return createTypeError(globalObject, ASCIILiteral("Not enough arguments")); +} + +JSObject* createURIError(JSGlobalObject* globalObject, const String& message) +{ + ASSERT(!message.isEmpty()); + return ErrorInstance::create(globalObject->vm(), globalObject->URIErrorConstructor()->errorStructure(), message); +} + +JSObject* createError(ExecState* exec, const String& message) +{ + return createError(exec->lexicalGlobalObject(), message); +} + +JSObject* createEvalError(ExecState* exec, const String& message) +{ + return createEvalError(exec->lexicalGlobalObject(), message); +} + +JSObject* createRangeError(ExecState* exec, const String& message) +{ + return createRangeError(exec->lexicalGlobalObject(), message); +} + +JSObject* createReferenceError(ExecState* exec, const String& message) +{ + return createReferenceError(exec->lexicalGlobalObject(), message); +} + +JSObject* createSyntaxError(ExecState* exec, const String& message) +{ + return createSyntaxError(exec->lexicalGlobalObject(), message); +} + +JSObject* createTypeError(ExecState* exec, const String& message) +{ + return createTypeError(exec->lexicalGlobalObject(), message); +} + +JSObject* createNotEnoughArgumentsError(ExecState* exec) +{ + return createNotEnoughArgumentsError(exec->lexicalGlobalObject()); +} + +JSObject* createURIError(ExecState* exec, const String& message) +{ + return createURIError(exec->lexicalGlobalObject(), message); +} + +JSObject* addErrorInfo(CallFrame* callFrame, JSObject* error, int line, const SourceCode& source) +{ + VM* vm = &callFrame->vm(); + const String& sourceURL = source.provider()->url(); + + if (line != -1) + error->putDirect(*vm, Identifier(vm, linePropertyName), jsNumber(line), ReadOnly | DontDelete); + if (!sourceURL.isNull()) + error->putDirect(*vm, Identifier(vm, sourceURLPropertyName), jsString(vm, sourceURL), ReadOnly | DontDelete); + return error; +} + + +bool hasErrorInfo(ExecState* exec, JSObject* error) +{ + return error->hasProperty(exec, Identifier(exec, linePropertyName)) + || error->hasProperty(exec, Identifier(exec, sourceURLPropertyName)); +} + +JSObject* throwTypeError(ExecState* exec) +{ + return exec->vm().throwException(exec, createTypeError(exec, ASCIILiteral("Type error"))); +} + +JSObject* throwSyntaxError(ExecState* exec) +{ + return exec->vm().throwException(exec, createSyntaxError(exec, ASCIILiteral("Syntax error"))); +} + +const ClassInfo StrictModeTypeErrorFunction::s_info = { "Function", &Base::s_info, 0, 0, CREATE_METHOD_TABLE(StrictModeTypeErrorFunction) }; + +void StrictModeTypeErrorFunction::destroy(JSCell* cell) +{ + static_cast(cell)->StrictModeTypeErrorFunction::~StrictModeTypeErrorFunction(); +} + +} // namespace JSC diff --git a/pool/shard001/C++/0022481_mitkRTDoseReaderTest.cpp b/pool/shard001/C++/0022481_mitkRTDoseReaderTest.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fe8166905e98a60387e0573c3458d534ac013df2 --- /dev/null +++ b/pool/shard001/C++/0022481_mitkRTDoseReaderTest.cpp @@ -0,0 +1,54 @@ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ + +#include +#include + +#include +#include + +class mitkRTDoseReaderTestSuite : public mitk::TestFixture +{ + CPPUNIT_TEST_SUITE(mitkRTDoseReaderTestSuite); + MITK_TEST(TestDoseImage); + CPPUNIT_TEST_SUITE_END(); + +private: + + mitk::RTDoseReader::Pointer m_rtDoseReader; + +public: + + void setUp() override + { + m_rtDoseReader = mitk::RTDoseReader::New(); + CPPUNIT_ASSERT_MESSAGE("Failed to initialize RTDoseReader", m_rtDoseReader.IsNotNull()); + } + + void TestDoseImage() + { + mitk::Image::Pointer refImage = mitk::IOUtil::LoadImage(GetTestDataFilePath("RT/Dose/RT_Dose.nrrd")); + + mitk::DataNode::Pointer node = m_rtDoseReader->LoadRTDose(GetTestDataFilePath("RT/Dose/RD.dcm").c_str()); + mitk::Image::Pointer image = dynamic_cast(node->GetData()); + + MITK_ASSERT_EQUAL(refImage, image, "referece-Image and image should be equal"); + + } + +}; + +MITK_TEST_SUITE_REGISTRATION(mitkRTDoseReader) diff --git a/pool/shard001/C++/0022482_mensaje_a_mayusculas_impl.cc b/pool/shard001/C++/0022482_mensaje_a_mayusculas_impl.cc new file mode 100644 index 0000000000000000000000000000000000000000..19bdd091f9c290e274979bb27cae9c7a88e700ef --- /dev/null +++ b/pool/shard001/C++/0022482_mensaje_a_mayusculas_impl.cc @@ -0,0 +1,77 @@ +/* -*- c++ -*- */ + + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include +#include "mensaje_a_mayusculas_impl.h" +#include +#include +#include + + + +namespace gr { + namespace tfg { + + mensaje_a_mayusculas::sptr + mensaje_a_mayusculas::make() + { + return gnuradio::get_initial_sptr + (new mensaje_a_mayusculas_impl()); + } + + /* + * The private constructor + */ + mensaje_a_mayusculas_impl::mensaje_a_mayusculas_impl() + : gr::block("mensaje_a_mayusculas", + gr::io_signature::make(0, 0, 0), + gr::io_signature::make(0, 0, 0)){ + + message_port_register_in(pmt::mp("entrada")); + message_port_register_out(pmt::mp("salida")); + + set_msg_handler(pmt::mp("entrada"), boost::bind(&mensaje_a_mayusculas_impl::msg_handler, this, _1)); + } + + /* + * Our virtual destructor. + */ + mensaje_a_mayusculas_impl::~mensaje_a_mayusculas_impl() + { + } + + + void mensaje_a_mayusculas_impl::msg_handler(pmt::pmt_t msg){ + + std::string str = pmt::symbol_to_string(msg); + std::cout << "En el bloque 'mensaje_a_mayusculas': Recibido = '" << str; + + std::transform(str.begin(), str.end(), str.begin(), ::toupper); + std::cout << "' Transmitido: '" << str << "'" << std::endl; + + pmt::pmt_t mensaje = pmt::string_to_symbol(str); + message_port_pub (pmt::mp("salida"), mensaje); + } + + + void + mensaje_a_mayusculas_impl::forecast (int noutput_items, gr_vector_int &ninput_items_required) + { + /* <+forecast+> e.g. ninput_items_required[0] = noutput_items */ + } + + int + mensaje_a_mayusculas_impl::general_work (int noutput_items, + gr_vector_int &ninput_items, + gr_vector_const_void_star &input_items, + gr_vector_void_star &output_items) + { + } + + } /* namespace tfg */ +} /* namespace gr */ + diff --git a/pool/shard001/C++/0022486_CWE121_Stack_Based_Buffer_Overflow__CWE805_char_declare_loop_81a.cpp b/pool/shard001/C++/0022486_CWE121_Stack_Based_Buffer_Overflow__CWE805_char_declare_loop_81a.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9a4bb2377a6caacff60ca1190d18b8d2453a880d --- /dev/null +++ b/pool/shard001/C++/0022486_CWE121_Stack_Based_Buffer_Overflow__CWE805_char_declare_loop_81a.cpp @@ -0,0 +1,91 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE121_Stack_Based_Buffer_Overflow__CWE805_char_declare_loop_81a.cpp +Label Definition File: CWE121_Stack_Based_Buffer_Overflow__CWE805.string.label.xml +Template File: sources-sink-81a.tmpl.cpp +*/ +/* + * @description + * CWE: 121 Stack Based Buffer Overflow + * BadSource: Set data pointer to the bad buffer + * GoodSource: Set data pointer to the good buffer + * Sinks: loop + * BadSink : Copy string to data using a loop + * Flow Variant: 81 Data flow: data passed in a parameter to an virtual method called via a reference + * + * */ + +#include "std_testcase.h" +#include "CWE121_Stack_Based_Buffer_Overflow__CWE805_char_declare_loop_81.h" + +namespace CWE121_Stack_Based_Buffer_Overflow__CWE805_char_declare_loop_81 +{ + +#ifndef OMITBAD + +void bad() +{ + char * data; + char dataBadBuffer[50]; + char dataGoodBuffer[100]; + /* FLAW: Set a pointer to a "small" buffer. This buffer will be used in the sinks as a destination + * buffer in various memory copying functions using a "large" source buffer. */ + data = dataBadBuffer; + data[0] = '\0'; /* null terminate */ + const CWE121_Stack_Based_Buffer_Overflow__CWE805_char_declare_loop_81_base& baseObject = CWE121_Stack_Based_Buffer_Overflow__CWE805_char_declare_loop_81_bad(); + baseObject.action(data); +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B uses the GoodSource with the BadSink */ +static void goodG2B() +{ + char * data; + char dataBadBuffer[50]; + char dataGoodBuffer[100]; + /* FIX: Set a pointer to a "large" buffer, thus avoiding buffer overflows in the sinks. */ + data = dataGoodBuffer; + data[0] = '\0'; /* null terminate */ + const CWE121_Stack_Based_Buffer_Overflow__CWE805_char_declare_loop_81_base& baseObject = CWE121_Stack_Based_Buffer_Overflow__CWE805_char_declare_loop_81_goodG2B(); + baseObject.action(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 CWE121_Stack_Based_Buffer_Overflow__CWE805_char_declare_loop_81; /* 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/shard001/C++/0022495_fpscamera.cpp b/pool/shard001/C++/0022495_fpscamera.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ef0dbbef17547ff6550001f01a2e18beab3517f1 --- /dev/null +++ b/pool/shard001/C++/0022495_fpscamera.cpp @@ -0,0 +1,47 @@ +#include "fpscamera.hpp" +#include +#include +#include +#include + +FPSCamera::FPSCamera() + : pos(0,0,0), orient(glm::vec3(0,0,0)) +{ +} + +void FPSCamera::move(float distance, glm::vec3 axis){ + pos += (distance * axis) * orient; +} + +void FPSCamera::moveForward(float distance){ +// pos += glm::vec3(0, 0, distance ) * orient; + move(distance, glm::vec3(0,0,1)); +} + +void FPSCamera::moveRight(float distance){ + pos += glm::vec3(distance, 0, 0) * orient; +} + +void FPSCamera::moveUpward(float distance){ + move(-distance, glm::vec3(0,1,0)); +} + +void FPSCamera::setPosition(glm::vec3 position){ + pos = position; +} + +void FPSCamera::rotate(float angle, float x, float y, float z){ + glm::quat rot = glm::angleAxis(angle, x, y, z); + orient = glm::normalize(rot * orient); +} + +glm::quat FPSCamera::getOrientation() const { + return orient; +} + +glm::vec3 FPSCamera::getPosition() const{ + return pos; +} + + + diff --git a/pool/shard001/C++/0022503_pgModel.cpp b/pool/shard001/C++/0022503_pgModel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d4053770d316c609a9260b77383f8d9503662244 --- /dev/null +++ b/pool/shard001/C++/0022503_pgModel.cpp @@ -0,0 +1,189 @@ +//////////////////////////////////////////////////////////////////////////////// +// pgModel.cpp + +// Includes +#include "BaArchive.h" +#include "pgModel.h" +#include "MtVector2.h" +#include "MtVector3.h" +#include "RsColour.h" +#include "SgNode.h" +#include "RsShader.h" +#include "BtBase.h" +#include "BtTime.h" +#include "ShTouch.h" +#include "RsRenderTarget.h" +#include "pgRenderOrders.h" +#include "HlModel.h" +#include "UiKeyboard.h" +#include +#include "HlFont.h" +#include "ApConfig.h" + +static BtU32 ShowShape = 1; + +//////////////////////////////////////////////////////////////////////////////// +// Setup + +void pgModel::Setup( BaArchive *pArchive ) +{ + m_pShader = pArchive->GetShader( "shader" ); + m_pModel = pArchive->GetNode( "Outer_All" ); + + HlModel::SetSortOrders( m_pModel, 5);//MaxSortOrders-1 ); + m_m3Rotation.SetIdentity(); + m_isContracting = BtFalse; +} + +//////////////////////////////////////////////////////////////////////////////// +// Reset + +void pgModel::Reset() +{ + m_isContracting = BtFalse; + scaleTime = 0; +} + +//////////////////////////////////////////////////////////////////////////////// +// Update + +BtBool pgModel::Update( BtU32 screenIndex, BtBool isPressed, BtBool isReleased ) +{ + if( ApConfig::IsWin() ) + { + if( UiKeyboard::pInstance()->IsPressed( UiKeyCode_1 ) ) + { + ShowShape = 1; + } + if( UiKeyboard::pInstance()->IsPressed( UiKeyCode_2 ) ) + { + ShowShape = 2; + } + + // Rotate the model + BtFloat speed = 0.1f; + if( UiKeyboard::pInstance()->IsHeld( UiKeyCode_UP ) ) + { + MtMatrix3 m3Rotate; + m3Rotate.SetRotationX( -speed ); + m_m3Rotation = m_m3Rotation * m3Rotate; + } + if( UiKeyboard::pInstance()->IsHeld( UiKeyCode_DOWN ) ) + { + MtMatrix3 m3Rotate; + m3Rotate.SetRotationX( speed ); + m_m3Rotation = m_m3Rotation * m3Rotate; + } + if( UiKeyboard::pInstance()->IsHeld( UiKeyCode_RIGHT ) ) + { + MtMatrix3 m3Rotate; + m3Rotate.SetRotationY( -speed ); + m_m3Rotation = m3Rotate * m_m3Rotation; + } + if( UiKeyboard::pInstance()->IsHeld( UiKeyCode_LEFT ) ) + { + MtMatrix3 m3Rotate; + m3Rotate.SetRotationY( speed ); + m_m3Rotation = m3Rotate * m_m3Rotation; + } + } + + /* + MtMatrix4 m4Translation; + m4Translation.SetTranslation( MtVector3( 0, -4.5f, 13.0f ) ); + + // Set the rotation + MtMatrix4 m4Transform; + MtMatrix4 Y; + Y.SetRotationX(MtDegreesToRadians(-20.0f)); + m4Transform = Y * m_m3Rotation * m4Translation; + */ + MtMatrix4 m4Rotate; + m4Rotate.SetRotationX(MtDegreesToRadians(90.0f)); + MtMatrix4 m4Transform; + m4Transform.SetTranslation(MtVector3(-5, 0, 10.0f)); + m_pModel->SetLocalTransform(m_m3Rotation * m4Rotate * m4Transform); + m_pModel->Update(); + + if( ( screenIndex == 20 ) || ( screenIndex == 21 ) ) + { + m4Transform = m4Transform; + scaleTime = 0; + m_elapsedTime = BtTime::GetElapsedTimeInSeconds(); + } + + const BtFloat MaxTime = 1.5f; + + if( ( screenIndex == 22 ) || ( screenIndex == 23 ) ) + { + if( isPressed ) + { + if( m_isContracting ) + { + scaleTime -= BtTime::GetTick(); + } + else + { + scaleTime += BtTime::GetTick(); + } + + if( scaleTime < 0 ) + { + scaleTime = 0; + m_isContracting = BtFalse; + return BtTrue; + } + if( scaleTime > MaxTime ) + { + scaleTime = MaxTime; + m_isContracting = BtTrue; + } + } + if( isReleased ) + { + scaleTime = 0; + m_isContracting = BtFalse; + } + m_scale = scaleTime / MaxTime; + } + return BtFalse; +} + +//////////////////////////////////////////////////////////////////////////////// +// Render + +void pgModel::Render( BtU32 screenIndex ) +{ + // Set the light direction + static BtFloat x, y, z; + z = -0.05f; + y = 0.05f; + x = 0.02f; + MtVector3 v3LightDirection( x, y, z ); + v3LightDirection.GetNormalise(); + + MtVector3 ambient(0.5f, 0.5f, 0.5f); + //MtVector3 ambient(0.3f, 0.3f, 0.3f); + //MtVector3 ambient(0, 0, 0); + m_pShader->SetFloats( RsHandles_Light0Direction, &v3LightDirection.x, 3 ); + + // Set the lights ambient level + m_pShader->SetFloats( RsHandles_LightAmbient, &ambient.x, 3 ); + + // Apply the shader + m_pShader->Apply(); + + if( ( screenIndex > 1 ) && ( screenIndex <= 18 ) ) + { + m_pModel->Render(); + } + if( screenIndex == 20 ) + { + m_pModel->Render(); + } + /* + BtChar text[32]; + sprintf( text, "Sin-angle %.2f", sinAngle ); + HlFont::RenderHeavy( MtVector2( 0, 0 ), text, MaxSortOrders-1 ); + */ +} diff --git a/pool/shard001/C++/0022504_NodeUiToggleButton.cpp b/pool/shard001/C++/0022504_NodeUiToggleButton.cpp new file mode 100644 index 0000000000000000000000000000000000000000..41fcc85acd6c7feaf3ba222d1b9cebc069ce8c7f --- /dev/null +++ b/pool/shard001/C++/0022504_NodeUiToggleButton.cpp @@ -0,0 +1,98 @@ +#include "SocketClient.h" + +#include "arro.pb.h" +#include "Trace.h" +#include "INodeContext.h" +#include "json.hpp" + +namespace Arro { + +class NodeRef; +class NodeUiToggleButton: public INodeDefinition { +public: + /** + * Constructor + * + * \param d The Process node instance. + * \param name Name of this node. + * \param params List of parameters passed to this node. + */ + NodeUiToggleButton(INodeContext* d, const std::string& name, StringMap& params, TiXmlElement*); + + virtual ~NodeUiToggleButton(); + + void finishConstruction(); + + /** + * Make the node execute a processing cycle. + */ + void runCycle(); + +private: + Trace m_trace; + INodeContext* m_elemBlock; + NodeRef* m_uiClient; + INodeContext::ItRef m_selection; + std::string m_name; + INodeContext::ItRef m_disable; + +}; + +} /* namespace Arro */ + + +using namespace std; +using namespace Arro; +using namespace arro; + +static RegisterMe registerMe("ToggleButton"); + +NodeUiToggleButton::NodeUiToggleButton(INodeContext* d, const string& /*name*/, StringMap& /*params*/, TiXmlElement*): + m_trace{"NodeUiToggleButton", true}, + m_elemBlock{d}, + m_uiClient{nullptr} { + + m_name = d->getParameter("name"); + + +} + +void +NodeUiToggleButton::finishConstruction() { + m_trace.println("finishConstruction"); + + m_disable = m_elemBlock->begin(m_elemBlock->getInputPad("disable"), 0, INodeContext::DELTA); + + m_selection = m_elemBlock->end(m_elemBlock->getOutputPad("selection")); + + std::string inst = std::string("getName() + "\" name=\"" + m_name + "\">"; + + m_uiClient = SocketClient::getInstance()->subscribe(m_elemBlock->getName(), inst, [=](const std::string& data) { + + Selection* sel = new Selection(); + auto info = nlohmann::json::parse(data.c_str()); + sel->set_value(info["value"]); + m_selection->setRecord(*sel); + }); + +} + +NodeUiToggleButton::~NodeUiToggleButton() { + SocketClient::getInstance()->unsubscribe(m_uiClient); +} + +void NodeUiToggleButton::runCycle() { + MessageBuf buf; + if(m_disable->getNext(buf)) { + Value* msg = new Value(); + msg->ParseFromString((*buf).c_str()); + + // output { "value": "" } + std::string json_string = "{ \"value\": " + std::to_string(msg->value()) + " }"; + + if(buf != nullptr) { + SocketClient::getInstance()->sendMessage(m_uiClient, json_string); + } + } +} + diff --git a/pool/shard001/C++/0022512_databasehelper.cpp b/pool/shard001/C++/0022512_databasehelper.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1c32dca54e6b4914d6f2d2193516f7241b4f5add --- /dev/null +++ b/pool/shard001/C++/0022512_databasehelper.cpp @@ -0,0 +1,123 @@ +#include "databasehelper.h" + +#include "logging.h" +#include "phxpaths.h" + +#include +#include + +using namespace Library; + +QSqlDatabase Library::getLibretroDatabase() { + QSqlDatabase libretroDatabase; + + // Create connection if connection not already created + { + QString connectionName = QThread::currentThread()->objectName() % QStringLiteral( "libretro" ); + + if( !QSqlDatabase::contains( connectionName ) ) { + libretroDatabase = QSqlDatabase::addDatabase( QStringLiteral( "QSQLITE" ), connectionName ); + } else { + libretroDatabase = QSqlDatabase::database( connectionName ); + } + } + + if( !libretroDatabase.isOpen() ) { + libretroDatabase.setDatabaseName( PhxPaths::metadataLocation() % QStringLiteral( "/libretro.sqlite" ) ); + libretroDatabase.open(); + Q_ASSERT( libretroDatabase.isOpen() ); + } + + return libretroDatabase; +} + +QSqlDatabase Library::getUserDatabase() { + QSqlDatabase userDatabase; + + // Create connection if connection not already created + { + QString connectionName = QThread::currentThread()->objectName() % QStringLiteral( "userdata" ); + + if( !QSqlDatabase::contains( connectionName ) ) { + userDatabase = QSqlDatabase::addDatabase( QStringLiteral( "QSQLITE" ), connectionName ); + } else { + userDatabase = QSqlDatabase::database( connectionName ); + } + } + + // Open if not already opened + if( !userDatabase.isOpen() ) { + userDatabase.setDatabaseName( PhxPaths::userDataLocation() % QStringLiteral( "/userdata.sqlite" ) ); + userDatabase.open(); + Q_ASSERT( userDatabase.isOpen() ); + } + + // Check if schema is set up, initialize it if it's not + { + if( !userDatabase.tables().contains( "schema_version" ) ) { + createUserDatabaseSchema( userDatabase ); + } + } + return userDatabase; +} + +bool Library::createUserDatabaseSchema( QSqlDatabase db ) { + qCDebug( phxLibrary, "Initializing database schema" ); + db.transaction(); + + qCDebug( phxLibrary ) << db; + + QSqlQuery q( db ); + q.exec( "CREATE TABLE schema_version (version INTEGER NOT NULL)" ); + q.exec( QStringLiteral( "INSERT INTO schema_version (version) VALUES (0)" ) ); + q.exec( QStringLiteral( "CREATE TABLE games (\n" ) + % QStringLiteral( " rowIndex INTEGER PRIMARY KEY AUTOINCREMENT,\n" ) + + % QStringLiteral( " \n/* game info */\n" ) + % QStringLiteral( " title TEXT NOT NULL,\n" ) + % QStringLiteral( " system TEXT,\n" ) + % QStringLiteral( " region TEXT,\n" ) + % QStringLiteral( " goodtoolsCode TEXT,\n" ) + % QStringLiteral( " timePlayed DATETIME,\n" ) + % QStringLiteral( " artworkUrl TEXT,\n" ) + % QStringLiteral( " coreFilePath TEXT,\n" ) + + % QStringLiteral( " /* file info */" ) + % QStringLiteral( " absolutePath TEXT,\n" ) + % QStringLiteral( " absoluteFilePath TEXT UNIQUE NOT NULL,\n" ) + % QStringLiteral( " crc32Checksum TEXT\n" ) + % QStringLiteral( ")" ) ); + + q.exec( QStringLiteral( "CREATE INDEX title_index ON games (title)" ) ); + q.exec( QStringLiteral( "CREATE INDEX favorite_index ON games (is_favorite)" ) ); + + + // Create Collections Mapping Table + q.exec( QStringLiteral( "CREATE TABLE collections (\n" ) + % QStringLiteral( " collectionID INTEGER PRIMARY KEY AUTOINCREMENT,\n" ) + % QStringLiteral( " collectionName TEXT UNIQUE NOT NULL\n" ) + % QStringLiteral( ")" ) ); + + // Create Collections Table + q.exec( QStringLiteral( "CREATE TABLE collectionMappings (\n" ) + % QStringLiteral( " collectionID INTEGER,\n" ) + % QStringLiteral( " rowIndex INTEGER,\n" ) + % QStringLiteral( " FOREIGN KEY (collectionID) REFERENCES collections " ) + % QStringLiteral( "(collectionID) ON DELETE CASCADE ON UPDATE CASCADE\n" ) + % QStringLiteral( " FOREIGN KEY (rowIndex) REFERENCES games " ) + % QStringLiteral( "(rowIndex) ON DELETE CASCADE ON UPDATE CASCADE\n" ) + % QStringLiteral( ")" ) ); + + q.exec( QStringLiteral( "INSERT INTO collections " ) + % QStringLiteral( "(collectionID, collectionName) VALUES (0, 'All')" ) ); + + // Create default core table + q.exec( QStringLiteral( "CREATE TABLE defaultCores (\n" ) + % QStringLiteral( " system TEXT UNIQUE NOT NULL," ) + % QStringLiteral( " defaultCore TEXT" ) + % QStringLiteral( ")" ) ); + + db.commit(); + + return true; +} diff --git a/pool/shard001/C++/0022515_drawlooper.cpp b/pool/shard001/C++/0022515_drawlooper.cpp new file mode 100644 index 0000000000000000000000000000000000000000..676e01aef65fb2fb5acd92120023d14321003c81 --- /dev/null +++ b/pool/shard001/C++/0022515_drawlooper.cpp @@ -0,0 +1,97 @@ +/* + * Copyright 2011 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + +#include "gm.h" +#include "SkBlurMask.h" +#include "SkBlurMaskFilter.h" +#include "SkCanvas.h" +#include "SkGraphics.h" +#include "SkLayerDrawLooper.h" +#include "SkRandom.h" + +#define WIDTH 200 +#define HEIGHT 200 + +class DrawLooperGM : public skiagm::GM { +public: + DrawLooperGM() : fLooper(nullptr) { + this->setBGColor(sk_tool_utils::color_to_565(0xFFDDDDDD)); + } + +protected: + virtual SkISize onISize() override { + return SkISize::Make(520, 160); + } + + SkString onShortName() override { + return SkString("drawlooper"); + } + + void onDraw(SkCanvas* canvas) override { + this->init(); + + SkPaint paint; + paint.setAntiAlias(true); + sk_tool_utils::set_portable_typeface(&paint); + paint.setTextSize(SkIntToScalar(72)); + paint.setLooper(fLooper); + + canvas->drawCircle(SkIntToScalar(50), SkIntToScalar(50), + SkIntToScalar(30), paint); + + canvas->drawRectCoords(SkIntToScalar(150), SkIntToScalar(50), + SkIntToScalar(200), SkIntToScalar(100), paint); + + canvas->drawText("Looper", 6, SkIntToScalar(230), SkIntToScalar(100), + paint); + } + +private: + sk_sp fLooper; + + void init() { + if (fLooper) return; + + constexpr struct { + SkColor fColor; + SkPaint::Style fStyle; + SkScalar fWidth; + SkScalar fOffset; + SkScalar fBlur; + } gParams[] = { + { SK_ColorWHITE, SkPaint::kStroke_Style, SkIntToScalar(1)*3/4, 0, 0 }, + { SK_ColorRED, SkPaint::kStroke_Style, SkIntToScalar(4), 0, 0 }, + { SK_ColorBLUE, SkPaint::kFill_Style, 0, 0, 0 }, + { 0x88000000, SkPaint::kFill_Style, 0, SkIntToScalar(10), SkIntToScalar(3) } + }; + + SkLayerDrawLooper::Builder looperBuilder; + + SkLayerDrawLooper::LayerInfo info; + info.fPaintBits = SkLayerDrawLooper::kStyle_Bit | SkLayerDrawLooper::kMaskFilter_Bit; + info.fColorMode = SkBlendMode::kSrc; + + for (size_t i = 0; i < SK_ARRAY_COUNT(gParams); i++) { + info.fOffset.set(gParams[i].fOffset, gParams[i].fOffset); + SkPaint* paint = looperBuilder.addLayer(info); + paint->setColor(gParams[i].fColor); + paint->setStyle(gParams[i].fStyle); + paint->setStrokeWidth(gParams[i].fWidth); + if (gParams[i].fBlur > 0) { + paint->setMaskFilter(SkBlurMaskFilter::Make(kNormal_SkBlurStyle, + SkBlurMask::ConvertRadiusToSigma(gParams[i].fBlur))); + } + } + fLooper = looperBuilder.detach(); + } + + typedef GM INHERITED; +}; + +////////////////////////////////////////////////////////////////////////////// + +DEF_GM( return new DrawLooperGM; ) diff --git a/pool/shard001/C++/0022518_Robot.cpp b/pool/shard001/C++/0022518_Robot.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2db10806494aa7266626946802b8443d7805365c --- /dev/null +++ b/pool/shard001/C++/0022518_Robot.cpp @@ -0,0 +1,69 @@ +/* + * Robot.cpp + * + */ + +#include "Robot.h" + +void Robot::update() { + auto now = chrono::high_resolution_clock::now(); + double elapsed = (chrono::duration_cast < chrono::duration > (now - lastBehaviourUpdate)).count(); + + if(activeAction){ + if(activeAction->duration < elapsed){ + //cout << "Tempo de ação esgotado!" << endl; + if(activeBehaviour){ + activeAction = activeBehaviour->getNextAction(); + } else { + activeAction = nullptr; + } + + actionPerformed = false; + } + } else { + if(activeBehaviour){ + activeAction = activeBehaviour->getNextAction(); + actionPerformed = false; + } + } + + if(!activeAction || !activeBehaviour){ + //cout << "Começando o scan de comportamento" << endl; + scanNextBehaviour(); + } + + runAction(); +} + +void Robot::scanNextBehaviour() { + for(unsigned int i = 0; i < desc->behaviours.size(); i++){ + if(desc->behaviours[i]->checkConditions()){ + activeBehaviour = desc->behaviours[i]; + activeBehaviour->reset(); + + //cout << "Ativando comportamento " << activeBehaviour << endl; + break; + } + } +} + +void Robot::runAction() { + if(activeAction && !actionPerformed){ + lastBehaviourUpdate = chrono::high_resolution_clock::now(); + + switch (activeAction->type) { + case ACTION_LINEAR_VEL: + pp->SetSpeed(activeAction->value, oldAng); + oldLinear = activeAction->value; + break; + case ACTION_ANGULAR_VEL: + pp->SetSpeed(oldLinear, activeAction->value); + oldAng = activeAction->value; + break; + default: + break; + } + } + + actionPerformed = true; +} diff --git a/pool/shard001/C++/0022527_filter_if.cpp b/pool/shard001/C++/0022527_filter_if.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f5f1b19022f8b8afb991fa2da1edc3a979a4f71b --- /dev/null +++ b/pool/shard001/C++/0022527_filter_if.cpp @@ -0,0 +1,77 @@ +/*============================================================================= + Copyright (c) 2001-2006 Joel de Guzman + + 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 +#include +#include +#include +#include + +struct X +{ + operator char const*() const + { + return ""; + } +}; + +struct Y +{ + operator char const*() const + { + return ""; + } +}; + +int +main() +{ + using namespace boost::fusion; + + using boost::mpl::_; + using boost::mpl::not_; + using boost::is_class; + using boost::is_same; + + std::cout << tuple_open('['); + std::cout << tuple_close(']'); + std::cout << tuple_delimiter(", "); + +/// Testing filter_if + + X x; Y y; + typedef boost::fusion::vector vector_type; + vector_type t(y, '@', 987654, x, true, 6.6); + + { + std::cout << filter_if > >(t) << std::endl; + BOOST_TEST((filter_if > >(t) + == make_vector('@', 987654, true, 6.6))); + } + + { + std::cout << filter_if >(t) << std::endl; + BOOST_TEST((filter_if >(t) + == make_vector(y, x))); + } + + { + typedef boost::mpl::vector mpl_vec; + BOOST_TEST((filter_if > >(mpl_vec()) + == make_vector(char(), long(), bool()))); + BOOST_TEST((filter_if >(mpl_vec()) + == make_vector(y, x))); + } + + return boost::report_errors(); +} + diff --git a/pool/shard001/C++/0022536_slavi16.cpp b/pool/shard001/C++/0022536_slavi16.cpp new file mode 100644 index 0000000000000000000000000000000000000000..27c49bf3851b9b799172dd2018d7a975f2dfe9a0 --- /dev/null +++ b/pool/shard001/C++/0022536_slavi16.cpp @@ -0,0 +1,74 @@ +// slavi16.cpp : Defines the class behaviors for the application. +// + +#include "stdafx.h" +#include "slavi16.h" +#include "slavi16Dlg.h" + +#ifdef _DEBUG +#define new DEBUG_NEW +#undef THIS_FILE +static char THIS_FILE[] = __FILE__; +#endif + +///////////////////////////////////////////////////////////////////////////// +// CSlavi16App + +BEGIN_MESSAGE_MAP(CSlavi16App, CWinApp) + //{{AFX_MSG_MAP(CSlavi16App) + // NOTE - the ClassWizard will add and remove mapping macros here. + // DO NOT EDIT what you see in these blocks of generated code! + //}}AFX_MSG + ON_COMMAND(ID_HELP, CWinApp::OnHelp) +END_MESSAGE_MAP() + +///////////////////////////////////////////////////////////////////////////// +// CSlavi16App construction + +CSlavi16App::CSlavi16App() +{ + // TODO: add construction code here, + // Place all significant initialization in InitInstance +} + +///////////////////////////////////////////////////////////////////////////// +// The one and only CSlavi16App object + +CSlavi16App theApp; + +///////////////////////////////////////////////////////////////////////////// +// CSlavi16App initialization + +BOOL CSlavi16App::InitInstance() +{ + AfxEnableControlContainer(); + + // Standard initialization + // If you are not using these features and wish to reduce the size + // of your final executable, you should remove from the following + // the specific initialization routines you do not need. + +#ifdef _AFXDLL + Enable3dControls(); // Call this when using MFC in a shared DLL +#else + Enable3dControlsStatic(); // Call this when linking to MFC statically +#endif + + CSlavi16Dlg dlg; + m_pMainWnd = &dlg; + int nResponse = dlg.DoModal(); + if (nResponse == IDOK) + { + // TODO: Place code here to handle when the dialog is + // dismissed with OK + } + else if (nResponse == IDCANCEL) + { + // TODO: Place code here to handle when the dialog is + // dismissed with Cancel + } + + // Since the dialog has been closed, return FALSE so that we exit the + // application, rather than start the application's message pump. + return FALSE; +} diff --git a/pool/shard001/C++/0022544_dthinker.cpp b/pool/shard001/C++/0022544_dthinker.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fac5258ccf0d15ad5125aab389c49500a845caa3 --- /dev/null +++ b/pool/shard001/C++/0022544_dthinker.cpp @@ -0,0 +1,279 @@ +// Emacs style mode select -*- C++ -*- +//----------------------------------------------------------------------------- +// +// $Id$ +// +// Copyright (C) 1998-2006 by Randy Heit (ZDoom). +// Copyright (C) 2006-2012 by The Odamex 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. +// +// DESCRIPTION: +// MapObj data. Map Objects or mobjs are actors, entities, +// thinker, take-your-pick... anything that moves, acts, or +// suffers state changes of more or less violent nature. +// +//----------------------------------------------------------------------------- + + +#include +#include + +#include "dthinker.h" +#include "z_zone.h" +#include "stats.h" +#include "p_local.h" + +IMPLEMENT_SERIAL (DThinker, DObject) + +DThinker *DThinker::FirstThinker = NULL; +DThinker *DThinker::LastThinker = NULL; + +std::vector LingerDestroy; + +void DThinker::Serialize (FArchive &arc) +{ + Super::Serialize (arc); + + // We do not serialize m_Next or m_Prev, because the DThinker + // constructor handles them for us. +} + +void DThinker::SerializeAll (FArchive &arc, bool hubLoad, bool noStorePlayers) +{ + DThinker *thinker; + if (arc.IsStoring () && noStorePlayers) + { + thinker = FirstThinker; + while (thinker) + { + // Don't store player mobjs. + if (!(thinker->IsKindOf(RUNTIME_CLASS(AActor)) && + static_cast(thinker)->type == MT_PLAYER)) + { + arc << (BYTE)1; + arc << thinker; + } + thinker = thinker->m_Next; + } + arc << (BYTE)0; + } + else if (arc.IsStoring ()) + { + thinker = FirstThinker; + while (thinker) + { + arc << (BYTE)1; + arc << thinker; + thinker = thinker->m_Next; + } + arc << (BYTE)0; + } + else + { + if (hubLoad || noStorePlayers) + DestroyMostThinkers (); + else + DestroyAllThinkers (); + + BYTE more; + arc >> more; + while (more) + { + DThinker *thinker; + arc >> thinker; + arc >> more; + } + + // killough 3/26/98: Spawn icon landings: + P_SpawnBrainTargets (); + } +} + +DThinker::DThinker () +{ + // Add a new thinker at the end of the list. + m_Prev = LastThinker; + m_Next = NULL; + if (LastThinker) + LastThinker->m_Next = this; + if (!FirstThinker) + FirstThinker = this; + LastThinker = this; + refCount = 0; + destroyed = false; +} + +DThinker::~DThinker () +{ +} + +void DThinker::Destroy () +{ + // denis - allow this function to be safely called multiple times + if(destroyed) + return; + + if (FirstThinker == this) + FirstThinker = m_Next; + if (LastThinker == this) + LastThinker = m_Prev; + if (m_Next) + m_Next->m_Prev = m_Prev; + if (m_Prev) + m_Prev->m_Next = m_Next; + + destroyed = true; + + if(refCount) + { + LingerDestroy.push_back(this); // something is still finding this pointer useful + } + else + Super::Destroy (); + + size_t l = LingerDestroy.size(); + for(size_t i = 0; i < l; i++) + { + DThinker *obj = LingerDestroy[i]; + if(!obj->refCount) + { + obj->ObjectFlags |= OF_Cleanup; + LingerDestroy.erase(LingerDestroy.begin() + i); + l--; i--; + delete obj; + } + } +} + +bool DThinker::WasDestroyed () +{ + return destroyed; +} + +// Destroy every thinker +void DThinker::DestroyAllThinkers () +{ + DThinker *currentthinker = FirstThinker; + while (currentthinker) + { + DThinker *next = currentthinker->m_Next; + currentthinker->Destroy (); + currentthinker = next; + } + DObject::EndFrame (); + + size_t l = LingerDestroy.size(); + for(size_t i = 0; i < l; i++) + { + DThinker *obj = LingerDestroy[i]; +// if(!obj->refCount) + { + obj->ObjectFlags |= OF_Cleanup; + delete obj; + } + } + LingerDestroy.clear(); +} + +// Destroy all thinkers except for player-controlled actors +void DThinker::DestroyMostThinkers () +{ + DThinker *thinker = FirstThinker; + while (thinker) + { + DThinker *next = thinker->m_Next; + if (!thinker->IsKindOf (RUNTIME_CLASS (AActor)) || + static_cast(thinker)->player == NULL || + static_cast(thinker)->player->mo + != static_cast(thinker)) + { + thinker->Destroy (); + } + thinker = next; + } + DObject::EndFrame (); +} + +EXTERN_CVAR (sv_speedhackfix) + +// +// IndependentThinker +// +// Returns true if a DThinker object is ticked independently elsewhere. +// Returns false if it should be ticked in DThinker::RunThinkers +// +bool IndependentThinker(DThinker *thinker) +{ + // Only have independent thinkers in client/server mode + if (!multiplayer || demoplayback) + return false; + + if (thinker->IsKindOf (RUNTIME_CLASS (AActor))) + { + AActor *mobj = static_cast(thinker); + if (!mobj->player || mobj->player->spectator) + return false; + + // Clientside prediction takes care of ticking + if (clientside) + return true; + + // Server ticks players as it processes their ticcmds + if (serverside) + return true; + } + + if (thinker->IsA(RUNTIME_CLASS (DPillar)) || + thinker->IsA(RUNTIME_CLASS (DElevator)) || + thinker->IsA(RUNTIME_CLASS (DFloor)) || + thinker->IsA(RUNTIME_CLASS (DCeiling)) || + thinker->IsA(RUNTIME_CLASS (DPlat)) || + thinker->IsA(RUNTIME_CLASS (DDoor))) + { + // Client ticks movable sectors in prediction code + if (clientside) + return true; + } + + return false; +} + + +void DThinker::RunThinkers () +{ + DThinker *currentthinker; + + BEGIN_STAT (ThinkCycles); + currentthinker = FirstThinker; + while (currentthinker) + { + if (!IndependentThinker(currentthinker)) + currentthinker->RunThink(); + currentthinker = currentthinker->m_Next; + } + END_STAT (ThinkCycles); +} + +void *DThinker::operator new (size_t size) +{ + return Z_Malloc (size, PU_LEVSPEC, 0); +} + +// Deallocation is lazy -- it will not actually be freed +// until its thinking turn comes up. +void DThinker::operator delete (void *mem) +{ + Z_Free (mem); +} + +VERSION_CONTROL (dthinker_cpp, "$Id$") + diff --git a/pool/shard001/C++/0022550_localhelpmanager.cpp b/pool/shard001/C++/0022550_localhelpmanager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0beb4fa6d1fb24391ee4dff716734e0cbae506d5 --- /dev/null +++ b/pool/shard001/C++/0022550_localhelpmanager.cpp @@ -0,0 +1,111 @@ +/**************************************************************************** +** +** Copyright (C) 2013 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 "localhelpmanager.h" +#include "bookmarkmanager.h" + +#include +#include + +#include + +#include + +using namespace Help::Internal; + +QMutex LocalHelpManager::m_guiMutex; +QHelpEngine* LocalHelpManager::m_guiEngine = 0; + +QMutex LocalHelpManager::m_bkmarkMutex; +BookmarkManager* LocalHelpManager::m_bookmarkManager = 0; + +LocalHelpManager::LocalHelpManager(QObject *parent) + : QObject(parent) + , m_guiNeedsSetup(true) + , m_needsCollectionFile(true) +{ +} + +LocalHelpManager::~LocalHelpManager() +{ + if (m_bookmarkManager) { + m_bookmarkManager->saveBookmarks(); + delete m_bookmarkManager; + m_bookmarkManager = 0; + } + + delete m_guiEngine; + m_guiEngine = 0; +} + +void LocalHelpManager::setupGuiHelpEngine() +{ + if (m_needsCollectionFile) { + m_needsCollectionFile = false; + helpEngine().setCollectionFile(Core::HelpManager::collectionFilePath()); + } + + if (m_guiNeedsSetup) { + m_guiNeedsSetup = false; + helpEngine().setupData(); + } +} + +void LocalHelpManager::setEngineNeedsUpdate() +{ + m_guiNeedsSetup = true; +} + +QHelpEngine &LocalHelpManager::helpEngine() +{ + if (!m_guiEngine) { + QMutexLocker _(&m_guiMutex); + if (!m_guiEngine) { + m_guiEngine = new QHelpEngine(""); + m_guiEngine->setAutoSaveFilter(false); + } + } + return *m_guiEngine; +} + +BookmarkManager& LocalHelpManager::bookmarkManager() +{ + if (!m_bookmarkManager) { + QMutexLocker _(&m_bkmarkMutex); + if (!m_bookmarkManager) { + m_bookmarkManager = new BookmarkManager; + m_bookmarkManager->setupBookmarkModels(); + const QString &url = QString::fromLatin1("qthelp://com.nokia.qtcreator." + "%1%2%3/doc/index.html").arg(IDE_VERSION_MAJOR).arg(IDE_VERSION_MINOR) + .arg(IDE_VERSION_RELEASE); + helpEngine().setCustomValue(QLatin1String("DefaultHomePage"), url); + } + } + return *m_bookmarkManager; +} diff --git a/pool/shard001/C++/0022557_QtAssetFileViewProxyModel.cpp b/pool/shard001/C++/0022557_QtAssetFileViewProxyModel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..14669a7f67d8913f35f0b085edf014e9baea6e65 --- /dev/null +++ b/pool/shard001/C++/0022557_QtAssetFileViewProxyModel.cpp @@ -0,0 +1,60 @@ +/* Copyright (c) Damian Jakub Smoczyk + * + * Contact: jakub.smoczyk@gmail.com + * + * All rights reserved. + * + * This file is part of reVision Project + * + * reVision Project 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. + * + * reVision Project 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 reVision Project. If not, see . + */ + +#include "QtAssetFileViewProxyModel.hpp" + +QtAssetFileViewProxyModel::QtAssetFileViewProxyModel(QObject* parent) + : QSortFilterProxyModel(parent) + , m_useFileTypeFiltering(false) + , m_fileTypeFilter(-1) +{ + +} + +QtAssetFileViewProxyModel::~QtAssetFileViewProxyModel() +{ + +} + +bool QtAssetFileViewProxyModel::filterAcceptsRow(int sourceRow, const QModelIndex& sourceParent) const +{ + if(m_useFileTypeFiltering) + { + QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent); + return (sourceModel()->data(index, ASSET_MODEL_FILETYPE_ROLE).toInt() == m_fileTypeFilter); + } + else + { + return QSortFilterProxyModel::filterAcceptsRow(sourceRow, sourceParent); + } +} + +void QtAssetFileViewProxyModel::setUseFileTypeFilter(bool userFileTypeFilter) +{ + m_useFileTypeFiltering = userFileTypeFilter; +} + +void QtAssetFileViewProxyModel::setFileTypeFilter(RafHeader::Type fileType) +{ + m_fileTypeFilter = static_cast(fileType); +} + diff --git a/pool/shard001/C++/0022559_netbuf-test.cpp b/pool/shard001/C++/0022559_netbuf-test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..989eb4547bba1b1d9e15afba89e41d81e2ae1c02 --- /dev/null +++ b/pool/shard001/C++/0022559_netbuf-test.cpp @@ -0,0 +1,227 @@ +#if OBSOLETE +#include + +#include +#include +#include "exp/misc.hpp" +#include +#include +#if __cplusplus >= 201103L +#include "platform/generic/malloc_netbuf.h" +#endif +#include "test-data.h" +#include "test-observer.h" + +#include +#include + +using namespace moducom::io::experimental; +using namespace moducom::coap; +using namespace embr::experimental; + +namespace std { + +std::ostream& operator << ( std::ostream& os, Decoder::State const& value ) { + os << get_description(value); + return os; +} + +} + + + + +template +static void suite(NetBufDecoder& decoder) +{ + decoder.header(); + decoder.token(); + + // NOTE: Flawed, because option_iterator sometimes wants + // a reference for its parameter into NetBufDecoder. Though in this + // unit test, that is so far not the case + option_iterator > it(decoder); + + while(it.valid()) ++it; + + INFO(decoder.state()); + REQUIRE((decoder.state() == Decoder::Payload || decoder.state() == Decoder::Done)); +} + + + +TEST_CASE("netbuf+coap tests", "[netbuf-coap]") +{ + typedef estd::const_buffer chunk_t; + + SECTION("writer") + { + // FIX: This is a bad test, writer shouldn't be prepopulated! + NetBufWriter writer(buffer_16bit_delta); + + REQUIRE(writer.size() == sizeof(buffer_16bit_delta)); + } + SECTION("reader") + { + NetBufReader reader(buffer_16bit_delta); + + REQUIRE(reader.netbuf().length_unprocessed() == sizeof(buffer_16bit_delta)); + } + SECTION("netbuf decoder") + { + NetBufDecoder decoder(buffer_16bit_delta); + + Header header = decoder.header(); + + REQUIRE(header.message_id() == 0x0123); + REQUIRE(header.token_length() == 0); + + moducom::coap::layer3::Token token = decoder.token(); + + REQUIRE(token.size() == 0); + + // from RFC7252 + // "(Note that every message carries a token, even if it is of zero length.)" + REQUIRE(decoder.state() == Decoder::OptionsStart); + } + SECTION("'simplest' (data) incoming decoder") + { + NetBufDecoder reader(buffer_simplest_request); + + reader.header(); + reader.token(); + reader.begin_option_experimental(); + + REQUIRE(reader.netbuf().length_unprocessed() == sizeof(buffer_simplest_request)); + } + SECTION("0-length value option") + { + NetBufDecoder decoder(buffer_oversimplified_observe); + + Header header = decoder.header(); + + decoder.token(); + + decoder.begin_option_experimental(); + + REQUIRE(decoder.state() == Decoder::Options); + + // FIX: clumsy call - have to make this *after* option header, but but also + // after checking decoder.state() + decoder.process_option_header_experimental(); + + REQUIRE(decoder.option_number() == Option::Observe); + + chunk_t value = decoder.option(); + + REQUIRE(value.size() == 0); + } +#if __cplusplus >= 201103L + SECTION("netbuf copy") + { + NetBufReadOnlyMemory buf1(buffer_simplest_request); + NetBufDynamicExperimental buf2; + + coap_netbuf_copy(buf1, buf2); + + REQUIRE(buf2.length_processed() == 4); + REQUIRE(memcmp(buf1.processed(), buf2.processed(), 4) == 0); + } + SECTION("netbuf copy ('skip' feature)") + { + NetBufReadOnlyMemory buf1(buffer_simplest_request); + NetBufDynamicExperimental buf2; + + coap_netbuf_copy(buf1, buf2, 1); + + REQUIRE(buf2.length_processed() == 3); + REQUIRE(memcmp(buf1.processed() + 1, buf2.processed(), 3) == 0); + } +#endif + SECTION("coap NetBufDecoder suite") + { + SECTION("No option, no payload") + { + NetBufDecoder decoder(buffer_simplest_request); + + suite(decoder); + } + SECTION("With option (small), no payload") + { + NetBufDecoder decoder(buffer_oversimplified_observe); + + suite(decoder); + } + /* + SECTION("With option, no payload") + { + NetBufDecoder decoder(buffer_oversimplified_observe); + + suite(decoder); + } */ + SECTION("No option, with payload") + { + NetBufDecoder decoder(buffer_payload_only); + + suite(decoder); + + REQUIRE(decoder.state() == Decoder::Payload); + } + SECTION("With option, with payload") + { + NetBufDecoder decoder(buffer_16bit_delta); + + suite(decoder); + + REQUIRE(decoder.state() == Decoder::Payload); + } + } + SECTION("token decoding") + { + NetBufDecoder decoder(buffer_with_token); + + Header header = decoder.header(); + + REQUIRE(header.token_length() == 2); + + SECTION("layer2") + { + moducom::coap::layer2::Token token; + + decoder.token(&token); + + REQUIRE(token.size() == 2); + REQUIRE(token.data()[0] == 0x77); + REQUIRE(token.data()[1] == 0x78); + } + SECTION("layer3") + { + moducom::coap::layer3::Token token = decoder.token(); + + REQUIRE(token.size() == 2); + REQUIRE(token.data()[0] == 0x77); + REQUIRE(token.data()[1] == 0x78); + } + } + SECTION("embr based netbuf") + { + typedef embr::mem::experimental::NetBufDynamic<> netbuf_t; + netbuf_t nb; + + // TODO: Consider instead a 'shrink' method like PBUF has + nb.expand(sizeof(buffer_16bit_delta), true); + REQUIRE(nb.data() != NULLPTR); + memcpy(nb.data(), buffer_16bit_delta, sizeof(buffer_16bit_delta)); + + // FIX: netbuf not reflecting proper size, need a kind of shrink operation + // *or* decoder needs to be smart enough to handle that + // *or* we have some kind of netbuf wrapper/reader + NetBufDecoder decoder(nb); + + // FIX: We actually pass an invalid size (128) in since nb.expand + // is subject to a minimum allocation size. Still, this works + // since suite doesn't fully process payload + suite(decoder); + } +} +#endif \ No newline at end of file diff --git a/pool/shard001/C++/0022565_Lobby.cpp b/pool/shard001/C++/0022565_Lobby.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f5803f3fcfabb246df9c46b00d120d55b6a3a9f3 --- /dev/null +++ b/pool/shard001/C++/0022565_Lobby.cpp @@ -0,0 +1,297 @@ +// Lobby.cpp +// KlayGE ÓÎÏ·´óÌü ʵÏÖÎļþ +// Ver 1.4.8.3 +// °æÈ¨ËùÓÐ(C) ¹¨ÃôÃô, 2003 +// Homepage: http://www.klayge.org +// +// 1.4.8.3 +// ³õ´Î½¨Á¢ (2003.3.8) +// +// Ð޸ļǼ +///////////////////////////////////////////////////////////////////////////////// + +#include +#include + +#include +#include +#include + +#include +#include + +#ifndef KLAYGE_PLATFORM_WINDOWS_RUNTIME + +namespace KlayGE +{ + // ¹¹Ô캯Êý + ///////////////////////////////////////////////////////////////////////////////// + Lobby::Lobby() + { + this->socket_.Create(SOCK_DGRAM); + } + + // Îö¹¹º¯Êý + ///////////////////////////////////////////////////////////////////////////////// + Lobby::~Lobby() + { + Close(); + } + + Lobby::PlayerAddrsIter Lobby::ID(sockaddr_in const & addr) + { + for (KLAYGE_AUTO(iter, players_.begin()); iter != players_.end(); ++ iter) + { + if (0 == std::memcmp(&addr, &(iter->second.addr), sizeof(addr))) + { + return iter; + } + } + + return players_.end(); + } + + // ½¨Á¢ÓÎÏ·´óÌü + ///////////////////////////////////////////////////////////////////////////////// + void Lobby::Create(std::string const & Name, char maxPlayers, uint16_t port, Processor const & pro) + { + this->LobbyName(Name); + + this->MaxPlayers(maxPlayers); + + this->socket_.Bind(TransAddr("", port)); + + sockaddr_in from; + char revBuf[Max_Buffer]; + char sendBuf[Max_Buffer]; + int numSend = 0; + for (;;) + { + this->Receive(revBuf, sizeof(revBuf), from); + + // ÿ¸öÏûÏ¢Ç°Ãæ¶¼°üº¬1×Ö½ÚµÄÏûÏ¢ÀàÐÍ + char* revPtr(&revBuf[1]); + char* sendPtr(&sendBuf[1]); + sendBuf[0] = revBuf[0]; + + switch (revBuf[0]) + { + case MSG_JOIN: + this->OnJoin(revPtr, sendPtr, numSend, from, pro); + break; + + case MSG_QUIT: + this->OnQuit(this->ID(from), sendPtr, numSend, pro); + break; + + case MSG_GETLOBBYINFO: + this->OnGetLobbyInfo(sendPtr, numSend, pro); + break; + + case MSG_NOP: + this->OnNop(this->ID(from)); + break; + + default: + pro.OnDefault(revBuf, sizeof(revBuf), sendBuf, numSend, from); + break; + } + + if (numSend != 0) + { + this->Send(sendBuf, numSend + 1, from); + } + + // ·¢ËÍÐÅÏ¢ + typedef KLAYGE_DECLTYPE(players_) PlayersType; + KLAYGE_FOREACH(PlayersType::reference player, players_) + { + SendQueueType& msgs = player.second.msgs; + typedef KLAYGE_DECLTYPE(msgs) MsgsType; + KLAYGE_FOREACH(MsgsType::reference msg, msgs) + { + socket_.SendTo(&msg[0], static_cast(msg.size()), player.second.addr); + } + } + + // ¼ì²éÊÇ·ñÓÐÔÚÏßÓû§³¬Ê± + for (KLAYGE_AUTO(iter, players_.begin()); iter != players_.end();) + { + // ´óÓÚ20Ãë + if (std::time(nullptr) - iter->second.time >= 20 * 1000) + { + iter = players_.erase(iter); + } + else + { + ++ iter; + } + } + } + } + + // ÉèÖÃ×î´óÈËÊý + ///////////////////////////////////////////////////////////////////////////////// + char Lobby::NumPlayer() const + { + char n = 0; + typedef KLAYGE_DECLTYPE(players_) PlayersType; + KLAYGE_FOREACH(PlayersType::const_reference player, players_) + { + if (player.first != 0) + { + ++ n; + } + } + + return n; + } + + // ÉèÖôóÌüÃû³Æ + ///////////////////////////////////////////////////////////////////////////////// + void Lobby::LobbyName(std::string const & name) + { + if (name.length() > 16) + { + this->name_ = name.substr(0, 16); + } + else + { + this->name_ = name; + } + } + + // »ñÈ¡´óÌüÃû³Æ + ///////////////////////////////////////////////////////////////////////////////// + std::string const & Lobby::LobbyName() const + { + return this->name_; + } + + // ÉèÖÃ×î´óÈËÊý + ///////////////////////////////////////////////////////////////////////////////// + void Lobby::MaxPlayers(char maxPlayers) + { + players_.resize(maxPlayers); + PlayerAddrs(players_).swap(players_); + + typedef KLAYGE_DECLTYPE(players_) PlayersType; + KLAYGE_FOREACH(PlayersType::reference player, players_) + { + player.first = 0; + } + } + + // »ñÈ¡×î´óÈËÊý + ///////////////////////////////////////////////////////////////////////////////// + char Lobby::MaxPlayers() const + { + return static_cast(this->players_.size()); + } + + // ¹Ø±ÕÓÎÏ·´óÌü + ///////////////////////////////////////////////////////////////////////////////// + void Lobby::Close() + { + this->socket_.Close(); + } + + // ·¢ËÍÊý¾Ý + ///////////////////////////////////////////////////////////////////////////////// + int Lobby::Receive(void* buf, int maxSize, sockaddr_in& from) + { + return this->socket_.ReceiveFrom(buf, maxSize, from); + } + + // ½ÓÊÕÊý¾Ý + ///////////////////////////////////////////////////////////////////////////////// + int Lobby::Send(void const * buf, int maxSize, sockaddr_in const & to) + { + return this->socket_.SendTo(buf, maxSize, to); + } + + + void Lobby::OnJoin(char* revBuf, char* sendBuf, int& numSend, + sockaddr_in& from, Processor const & pro) + { + // ÃüÁî¸ñʽ: + // PlayerÃû×Ö 16 ×Ö½Ú + + char id = 1; + KLAYGE_AUTO(iter, players_.begin()); + for (; iter != this->players_.end(); ++ iter, ++ id) + { + if (0 == iter->first) + { + size_t i(0); + while (revBuf[i] != 0) + { + ++ i; + } + std::string name(&revBuf[0], i); + iter->first = id; + iter->second.name = name; + iter->second.addr = from; + + pro.OnJoin(iter->first); + break; + } + } + + // ·µ»Ø¸ñʽ: + // Player ID 1 ×Ö½Ú + + // ÒѾ­ÂúÁË + if (iter == players_.end()) + { + sendBuf[0] = 1; + } + else + { + sendBuf[0] = 0; + } + + numSend = 1; + } + + void Lobby::OnQuit(PlayerAddrsIter iter, char* sendBuf, + int& numSend, Processor const & pro) + { + if (iter != this->players_.end()) + { + pro.OnQuit(iter->first); + iter->first = 0; + sendBuf[0] = 0; + } + else + { + sendBuf[0] = 1; + } + + numSend = 1; + } + + void Lobby::OnGetLobbyInfo(char* sendBuf, int& numSend, Processor const & /*pro*/) + { + // ·µ»Ø¸ñʽ: + // µ±Ç°PlayersÊý 1 ×Ö½Ú + // ×î´óPlayersÊý 1 ×Ö½Ú + // LobbyÃû×Ö 16 ×Ö½Ú + + std::fill_n(sendBuf, 18, 0); + sendBuf[0] = this->NumPlayer(); + sendBuf[1] = this->MaxPlayers(); + this->LobbyName().copy(&sendBuf[2], this->LobbyName().length()); + numSend = 18; + } + + void Lobby::OnNop(PlayerAddrsIter iter) + { + if (iter != this->players_.end()) + { + iter->second.time = static_cast(std::time(nullptr)); + } + } +} + +#endif diff --git a/pool/shard001/C++/0022568_chrome_proxy_main_dialog_unittest.cc b/pool/shard001/C++/0022568_chrome_proxy_main_dialog_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..3c2d3455f1e9364504afb08c31ca561023305857 --- /dev/null +++ b/pool/shard001/C++/0022568_chrome_proxy_main_dialog_unittest.cc @@ -0,0 +1,166 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/chrome_cleaner/ui/chrome_proxy_main_dialog.h" + +#include +#include + +#include "base/callback.h" +#include "base/files/scoped_temp_dir.h" +#include "base/run_loop.h" +#include "base/test/task_environment.h" +#include "chrome/chrome_cleaner/ipc/chrome_prompt_test_util.h" +#include "chrome/chrome_cleaner/test/test_file_util.h" +#include "chrome/chrome_cleaner/test/test_pup_data.h" +#include "chrome/chrome_cleaner/test/test_settings_util.h" +#include "chrome/chrome_cleaner/ui/mock_main_dialog_delegate.h" +#include "components/chrome_cleaner/public/proto/chrome_prompt.pb.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace chrome_cleaner { +namespace { + +using ::testing::_; +using ::testing::Eq; +using ::testing::Invoke; +using ::testing::SizeIs; +using ::testing::StrictMock; + +class ChromeProxyMainDialogTest : public ::testing::Test { + public: + void SetUp() override { + // StrictMock will ensure that the cleaner will not send an IPC to Chrome + // when the functions tested by this fixture get called. + dialog_ = std::make_unique(&delegate_, + &chrome_prompt_ipc_); + } + + StrictMock chrome_prompt_ipc_; + StrictMock delegate_; + std::unique_ptr dialog_; +}; + +TEST_F(ChromeProxyMainDialogTest, Create) { + dialog_->Create(); +} + +TEST_F(ChromeProxyMainDialogTest, NoPUPsFound) { + base::test::SingleThreadTaskEnvironment task_environment( + base::test::SingleThreadTaskEnvironment::MainThreadType::UI); + + base::RunLoop run_loop; + EXPECT_CALL(delegate_, OnClose()) + .WillOnce(testing::InvokeWithoutArgs([&run_loop]() { run_loop.Quit(); })); + EXPECT_CALL(chrome_prompt_ipc_, MockPostPromptUserTask(_, _, _, _)) + .WillOnce(Invoke([](const std::vector& files_to_delete, + const std::vector& registry_keys, + const std::vector& extension_ids, + ChromePromptIPC::PromptUserCallback* callback) { + std::move(*callback).Run(PromptUserResponse::DENIED); + })); + + dialog_->NoPUPsFound(); + run_loop.Run(); +} + +TEST_F(ChromeProxyMainDialogTest, CleanupDone) { + EXPECT_CALL(delegate_, OnClose()).Times(1); + dialog_->CleanupDone(RESULT_CODE_SUCCESS); +} + +TEST_F(ChromeProxyMainDialogTest, Close) { + EXPECT_CALL(delegate_, OnClose()).Times(1); + dialog_->Close(); +} + +class ConfirmCleanupChromeProxyMainDialogTest + : public ::testing::TestWithParam { + public: + void SetUp() override { Settings::SetInstanceForTesting(&mock_settings_); } + + void TearDown() override { Settings::SetInstanceForTesting(nullptr); } + + StrictMock mock_settings_; +}; + +// Flaky, see: crbug.com/1189076. +TEST_P(ConfirmCleanupChromeProxyMainDialogTest, DISABLED_ConfirmCleanup) { + constexpr UwSId kFakePupId = 1024; + PromptUserResponse::PromptAcceptance prompt_acceptance = GetParam(); + bool accept_cleanup = + prompt_acceptance == PromptUserResponse::ACCEPTED_WITH_LOGS || + prompt_acceptance == PromptUserResponse::ACCEPTED_WITHOUT_LOGS; + bool logs_allowed = + prompt_acceptance == PromptUserResponse::ACCEPTED_WITH_LOGS; + + base::test::SingleThreadTaskEnvironment task_environment( + base::test::SingleThreadTaskEnvironment::MainThreadType::UI); + + EXPECT_CALL(mock_settings_, + set_logs_allowed_in_cleanup_mode(Eq(logs_allowed))) + .Times(1); + + // Add a PUP and some disk footprints. Footprints should be passed along via + // the IPC. + TestPUPData test_pup_data; + test_pup_data.AddPUP(kFakePupId, PUPData::FLAGS_ACTION_REMOVE, "", + PUPData::kMaxFilesToRemoveSmallUwS); + PUPData::PUP* pup = PUPData::GetPUP(kFakePupId); + EXPECT_TRUE(pup->AddDiskFootprint( + base::FilePath(FILE_PATH_LITERAL("c:\\file1.exe")))); + EXPECT_TRUE(pup->AddDiskFootprint( + base::FilePath(FILE_PATH_LITERAL("c:\\file2.exe")))); + EXPECT_TRUE(pup->AddDiskFootprint( + base::FilePath(FILE_PATH_LITERAL("c:\\file3.txt")))); + + // This file is recognized by the DigestVerifier and should not be sent. + base::ScopedTempDir temp_dir; + ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); + base::FilePath known_file = temp_dir.GetPath().Append(L"known_file.exe"); + ASSERT_TRUE(chrome_cleaner::CreateFileInFolder( + known_file.DirName(), known_file.BaseName().value())); + auto digest_verifier = + chrome_cleaner::DigestVerifier::CreateFromFile(known_file); + EXPECT_TRUE(pup->AddDiskFootprint(known_file)); + + pup->expanded_registry_footprints.push_back(PUPData::RegistryFootprint( + RegKeyPath(HKEY_USERS, L"Software\\bad-software\\bad-key"), + std::wstring(), std::wstring(), REGISTRY_VALUE_MATCH_KEY)); + + std::vector found_pups{kFakePupId}; + + StrictMock chrome_prompt_ipc; + EXPECT_CALL(chrome_prompt_ipc, + MockPostPromptUserTask(/*files_to_delete*/ SizeIs(3), + /*registry_keys*/ SizeIs(1), + /*extensions*/ SizeIs(0), _)) + .WillOnce(Invoke([prompt_acceptance]( + const std::vector& files_to_delete, + const std::vector& registry_keys, + const std::vector& extension_ids, + ChromePromptIPC::PromptUserCallback* callback) { + std::move(*callback).Run(prompt_acceptance); + })); + + StrictMock delegate; + base::RunLoop run_loop; + EXPECT_CALL(delegate, AcceptedCleanup(Eq(accept_cleanup))) + .WillOnce(testing::InvokeWithoutArgs([&run_loop]() { run_loop.Quit(); })); + + ChromeProxyMainDialog dialog(&delegate, &chrome_prompt_ipc); + dialog.ConfirmCleanupIfNeeded(found_pups, digest_verifier); + run_loop.Run(); +} + +INSTANTIATE_TEST_SUITE_P( + All, + ConfirmCleanupChromeProxyMainDialogTest, + testing::Values(PromptUserResponse::ACCEPTED_WITH_LOGS, + PromptUserResponse::ACCEPTED_WITHOUT_LOGS, + PromptUserResponse::DENIED)); + +} // namespace +} // namespace chrome_cleaner diff --git a/pool/shard001/C++/0022570_PortabilityTest.cpp b/pool/shard001/C++/0022570_PortabilityTest.cpp new file mode 100644 index 0000000000000000000000000000000000000000..923c2391cbdcc46590fbbfce8e9f4113c5dd5a36 --- /dev/null +++ b/pool/shard001/C++/0022570_PortabilityTest.cpp @@ -0,0 +1,44 @@ +/* + * Copyright 2015 Facebook, 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 + +class Base { + public: + virtual ~Base() { } + virtual int foo() const { return 1; } +}; + +class Derived : public Base { + public: + int foo() const final { return 2; } +}; + +// A compiler that supports final will likely inline the call to p->foo() +// in fooDerived (but not in fooBase) as it knows that Derived::foo() can +// no longer be overridden. +int fooBase(const Base* p) { return p->foo() + 1; } +int fooDerived(const Derived* p) { return p->foo() + 1; } + +TEST(Portability, Final) { + std::unique_ptr p(new Derived); + EXPECT_EQ(3, fooBase(p.get())); + EXPECT_EQ(3, fooDerived(p.get())); +} diff --git a/pool/shard001/C++/0022571_warn.cc b/pool/shard001/C++/0022571_warn.cc new file mode 100644 index 0000000000000000000000000000000000000000..52631a866592661850c77c0c19053d1e35fd1c3e --- /dev/null +++ b/pool/shard001/C++/0022571_warn.cc @@ -0,0 +1,71 @@ +/* + warn.cc -- implement warnings + + source file of the Flower Library + + (c) 1997--2007 Han-Wen Nienhuys +*/ + +#include "warn.hh" + +#include +#include + +#include "international.hh" + +using namespace std; + +/* Is progress indication at NEWLINE? */ +static bool progress_newline = true; + +/* Display user information that is not a full message. */ +void +progress_indication (string s) +{ + /* Test if all silly progress_indication ("\n") can be dropped now. */ + if (s == "\n") + return; + + fputs (s.c_str (), stderr); + fflush (stderr); + if (s.length ()) + progress_newline = s[s.length () - 1] == '\n'; +} + +/* Display a single user message. Always starts on a new line. */ +void +message (string s) +{ + if (!progress_newline) + fputc ('\n', stderr); + progress_indication (s); +} + +/* Display a warning message. Always starts on a new line. */ +void +warning (string s) +{ + message (_f ("warning: %s", s.c_str ()) + "\n"); +} + +void +non_fatal_error (string s) +{ + message (_f ("error: %s", s.c_str ()) + "\n"); +} + +/* Display an error message. Always starts on a new line. */ +void +error (string s) +{ + non_fatal_error (s); + exit (1); +} + +void +programming_error (string s) +{ + message (_f ("programming error: %s", s) + "\n"); + message (_ ("continuing, cross fingers") + "\n"); +} + diff --git a/pool/shard001/C++/0022574_signin_confirmation_unittest.cc b/pool/shard001/C++/0022574_signin_confirmation_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..fc22e04955e6eadd4b6bccc7480b9d0897636ab7 --- /dev/null +++ b/pool/shard001/C++/0022574_signin_confirmation_unittest.cc @@ -0,0 +1,82 @@ +// Copyright 2020 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/enterprise/connectors/file_system/signin_confirmation_modal.h" + +#include "base/strings/utf_string_conversions.h" +#include "base/test/bind.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "ui/base/models/image_model.h" +#include "ui/views/controls/label.h" +#include "ui/views/test/test_layout_provider.h" + +using testing::_; +using testing::Invoke; +using testing::Return; + +namespace enterprise_connectors { + +const std::u16string kTestTitle = base::UTF8ToUTF16(std::string("title")); +const std::u16string kTestMessage = base::UTF8ToUTF16(std::string("message")); +const std::u16string kTestCancel = base::UTF8ToUTF16(std::string("cancel")); +const std::u16string kTestAccept = base::UTF8ToUTF16(std::string("accept")); + +class FileSystemConfirmationModalTest : public testing::Test { + public: + void SetUp() override { + modal = std::unique_ptr( + new FileSystemConfirmationModal( + kTestTitle, kTestMessage, kTestCancel, kTestAccept, + base::BindOnce(&FileSystemConfirmationModalTest::OnUserClick, + base::Unretained(this)))); + } + + std::unique_ptr modal; + bool callback_ran = false; + bool callback_user_accepted = false; + + private: + void OnUserClick(bool user_accepted) { + callback_ran = true; + callback_user_accepted = user_accepted; + } + + // For GetContentsView() which needs views::layout::GetFont(). + views::test::TestLayoutProvider layout_provider; +}; + +TEST_F(FileSystemConfirmationModalTest, GetUIProperties) { + ASSERT_TRUE(modal->ShouldShowWindowTitle()); + ASSERT_TRUE(modal->ShouldShowWindowIcon()); + ASSERT_FALSE(modal->ShouldShowCloseButton()); + + ASSERT_EQ(modal->GetWindowTitle(), kTestTitle); + ASSERT_EQ(modal->GetAccessibleWindowTitle(), kTestTitle); + ASSERT_EQ(modal->GetModalType(), ui::MODAL_TYPE_WINDOW); + + auto icon = modal->GetWindowIcon(); + ASSERT_FALSE(icon.IsEmpty()); + ASSERT_TRUE(icon.IsImage()); + + views::View* message_view = modal->GetContentsView(); + ASSERT_NE(message_view, nullptr); + // Check on the message text. + views::Label* message_label = static_cast(message_view); + ASSERT_EQ(message_label->GetText(), kTestMessage); +} + +TEST_F(FileSystemConfirmationModalTest, ClickAccept) { + modal->Accept(); + ASSERT_TRUE(callback_ran); + ASSERT_TRUE(callback_user_accepted); +} + +TEST_F(FileSystemConfirmationModalTest, ClickCancel) { + modal->Cancel(); + ASSERT_TRUE(callback_ran); + ASSERT_FALSE(callback_user_accepted); +} + +} // namespace enterprise_connectors diff --git a/pool/shard001/C++/0022576_helloworldplugin.cpp b/pool/shard001/C++/0022576_helloworldplugin.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4f5f6ef42a959bfd4e5d59cf72f69b8dff0f78d5 --- /dev/null +++ b/pool/shard001/C++/0022576_helloworldplugin.cpp @@ -0,0 +1,147 @@ +/**************************************************************************** +** +** 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 "helloworldplugin.h" + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace HelloWorld { +namespace Internal { + +/*! A mode with a push button based on BaseMode. */ + +class HelloMode : public Core::IMode +{ +public: + HelloMode() + { + setWidget(new QPushButton(tr("Hello World PushButton!"))); + setContext(Core::Context("HelloWorld.MainView")); + setDisplayName(tr("Hello world!")); + setIcon(QIcon()); + setPriority(0); + setId("HelloWorld.HelloWorldMode"); + } +}; + + +/*! Constructs the Hello World plugin. Normally plugins don't do anything in + their constructor except for initializing their member variables. The + actual work is done later, in the initialize() and extensionsInitialized() + functions. +*/ +HelloWorldPlugin::HelloWorldPlugin() +{ +} + +/*! Plugins are responsible for deleting objects they created on the heap, and + to unregister objects from the plugin manager that they registered there. +*/ +HelloWorldPlugin::~HelloWorldPlugin() +{ + delete m_helloMode; +} + +/*! Initializes the plugin. Returns true on success. + Plugins want to register objects with the plugin manager here. + + \a errorMessage can be used to pass an error message to the plugin system, + if there was any. +*/ +bool HelloWorldPlugin::initialize(const QStringList &arguments, QString *errorMessage) +{ + Q_UNUSED(arguments) + Q_UNUSED(errorMessage) + + // Create a unique context for our own view, that will be used for the + // menu entry later. + Core::Context context("HelloWorld.MainView"); + + // Create an action to be triggered by a menu entry + auto helloWorldAction = new QAction(tr("Say \"&Hello World!\""), this); + connect(helloWorldAction, &QAction::triggered, this, &HelloWorldPlugin::sayHelloWorld); + + // Register the action with the action manager + Core::Command *command = + Core::ActionManager::registerAction( + helloWorldAction, "HelloWorld.HelloWorldAction", context); + + // Create our own menu to place in the Tools menu + Core::ActionContainer *helloWorldMenu = + Core::ActionManager::createMenu("HelloWorld.HelloWorldMenu"); + QMenu *menu = helloWorldMenu->menu(); + menu->setTitle(tr("&Hello World")); + menu->setEnabled(true); + + // Add the Hello World action command to the menu + helloWorldMenu->addAction(command); + + // Request the Tools menu and add the Hello World menu to it + Core::ActionContainer *toolsMenu = + Core::ActionManager::actionContainer(Core::Constants::M_TOOLS); + toolsMenu->addMenu(helloWorldMenu); + + // Add a mode with a push button based on BaseMode. + m_helloMode = new HelloMode; + + return true; +} + +/*! Notification that all extensions that this plugin depends on have been + initialized. The dependencies are defined in the plugins .json(.in) file. + + Normally this function is used for things that rely on other plugins to have + added objects to the plugin manager, that implement interfaces that we're + interested in. These objects can now be requested through the + PluginManager. + + The HelloWorldPlugin doesn't need things from other plugins, so it does + nothing here. +*/ +void HelloWorldPlugin::extensionsInitialized() +{ +} + +void HelloWorldPlugin::sayHelloWorld() +{ + // When passing nullptr for the parent, the message box becomes an + // application-global modal dialog box + QMessageBox::information( + nullptr, tr("Hello World!"), tr("Hello World! Beautiful day today, isn't it?")); +} + +} // namespace Internal +} // namespace HelloWorld diff --git a/pool/shard001/C++/0022581_ContextMenus.cpp b/pool/shard001/C++/0022581_ContextMenus.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f072e3ea339539957132149fe49d898b010673ef --- /dev/null +++ b/pool/shard001/C++/0022581_ContextMenus.cpp @@ -0,0 +1,99 @@ +/* + * Copyright (C) 2016-2018 Team Kodi + * This file is part of Kodi - https://kodi.tv + * + * SPDX-License-Identifier: GPL-2.0-or-later + * See LICENSES/README.md for more information. + */ + +#include "ContextMenus.h" + +#include "ServiceBroker.h" +#include "favourites/FavouritesService.h" +#include "guilib/GUIComponent.h" +#include "guilib/GUIWindowManager.h" +#include "input/WindowTranslator.h" +#include "storage/MediaManager.h" +#include "utils/URIUtils.h" +#include "utils/Variant.h" + +namespace CONTEXTMENU +{ + + bool CEjectDisk::IsVisible(const CFileItem& item) const + { +#ifdef HAS_DVD_DRIVE + return item.IsRemovable() && (item.IsDVD() || item.IsCDDA()); +#else + return false; +#endif + } + + bool CEjectDisk::Execute(const CFileItemPtr& item) const + { +#ifdef HAS_DVD_DRIVE + CServiceBroker::GetMediaManager().ToggleTray( + CServiceBroker::GetMediaManager().TranslateDevicePath(item->GetPath())[0]); +#endif + return true; + } + + bool CEjectDrive::IsVisible(const CFileItem& item) const + { + // Must be HDD + return item.IsRemovable() && !item.IsDVD() && !item.IsCDDA(); + } + + bool CEjectDrive::Execute(const CFileItemPtr& item) const + { + return CServiceBroker::GetMediaManager().Eject(item->GetPath()); + } + +namespace +{ + +int GetTargetWindowID(const CFileItem& item) +{ + int iTargetWindow = WINDOW_INVALID; + + const std::string targetWindow = item.GetProperty("targetwindow").asString(); + if (targetWindow.empty()) + iTargetWindow = CServiceBroker::GetGUI()->GetWindowManager().GetActiveWindow(); + else + iTargetWindow = CWindowTranslator::TranslateWindow(targetWindow); + + return iTargetWindow; +} + +} // unnamed namespace + +std::string CAddRemoveFavourite::GetLabel(const CFileItem& item) const +{ + return g_localizeStrings.Get(CServiceBroker::GetFavouritesService().IsFavourited(item, GetTargetWindowID(item)) + ? 14077 /* Remove from favourites */ + : 14076); /* Add to favourites */ +} + +bool CAddRemoveFavourite::IsVisible(const CFileItem& item) const +{ + return (!item.GetPath().empty() && !item.IsParentFolder() && !item.IsPath("add") && + !item.IsPath("newplaylist://") && !URIUtils::IsProtocol(item.GetPath(), "favourites") && + !URIUtils::IsProtocol(item.GetPath(), "newsmartplaylist") && + !URIUtils::IsProtocol(item.GetPath(), "newtag") && + !URIUtils::IsProtocol(item.GetPath(), "musicsearch") && + // hide this item for all PVR timers/EPG except timer/timer rules/EPG root folders + !StringUtils::StartsWith(item.GetPath(), "pvr://guide/") && + !StringUtils::StartsWith(item.GetPath(), "pvr://timers/")) || + item.GetPath() == "pvr://guide/tv/" || item.GetPath() == "pvr://guide/radio/" || + item.GetPath() == "pvr://timers/tv/timers/" || + item.GetPath() == "pvr://timers/radio/timers/" || + item.GetPath() == "pvr://timers/tv/rules/" || + item.GetPath() == "pvr://timers/radio/rules/"; +} + +bool CAddRemoveFavourite::Execute(const CFileItemPtr& item) const +{ + return CServiceBroker::GetFavouritesService().AddOrRemove(*item.get(), GetTargetWindowID(*item)); +} + +} // namespace CONTEXTMENU diff --git a/pool/shard001/C++/0022582_exampleDigitalConvexity.cpp b/pool/shard001/C++/0022582_exampleDigitalConvexity.cpp new file mode 100644 index 0000000000000000000000000000000000000000..17866eed969454962b35a14eb15980144f50964e --- /dev/null +++ b/pool/shard001/C++/0022582_exampleDigitalConvexity.cpp @@ -0,0 +1,114 @@ +/** + * 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 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 geometry/curves/exampleDigitalConvexity.cpp + * @ingroup Examples + * @author Jacques-Olivier Lachaud (\c jacques-olivier.lachaud@univ-savoie.fr ) + * Laboratory of Mathematics (CNRS, UMR 5127), University of Savoie, France + * + * @date 2020/02/02 + * + * @brief An example file for DigitalConvexity in 2D. + * + * This file is part of the DGtal library. + */ + + +/** + This snippet shows how to identify and display digital fully + subconvex sets of a grid curve form its tangent bundle. + + @see \ref moduleDigitalConvexity + + \image html grid-curve-dig-convexity.png "Extraction of all subconvex triangles to the digital curve." + + \example geometry/curves/exampleDigitalConvexity.cpp +*/ + + +/////////////////////////////////////////////////////////////////////////////// +#include + +#include "DGtal/base/Common.h" +#include "DGtal/helpers/StdDefs.h" +#include "ConfigExamples.h" + +#include "DGtal/geometry/curves/FreemanChain.h" +#include "DGtal/geometry/curves/GridCurve.h" +#include "DGtal/geometry/volumes/DigitalConvexity.h" + +#include "DGtal/io/boards/Board2D.h" + +/////////////////////////////////////////////////////////////////////////////// + +using namespace std; +using namespace DGtal; +using namespace Z2i; + + +/////////////////////////////////////////////////////////////////////////////// +int main( int argc, char** argv ) +{ + trace.beginBlock ( "Example for 2d gridcurves" ); + string S = examplesPath + "samples/contourS.fc"; + + // domain + const Point lowerBound( -200, -200 ); + const Point upperBound( 200, 200 ); + + fstream inputStream( S.c_str(), ios::in ); + FreemanChain fc(inputStream); + inputStream.close(); + Curve c; + c.initFromPointsRange( fc.begin(), fc.end() ); + auto points = c.getPointsRange(); + std::vector T( points.begin(), points.end() ); + Board2D aBoard; + aBoard.setUnit(Board2D::UCentimeter); + DigitalConvexity dconv( lowerBound, upperBound ); + auto c_cover = dconv.makeCellCover( T.begin(), T.end(), 1, 1 ); + const float sx = -0.5; + const float sy = -0.5; + trace.beginBlock( "Compute fully subconvex sets" ); + for ( unsigned int i = 0; i < T.size(); ++i ) + for ( unsigned int j = i+2; j < T.size(); ++j ) + { + aBoard.setPenColorRGBi( rand() % 255, rand() % 255, rand() % 255 ); + unsigned int k = (i+j)/2; + if ( ! dconv.isSimplexFullDimensional( { T[i], T[j], T[k] } ) ) continue; + auto triangle = dconv.makeSimplex( { T[i], T[j], T[k] } ); + if ( dconv.isFullySubconvex( triangle, c_cover ) ) + { + aBoard.drawLine( sx+(float)T[i][0], sy+(float)T[i][1], + sx+(float)T[j][0], sy+(float)T[j][1] ); + aBoard.drawLine( sx+(float)T[i][0], sy+(float)T[i][1], + sx+(float)T[k][0], sy+(float)T[k][1] ); + aBoard.drawLine( sx+(float)T[k][0], sy+(float)T[k][1], + sx+(float)T[j][0], sy+(float)T[j][1] ); + } + else + j = T.size(); + } + trace.endBlock(); + aBoard.setPenColor( Color::Black ); + aBoard << c; + aBoard.saveEPS( "myGridCurve.eps", Board2D::BoundingBox );//, 5000 ); + trace.endBlock(); + return 0; +} +// // +/////////////////////////////////////////////////////////////////////////////// diff --git a/pool/shard001/C++/0022586_capture_mode_advanced_settings_test_api.cc b/pool/shard001/C++/0022586_capture_mode_advanced_settings_test_api.cc new file mode 100644 index 0000000000000000000000000000000000000000..5616b22a244030a1347ffaabd9ecfc421cc1b33c --- /dev/null +++ b/pool/shard001/C++/0022586_capture_mode_advanced_settings_test_api.cc @@ -0,0 +1,72 @@ +// 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 "ash/capture_mode/capture_mode_advanced_settings_test_api.h" + +#include "ash/capture_mode/capture_mode_advanced_settings_view.h" +#include "ash/capture_mode/capture_mode_controller.h" +#include "ash/capture_mode/capture_mode_session.h" +#include "ash/constants/ash_features.h" +#include "base/check.h" + +namespace ash { + +namespace { + +CaptureModeSession* GetCaptureModeSession() { + DCHECK(features::AreImprovedScreenCaptureSettingsEnabled()); + auto* controller = CaptureModeController::Get(); + DCHECK(controller->IsActive()); + CaptureModeSession* session = controller->capture_mode_session(); + DCHECK(session->capture_mode_settings_widget()); + return session; +} + +} // namespace + +CaptureModeAdvancedSettingsTestApi::CaptureModeAdvancedSettingsTestApi() + : settings_view_( + GetCaptureModeSession()->capture_mode_advanced_settings_view_) {} + +CaptureModeAdvancedSettingsView* +CaptureModeAdvancedSettingsTestApi::GetAdvancedSettingsView() { + return settings_view_; +} + +CaptureModeMenuGroup* +CaptureModeAdvancedSettingsTestApi::GetAudioInputMenuGroup() { + return settings_view_->audio_input_menu_group_; +} + +views::View* CaptureModeAdvancedSettingsTestApi::GetMicrophoneOption() { + return GetAudioInputMenuGroup()->GetOptionForTesting(kAudioMicrophone); +} + +views::View* CaptureModeAdvancedSettingsTestApi::GetAudioOffOption() { + return GetAudioInputMenuGroup()->GetOptionForTesting(kAudioOff); +} + +CaptureModeMenuGroup* CaptureModeAdvancedSettingsTestApi::GetSaveToMenuGroup() { + return settings_view_->save_to_menu_group_; +} + +views::View* CaptureModeAdvancedSettingsTestApi::GetDefaultDownloadsOption() { + return GetSaveToMenuGroup()->GetOptionForTesting(kDownloadsFolder); +} + +views::View* CaptureModeAdvancedSettingsTestApi::GetCustomFolderOptionIfAny() { + return GetSaveToMenuGroup()->GetOptionForTesting(kCustomFolder); +} + +views::View* CaptureModeAdvancedSettingsTestApi::GetSelectFolderMenuItem() { + return GetSaveToMenuGroup()->GetSelectFolderMenuItemForTesting(); +} + +void CaptureModeAdvancedSettingsTestApi::SetOnSettingsMenuRefreshedCallback( + base::OnceClosure callback) { + settings_view_->on_settings_menu_refreshed_callback_for_test_ = + std::move(callback); +} + +} // namespace ash diff --git a/pool/shard001/C++/0022592_rpcnet.cpp b/pool/shard001/C++/0022592_rpcnet.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bb36359ecb87be8f02f8e2e945f6cb5287a5be88 --- /dev/null +++ b/pool/shard001/C++/0022592_rpcnet.cpp @@ -0,0 +1,193 @@ +// Copyright (c) 2009-2016 Bitcoin Developers +// 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" +#include "ntp.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(); +} + +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)); + obj.push_back(Pair("subver", stats.strSubVer)); + obj.push_back(Pair("inbound", stats.fInbound)); + obj.push_back(Pair("startingheight", stats.nStartingHeight)); + obj.push_back(Pair("banscore", stats.nMisbehavior)); + + ret.push_back(obj); + } + + return ret; +} + +// 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\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 = params[2].get_int(); + alert.nMaxVer = params[3].get_int(); + alert.nPriority = params[4].get_int(); + alert.nID = params[5].get_int(); + if (params.size() > 6) + alert.nCancel = params[6].get_int(); + 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()); + + 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; +} + +/* +05:53:45 ntptime +05:53:48 +{ +"epoch" : 1442494427, +"time" : "2015-09-17 12:53:47 UTC" +} + +05:53:56 ntptime time.windows.com +05:53:57 +{ +"epoch" : 1442494436, +"time" : "2015-09-17 12:53:56 UTC" +} + +05:54:33 ntptime time-a.nist.gov +05:54:34 +{ +"epoch" : 1442494473, +"time" : "2015-09-17 12:54:33 UTC" +}*/ + +Value ntptime(const Array& params, bool fHelp) +{ + if (fHelp || params.size() > 1) + throw runtime_error( + "ntptime [ntpserver]\n" + "Returns current time from specific or random NTP server."); + + int64_t nTime; + if (params.size() > 0) { + string strHostName = params[0].get_str(); + nTime = NtpGetTime(strHostName); + } + else { + CNetAddr ip; + nTime = NtpGetTime(ip); + } + + Object obj; + switch (nTime) { + case -1: + throw runtime_error("Socket initialization error"); + case -2: + throw runtime_error("Switching socket mode to non-blocking failed"); + case -3: + throw runtime_error("Unable to send data"); + case -4: + throw runtime_error("Receive timed out"); + default: + if (nTime > 0 && nTime != 2085978496) { + obj.push_back(Pair("epoch", nTime)); + obj.push_back(Pair("time", DateTimeStrFormat(nTime))); + } + else throw runtime_error("Unexpected response"); + } + + return obj; +} diff --git a/pool/shard001/C++/0022598_PictureDescription.cpp b/pool/shard001/C++/0022598_PictureDescription.cpp new file mode 100644 index 0000000000000000000000000000000000000000..299a8929dd01c2c6de2f7d7b5add243745e80e6c --- /dev/null +++ b/pool/shard001/C++/0022598_PictureDescription.cpp @@ -0,0 +1,77 @@ +#include "PictureDescription.h" +#include + +#include "aws/core/utils/json/JsonSerializer.h" + +PictureDescription::PictureDescription() + : sha256_("") + , iv_("") + , authTag_("") + , fileName_("") + , fileType_("") + , cameraType_("") + , fileSizeBytes_(0) + , dateTimeTaken_(0) + , dateTimeUploaded_(0) + , year_(0) + , month_(0) + , day_(0) +{ +} + +PictureDescription::PictureDescription(const Aws::Utils::Json::JsonValue& jsonDescription) + : sha256_("") + , iv_("") + , authTag_("") + , fileName_("") + , fileType_("") + , cameraType_("") + , fileSizeBytes_(0) + , dateTimeTaken_(0) + , dateTimeUploaded_(0) + , year_(0) + , month_(0) + , day_(0) +{ + Parse(jsonDescription); +} + +PictureDescription::~PictureDescription() +{ +} + +void PictureDescription::Parse(const Aws::Utils::Json::JsonValue& jsonDescription) +{ + sha256_ = jsonDescription.GetString("sha256"); + iv_ = jsonDescription.GetString("iv"); + authTag_ = jsonDescription.GetString("auth_tag"); + fileName_ = jsonDescription.GetString("file_name"); + fileType_ = jsonDescription.GetString("file_type"); + cameraType_ = jsonDescription.GetString("camera_type"); + fileSizeBytes_ = jsonDescription.GetInt64("file_size_bytes"); + dateTimeTaken_ = jsonDescription.GetInt64("datetime_taken"); + dateTimeUploaded_ = jsonDescription.GetInt64("datetime_uploaded"); + year_ = jsonDescription.GetInteger("year"); + month_ = jsonDescription.GetInteger("month"); + day_ = jsonDescription.GetInteger("day"); +} + +std::ostream& operator<<(std::ostream& out, const PictureDescription& desc) +{ + out << "{" << std::endl; + out << " SHA : " << desc.sha256_ << std::endl; + out << " IV : " << desc.iv_ << std::endl; + out << " AUTH: " << desc.authTag_ << std::endl; + out << " FILE_NAME: " << desc.fileName_ << std::endl; + out << " FILE_TYPE: " << desc.fileType_ << std::endl; + out << " CAM_TYPE : " << desc.cameraType_ << std::endl; + out << " FILE_SIZE: " << desc.fileSizeBytes_ << std::endl; + out << " DATE_TIME_TAKEN: " << desc.dateTimeTaken_ << std::endl; + out << " DATE_TIME_UPLD : " << desc.dateTimeUploaded_ << std::endl; + out << " YEAR : " << desc.year_ << std::endl; + out << " MONTH: " << desc.month_ << std::endl; + out << " DAY : " << desc.day_ << std::endl; + out << "}" << std::endl; + + return out; +} diff --git a/pool/shard001/C++/0022605_coreaudio_dispatch_override.cc b/pool/shard001/C++/0022605_coreaudio_dispatch_override.cc new file mode 100644 index 0000000000000000000000000000000000000000..68a9618819c5e6cdc8d1d75bfa65d6f9e57f1b39 --- /dev/null +++ b/pool/shard001/C++/0022605_coreaudio_dispatch_override.cc @@ -0,0 +1,197 @@ +// 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 "media/audio/mac/coreaudio_dispatch_override.h" + +#include +#include +#include + +#include "base/atomicops.h" +#include "base/logging.h" +#include "base/mac/mac_util.h" +#include "base/metrics/histogram_macros.h" + +namespace { +struct dyld_interpose_tuple { + template + dyld_interpose_tuple(T* replacement, T* replacee) + : replacement(reinterpret_cast(replacement)), + replacee(reinterpret_cast(replacee)) {} + const void* replacement; + const void* replacee; +}; + +using DispatchGetGlobalQueueFunc = dispatch_queue_t (*)(long id, + unsigned long flags); +} // namespace + +// This method, and the tuple above, is defined in dyld_priv.h; see: +// https://github.com/opensource-apple/dyld/blob/master/include/mach-o/dyld_priv.h +extern "C" void dyld_dynamic_interpose( + const struct mach_header* mh, + const struct dyld_interpose_tuple array[], + size_t count) __attribute__((weak_import)); + +namespace media { +namespace { +// These values are persisted to logs. Entries should not be renumbered and +// numeric values should never be reused. +enum DispatchOverrideInitResult { + RESULT_NOT_SUPPORTED = 0, + RESULT_INITIALIZED = 1, + RESULT_DYNAMIC_INTERPOSE_NOT_FOUND = 2, + RESULT_COREAUDIO_DLOPEN_FAILED = 3, + RESULT_COREAUDIO_SYMBOL_NOT_FOUND = 4, + RESULT_COREAUDIO_MACH_HEADER_NOT_FOUND = 5, + RESULT_MAX = RESULT_COREAUDIO_MACH_HEADER_NOT_FOUND +}; + +void LogInitResult(DispatchOverrideInitResult result) { + UMA_HISTOGRAM_ENUMERATION("Media.Audio.CoreAudioDispatchOverrideInitResult", + result, RESULT_MAX + 1); +} + +enum CallsiteLookupEvent { + LOOKUP_MISS = 0, + LOOKUP_RESUMEIO_CALLSITE_FOUND = 1, + LOOKUP_PAUSEIO_CALLSITE_FOUND = 2, + LOOKUP_MAX = LOOKUP_PAUSEIO_CALLSITE_FOUND +}; + +void LogCallsiteLookupEvent(CallsiteLookupEvent event) { + UMA_HISTOGRAM_ENUMERATION("Media.Audio.CoreAudioDispatchOverrideLookupEvent", + event, LOOKUP_MAX + 1); +} + +const char kCoreAudioPath[] = + "/System/Library/Frameworks/CoreAudio.framework/Versions/A/CoreAudio"; + +dispatch_queue_t g_pause_resume_queue = nullptr; +bool g_dispatch_override_installed = false; +base::subtle::AtomicWord g_resumeio_callsite = 0; +base::subtle::AtomicWord g_pauseio_callsite = 0; + +bool AddressIsPauseOrResume(intptr_t address) { + if (address == 0) + return false; + + intptr_t resumeio_callsite = + base::subtle::NoBarrier_Load(&g_resumeio_callsite); + + if (address == resumeio_callsite) + return true; + + intptr_t pauseio_callsite = base::subtle::NoBarrier_Load(&g_pauseio_callsite); + if (address == pauseio_callsite) + return true; + + if (resumeio_callsite && pauseio_callsite) + return false; + + // We don't know both callsites yet, so try to look up the caller. + Dl_info info; + if (!dladdr(reinterpret_cast(address), &info)) + return false; + + DCHECK_EQ(strcmp(info.dli_fname, kCoreAudioPath), 0); + + // Before Mac OSX 10.10, this code is not applied because dyld is not + // available. + // From Mac OSX 10.10 to 10.15 (excluded) the target functions that trigger + // the interposition are HALC_IOContext_ResumeIO and HALC_IOContext_PauseIO + // for respectively resume and pause. + // With MacOSX 10.15 the target functions have changed to _XIOContext_ResumeIO + // and _XIOContext_PauseIO for respectively resume and pause. + if (!resumeio_callsite && info.dli_sname && + (strcmp(info.dli_sname, "HALC_IOContext_ResumeIO") == 0 || + strcmp(info.dli_sname, "_XIOContext_ResumeIO") == 0)) { + resumeio_callsite = address; + base::subtle::NoBarrier_CompareAndSwap(&g_resumeio_callsite, 0, + resumeio_callsite); + LogCallsiteLookupEvent(LOOKUP_RESUMEIO_CALLSITE_FOUND); + } else if (!pauseio_callsite && info.dli_sname && + (strcmp(info.dli_sname, "HALC_IOContext_PauseIO") == 0 || + strcmp(info.dli_sname, "_XIOContext_PauseIO") == 0)) { + pauseio_callsite = address; + base::subtle::NoBarrier_CompareAndSwap(&g_pauseio_callsite, 0, + pauseio_callsite); + LogCallsiteLookupEvent(LOOKUP_PAUSEIO_CALLSITE_FOUND); + } else { + LogCallsiteLookupEvent(LOOKUP_MISS); + } + + return address == pauseio_callsite || address == resumeio_callsite; +} + +dispatch_queue_t GetGlobalQueueOverride(long identifier, unsigned long flags) { + // Get the return address. + const intptr_t* rbp = 0; + asm("movq %%rbp, %0;" : "=r"(rbp)); + const intptr_t caller = rbp[1]; + + // Check if it's one we should override. + if (identifier == DISPATCH_QUEUE_PRIORITY_HIGH && + AddressIsPauseOrResume(caller)) { + return g_pause_resume_queue; + } + + return dispatch_get_global_queue(identifier, flags); +} + +} // namespace + +bool InitializeCoreAudioDispatchOverride() { + if (g_dispatch_override_installed) + return true; + + DCHECK_EQ(g_pause_resume_queue, nullptr); + + if (dyld_dynamic_interpose == nullptr) { + LOG(ERROR) << "Unable to resolve dyld_dynamic_interpose()"; + LogInitResult(RESULT_DYNAMIC_INTERPOSE_NOT_FOUND); + return false; + } + // Get CoreAudio handle + void* coreaudio = dlopen(kCoreAudioPath, RTLD_LAZY); + if (!coreaudio) { + LOG(ERROR) << "Could not load CoreAudio while trying to initialize " + "dispatch override"; + LogInitResult(RESULT_COREAUDIO_DLOPEN_FAILED); + return false; + } + // Retrieve the base address (also address of Mach header). For this + // we need any external symbol to look up. + const void* symbol = dlsym(coreaudio, "AudioObjectGetPropertyData"); + if (!symbol) { + LOG(ERROR) << "Unable to resolve AudioObjectGetPropertyData in " + "CoreAudio library"; + LogInitResult(RESULT_COREAUDIO_SYMBOL_NOT_FOUND); + return false; + } + // From the address of that symbol, we can get the address of the library's + // header. + Dl_info info = {}; + if (!dladdr(symbol, &info)) { + LOG(ERROR) << "Unable to find Mach header for CoreAudio library."; + LogInitResult(RESULT_COREAUDIO_MACH_HEADER_NOT_FOUND); + return false; + } + const auto* header = reinterpret_cast(info.dli_fbase); + g_pause_resume_queue = + dispatch_queue_create("org.chromium.CoreAudioPauseResumeQueue", nullptr); + // The reinterpret_cast<> is needed because in the macOS 10.14 SDK, the return + // type of dispatch_get_global_queue changed to return a subtype of + // dispatch_queue_t* instead of dispatch_queue_t* itself, and T(*)(...) isn't + // automatically converted to U(*)(...) even if U is a superclass of T. + dyld_interpose_tuple interposition( + &GetGlobalQueueOverride, + reinterpret_cast(&dispatch_get_global_queue)); + dyld_dynamic_interpose(header, &interposition, 1); + g_dispatch_override_installed = true; + LogInitResult(RESULT_INITIALIZED); + return true; +} + +} // namespace media diff --git a/pool/shard001/C++/0022606_concat_op.cc b/pool/shard001/C++/0022606_concat_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..91e4d9cea7cbf6075e30250587044174c4b8e7f4 --- /dev/null +++ b/pool/shard001/C++/0022606_concat_op.cc @@ -0,0 +1,208 @@ +/* Copyright 2017 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. +==============================================================================*/ + +// XLA-specific Concat Ops. + +#include +#include + +#include "tensorflow/compiler/tf2xla/type_util.h" +#include "tensorflow/compiler/tf2xla/xla_helpers.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "tensorflow/compiler/xla/client/xla_builder.h" +#include "tensorflow/compiler/xla/literal_util.h" +#include "tensorflow/core/framework/bounds_check.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/register_types.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/tensor_types.h" +#include "tensorflow/core/framework/types.h" +#include "tensorflow/core/kernels/concat_lib.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/platform/types.h" + +namespace tensorflow { +namespace { + +// -------------------------------------------------------------------------- +class ConcatBaseOp : public XlaOpKernel { + public: + ConcatBaseOp(OpKernelConstruction* c, int axis_index) + : XlaOpKernel(c), axis_index_(axis_index) {} + + void Compile(XlaOpKernelContext* ctx) override { + const TensorShape concat_dim_tensor_shape = ctx->InputShape(axis_index_); + OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(concat_dim_tensor_shape), + errors::InvalidArgument( + "Concat dim tensor should be a scalar, but got shape ", + concat_dim_tensor_shape.DebugString())); + int64 concat_dim; + OP_REQUIRES_OK(ctx, + ctx->ConstantInputAsIntScalar(axis_index_, &concat_dim)); + + std::vector values; + std::vector shapes; + OP_REQUIRES_OK(ctx, ctx->InputList("values", &values, &shapes)); + const int N = values.size(); + const int input_dims = shapes[0].dims(); + const TensorShape& input_shape = shapes[0]; + + int32 axis = concat_dim < 0 ? concat_dim + input_dims : concat_dim; + OP_REQUIRES(ctx, 0 <= axis && axis < input_dims, + errors::InvalidArgument( + "ConcatOp : Expected concatenating dimensions in the range " + "[", + -input_dims, ", ", input_dims, "), but got ", concat_dim)); + + // Make a vector holding the XlaOp for each of the inputs that has non-zero + // elements. + std::vector input_data; + int output_concat_dim = 0; + for (int i = 0; i < N; ++i) { + xla::XlaOp handle = values[i]; + const TensorShape& in_shape = shapes[i]; + OP_REQUIRES( + ctx, in_shape.dims() == input_dims, + errors::InvalidArgument( + "ConcatOp : Ranks of all input tensors should match: shape[0] = ", + input_shape.DebugString(), " vs. shape[", i, + "] = ", in_shape.DebugString())); + if (in_shape.dims() == 0) { + // Inputs that come in as scalars must be reshaped to 1-vectors. + input_data.push_back(xla::Reshape(handle, {1})); + } else { + input_data.push_back(handle); + } + output_concat_dim += in_shape.dims() > 0 ? in_shape.dim_size(axis) : 1; + } + + VLOG(1) << "Concat dim " << concat_dim << " equivalent to " << axis; + ctx->SetOutput(0, xla::ConcatInDim(ctx->builder(), input_data, axis)); + } + + private: + int axis_index_; +}; + +class ConcatOp : public ConcatBaseOp { + public: + explicit ConcatOp(OpKernelConstruction* c) + : ConcatBaseOp(c, /* axis_index */ 0) {} +}; + +// ConcatV2 operation is the same as Concat except 'concat_dim' +// is the last input instead of the first and renamed to 'axis'. +class ConcatV2Op : public ConcatBaseOp { + public: + explicit ConcatV2Op(OpKernelConstruction* c) + : ConcatBaseOp(c, /* axis_index */ c->num_inputs() - 1) {} +}; + +REGISTER_XLA_OP(Name("Concat").CompileTimeConstantInput("concat_dim"), + ConcatOp); +REGISTER_XLA_OP(Name("ConcatV2") + .TypeConstraint("Tidx", DT_INT32) + .CompileTimeConstantInput("axis"), + ConcatV2Op); + +class ConcatOffsetOp : public XlaOpKernel { + public: + explicit ConcatOffsetOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} + + void Compile(XlaOpKernelContext* ctx) override { + const TensorShape concat_dim_shape = ctx->InputShape(0); + OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(concat_dim_shape), + errors::InvalidArgument( + "Concat dim tensor should be a scalar, but got shape ", + concat_dim_shape.DebugString())); + for (int i = 1; i < ctx->num_inputs(); ++i) { + OP_REQUIRES(ctx, TensorShapeUtils::IsVector(ctx->InputShape(i)), + errors::InvalidArgument("input ", i, + " should be a vector, but got shape ", + ctx->InputShape(i).DebugString())); + } + // Suppose a Concat() op needs to Concatenate N tensors, each of + // which has the same number of dimensions. Their shapes match + // except the concat dimension. + // + // E.g., say, we want to concatenate 3 tensors in the 2nd + // dimension, and their shapes are: + // + // [2, 2, 5, 7] + // [2, 3, 5, 7] + // [2, 4, 5, 7] + // + // Here, N=3, cdim=1, dims=4. The concatenated tensor has shape + // [2,9,5,7]. We will compute the cumulative sum along the 2nd + // dimension to figure out each input's offset in the concatenated + // output: + // [0, 0, 0, 0] + // [0, 2, 0, 0] + // [0, 5, 0, 0] + const int32 N = ctx->num_inputs() - 1; + const TensorShape inp0_shape = ctx->InputShape(1); + std::vector inp0_dims; + OP_REQUIRES_OK(ctx, ctx->ConstantInputAsIntVector(1, &inp0_dims)); + const int64 inp0_rank = inp0_shape.num_elements(); + + int64 cdim; + OP_REQUIRES_OK(ctx, ctx->ConstantInputAsIntScalar(0, &cdim)); + + VLOG(1) << "ConcatOffset " << cdim << "," << inp0_rank; + int32 axis = cdim < 0 ? cdim + inp0_rank : cdim; + OP_REQUIRES(ctx, FastBoundsCheck(axis, inp0_rank), + errors::InvalidArgument("Concat dim is out of range: ", axis, + " vs. ", inp0_rank)); + int32 offset = 0; + for (int i = 0; i < N; ++i) { + const TensorShape inp_shape = ctx->InputShape(1 + i); + OP_REQUIRES(ctx, inp0_rank == inp_shape.num_elements(), + errors::InvalidArgument("input ", i, " should contain ", + inp0_rank, " elements, but got ", + inp_shape.num_elements())); + std::vector inp_dims; + OP_REQUIRES_OK(ctx, ctx->ConstantInputAsIntVector(1 + i, &inp_dims)); + + Tensor out_constant(DT_INT32, TensorShape({inp0_rank})); + auto out_vec = out_constant.vec(); + for (int64 j = 0; j < inp0_rank; ++j) { + if (j == axis) { + out_vec(j) = offset; + offset += inp_dims[j]; + } else { + const int32 inp0_element = inp0_dims[j]; + const int32 inp_element = inp_dims[j]; + OP_REQUIRES(ctx, inp0_element == inp_element, + errors::InvalidArgument("input[", i, ",", j, + "] mismatch: ", inp0_element, + " vs. ", inp_element)); + out_vec(j) = 0; + } + } + + ctx->SetConstantOutput(i, out_constant); + } + } +}; + +REGISTER_XLA_OP(Name("ConcatOffset") + .CompileTimeConstantInput("concat_dim") + .CompileTimeConstantInput("shape"), + ConcatOffsetOp); + +} // namespace +} // namespace tensorflow diff --git a/pool/shard001/C++/0022607_ChunkServer.cc b/pool/shard001/C++/0022607_ChunkServer.cc new file mode 100644 index 0000000000000000000000000000000000000000..28849cf49c2909002c36c41d4a253822513b8106 --- /dev/null +++ b/pool/shard001/C++/0022607_ChunkServer.cc @@ -0,0 +1,213 @@ +//---------------------------------------------------------- -*- Mode: C++ -*- +// $Id: ChunkServer.cc 155 2008-09-18 04:47:20Z sriramsrao $ +// +// Created 2006/03/23 +// Author: Sriram Rao +// +// Copyright 2008 Quantcast Corp. +// Copyright 2006-2008 Kosmix Corp. +// +// This file is part of Kosmos File System (KFS). +// +// 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. +// +// +//---------------------------------------------------------------------------- + +// order of #includes here is critical. don't change it +#include "libkfsIO/Counter.h" +#include "libkfsIO/Globals.h" + +#include "ChunkServer.h" +#include "Utils.h" + +#include +#include + +using std::list; + +using namespace KFS; +using namespace KFS::libkfsio; + +// single network thread that manages connections and net I/O +/// 管理网络和网络读写的线程 +static MetaThread netProcessor; + +/// 本地全局chunkServer +ChunkServer KFS::gChunkServer; + +/// 启动网络监听,监听所有的socket读写操作 +static void * netWorker(void *dummy) +{ + globals().netManager.MainLoop(); + return NULL; +} + +/// 使用netProcessor启动一个线程,对网络进行管理 +static void StartNetProcessor() +{ + // 调用start建立一个线程 + netProcessor.start(netWorker, NULL); +} + +void ChunkServer::Init() +{ + // 建立一系列的命令和函数指针的对应关系 + InitParseHandlers(); + // Register the counters + // 建立命令和Counter的对应关系并且注册到全局变量的counterManager中 + RegisterCounters(); +} + +/// 常驻函数,具体操作列表如下: +/* + * 1. 获取本地host IP和接收客户请求的端口 + * 2. 启动监听socket + * 3. 启动日志系统:Logger + * 4. 启动chunkManager + * 5. 启动管理MetaServer请求和相应的管理器 + * 6. 使用netProcessor启动一个线程,对网络进行管理 + * 7. 暂停当前线程,等待其他线程运行 + */ +void ChunkServer::MainLoop(int clientAcceptPort) +{ +#if !defined (__sun__) + static const int MAXHOSTNAMELEN = 256; +#endif + char hostname[MAXHOSTNAMELEN]; + + // 指定接收用户socket连接的端口号 + mClientAcceptPort = clientAcceptPort; + + // 把自己的主机名导入到hostname中,hostname最大长度为MAXHOSTNAMELEN, + // 若超出长度,则进行截尾操作 + if (gethostname(hostname, MAXHOSTNAMELEN)) + { + perror("gethostname: "); + exit(-1); + } + + // convert to IP address + // 将hostname转换成hostent类,主要目的是提取其IP地址 + struct hostent *hent = gethostbyname(hostname); + in_addr ipaddr; + + // 提取出IP地址到ipaddr中 + memcpy(&ipaddr, hent->h_addr, hent->h_length); + + mLocation.Reset(inet_ntoa(ipaddr), clientAcceptPort); + + // 1. 启动socket,监听网络上的连接请求 + gClientManager.StartAcceptor(clientAcceptPort); + // 2. 启动日志记录器 + gLogger.Start(); + // 3. 启动chunkManager,即向全局变量的netManager中注册定时处理程序(含Loop) + gChunkManager.Start(); + // gMetaServerSM.SendHello(clientAcceptPort); + // 4. 启动管理MetaServer请求和相应的管理器(含Loop,常驻) + gMetaServerSM.Init(clientAcceptPort); + + // 5. 使用netProcessor启动一个线程,对网络进行管理(含Loop,单独线程) + StartNetProcessor(); + + /* + * pthread_join()的调用者将挂起并等待th线程终止,retval是pthread_exit()调用者 + * 线程(线程ID为th)的返回值,如果thread_return不为NULL,则 + * *thread_return=retval。需要注意的是一个线程仅允许唯一的一个线程使用 + * pthread_join()等待它的终止,并且被等待的线程应该处于可join状态,即非DETACHED状态。 + */ + // 6. 暂停当前线程,等待指定线程(netProcessor)运行 + netProcessor.join(); +} + +/// 比较两个RemoteSyncSM是否相同:RemoteSyncSM通过mLocation唯一标识 +class RemoteSyncSMMatcher +{ + ServerLocation myLoc; +public: + RemoteSyncSMMatcher(const ServerLocation &loc) : + myLoc(loc) + { + } + bool operator()(RemoteSyncSMPtr other) + { + return other->GetLocation() == myLoc; + } +}; + +/// 在mRemoteSyncers中查找对应于location的RemoteSyncSM +/// 如果找到了,就直接返回;如果没有找到,并且connect为真,则创建一个location相关的 +/// RemoteSyncSM +RemoteSyncSMPtr ChunkServer::FindServer(const ServerLocation &location, + bool connect) +{ + list::iterator i; + RemoteSyncSMPtr peer; + + // 查找location对应的RemoteSyncSM + i = find_if(mRemoteSyncers.begin(), mRemoteSyncers.end(), + RemoteSyncSMMatcher(location)); + // 如果在mRemoteSyncers中找到了指定的RemoteSyncSM,则直接返回其指针即可 + if (i != mRemoteSyncers.end()) + { + peer = *i; + return peer; + } + + // 如果没有找到对应的RemoteSyncSM,并且不需要进行连接,则直接返回找空指针即可 + if (!connect) + return peer; + + // 建立location相关的RemoteSyncSM + peer.reset(new RemoteSyncSM(location)); + // 对远端服务器进行连接 + if (peer->Connect()) + { + mRemoteSyncers.push_back(peer); + } + else + { + // we couldn't connect...so, force destruction + peer.reset(); + } + return peer; +} + +/// 从mRemoteSyncers中删除指定的RemoteSyncSM +void ChunkServer::RemoveServer(RemoteSyncSM *target) +{ + list::iterator i; + + i = find_if(mRemoteSyncers.begin(), mRemoteSyncers.end(), + RemoteSyncSMMatcher(target->GetLocation())); + if (i != mRemoteSyncers.end()) + { + mRemoteSyncers.erase(i); + } +} + +/// 验证当前线程是否属于netProcessor +void KFS::verifyExecutingOnNetProcessor() +{ + assert(netProcessor.isEqual(pthread_self())); + if (!netProcessor.isEqual(pthread_self())) + { + die("FATAL: Not executing on net processor"); + } +} + +/// 退出NetProcessor线程 +void KFS::StopNetProcessor(int status) +{ + netProcessor.exit(status); +} diff --git a/pool/shard001/C++/0022608_AMDGPUELFObjectWriter.cpp b/pool/shard001/C++/0022608_AMDGPUELFObjectWriter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5fb94d5914d43157527ece2b65ddd5b4999f4821 --- /dev/null +++ b/pool/shard001/C++/0022608_AMDGPUELFObjectWriter.cpp @@ -0,0 +1,39 @@ +//===-- AMDGPUELFObjectWriter.cpp - AMDGPU ELF Writer ----------------------==// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +/// \file +//===----------------------------------------------------------------------===// + +#include "AMDGPUMCTargetDesc.h" +#include "llvm/MC/MCELFObjectWriter.h" +#include "llvm/MC/MCFixup.h" + +using namespace llvm; + +namespace { + +class AMDGPUELFObjectWriter : public MCELFObjectTargetWriter { +public: + AMDGPUELFObjectWriter(); +protected: + unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup, + bool IsPCRel) const override { + return Fixup.getKind(); + } + +}; + + +} // End anonymous namespace + +AMDGPUELFObjectWriter::AMDGPUELFObjectWriter() + : MCELFObjectTargetWriter(false, 0, 0, false) { } + +MCObjectWriter *llvm::createAMDGPUELFObjectWriter(raw_ostream &OS) { + MCELFObjectTargetWriter *MOTW = new AMDGPUELFObjectWriter(); + return createELFObjectWriter(MOTW, OS, true); +} diff --git a/pool/shard001/C++/0022610_gpgconfcheck.cpp b/pool/shard001/C++/0022610_gpgconfcheck.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2cea8b13dcf2a5482f5921d401a3a760c081e702 --- /dev/null +++ b/pool/shard001/C++/0022610_gpgconfcheck.cpp @@ -0,0 +1,154 @@ +/* -*- mode: c++; c-basic-offset:4 -*- + selftest/gpgconfcheck.cpp + + This file is part of Kleopatra, the KDE keymanager + Copyright (c) 2008 Klarälvdalens Datakonsult AB + + Kleopatra 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. + + Kleopatra 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 the code of this program with any edition of + the Qt library by Trolltech AS, Norway (or with modified versions + of Qt that use the same license as Qt), and distribute linked + combinations including the two. You must obey the GNU General + Public License in all respects for all of the code used other than + Qt. If you modify this file, you may extend this exception to + your version of the file, but you are not obligated to do so. If + you do not wish to do so, delete this exception statement from + your version. +*/ + +#include + +#include "gpgconfcheck.h" + +#include "implementation_p.h" + +#include +#include + +#include +#include + +#include +#include + +#include + +#include + +using namespace Kleo; +using namespace Kleo::_detail; +using namespace boost; + +namespace { + + class GpgConfCheck : public SelfTestImplementation { + QString m_component; + public: + explicit GpgConfCheck( const char * component ) + : SelfTestImplementation( i18nc("@title", "%1 Configuration Check", component && *component ? QLatin1String(component) : QLatin1String("gpgconf") ) ), + m_component( QLatin1String(component) ) + { + runTest(); + } + + QStringList arguments() const { + if ( m_component.isEmpty() ) + return QStringList() << QLatin1String("--check-config"); + else + return QStringList() << QLatin1String("--check-options") << m_component ; + } + + bool canRun() { + if ( !ensureEngineVersion( GpgME::GpgConfEngine, 2, 0, 10 ) ) + return false; + + if ( !m_component.isEmpty() ) + return true; + + QProcess gpgconf; + gpgconf.setReadChannel( QProcess::StandardOutput ); + gpgconf.start( gpgConfPath(), QStringList() << QLatin1String("--list-dirs"), QIODevice::ReadOnly ); + gpgconf.waitForFinished(); + if ( gpgconf.exitStatus() != QProcess::NormalExit || gpgconf.exitCode() != 0 ) { + kDebug() << "GpgConfCheck: \"gpgconf --list-dirs\" gives error, disabling"; + return false; + } + const QList lines = gpgconf.readAll().split( '\n' ); + Q_FOREACH( const QByteArray & line, lines ) + if ( line.startsWith( "sysconfdir:" ) ) //krazy:exclude=strings + try { + return QDir( QFile::decodeName( hexdecode( line.mid( strlen( "sysconfdir:" ) ) ) ) ).exists( QLatin1String("gpgconf.conf") ); + } catch ( ... ) { return false; } + kDebug() << "GpgConfCheck: \"gpgconf --list-dirs\" has no sysconfdir entry"; + return false; + } + + void runTest() { + + if ( !canRun() ) { + if ( !m_skipped ) + m_passed = true; + return; + } + + QProcess process; + process.setProcessChannelMode( QProcess::MergedChannels ); + + process.start( gpgConfPath(), arguments(), QIODevice::ReadOnly ); + + process.waitForFinished(); + + const QString output = QString::fromUtf8( process.readAll() ); + const QString message = process.exitStatus() == QProcess::CrashExit ? i18n( "The process terminated prematurely" ) : process.errorString() ; + + if ( process.exitStatus() != QProcess::NormalExit || + process.error() != QProcess::UnknownError ) { + m_passed = false; + m_error = i18nc("self-test did not pass", "Failed"); + m_explaination = + i18n( "There was an error executing the GnuPG configuration self-check for %2:\n" + " %1\n" + "You might want to execute \"gpgconf %3\" on the command line.\n", + message, m_component.isEmpty() ? QLatin1String("GnuPG") : m_component, arguments().join(QLatin1String(" ") ) ); + if ( !output.trimmed().isEmpty() ) + m_explaination += QLatin1Char('\n') + i18n("Diagnostics:") + QLatin1Char('\n') + output ; + + m_proposedFix.clear(); + } else if ( process.exitCode() ) { + m_passed = false; + m_error = i18nc("self-check did not pass", "Failed"); + m_explaination = !output.trimmed().isEmpty() + ? i18nc("Self-test did not pass", + "The GnuPG configuration self-check failed.\n" + "\n" + "Error code: %1\n" + "Diagnostics:", process.exitCode() ) + QLatin1Char('\n') + output + : i18nc("self-check did not pass", + "The GnuPG configuration self-check failed with error code %1.\n" + "No output was received.", process.exitCode() ); + m_proposedFix.clear(); + } else { + m_passed = true; + } + } + + }; +} + +shared_ptr Kleo::makeGpgConfCheckConfigurationSelfTest( const char * component ) { + return shared_ptr( new GpgConfCheck( component ) ); +} diff --git a/pool/shard001/C++/0022612_ListJournalKinesisStreamsForLedgerResult.cpp b/pool/shard001/C++/0022612_ListJournalKinesisStreamsForLedgerResult.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2eb0ce98ba08985d6d4e7979b106501939340414 --- /dev/null +++ b/pool/shard001/C++/0022612_ListJournalKinesisStreamsForLedgerResult.cpp @@ -0,0 +1,49 @@ +/** + * 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::QLDB::Model; +using namespace Aws::Utils::Json; +using namespace Aws::Utils; +using namespace Aws; + +ListJournalKinesisStreamsForLedgerResult::ListJournalKinesisStreamsForLedgerResult() +{ +} + +ListJournalKinesisStreamsForLedgerResult::ListJournalKinesisStreamsForLedgerResult(const Aws::AmazonWebServiceResult& result) +{ + *this = result; +} + +ListJournalKinesisStreamsForLedgerResult& ListJournalKinesisStreamsForLedgerResult::operator =(const Aws::AmazonWebServiceResult& result) +{ + JsonView jsonValue = result.GetPayload().View(); + if(jsonValue.ValueExists("Streams")) + { + Array streamsJsonList = jsonValue.GetArray("Streams"); + for(unsigned streamsIndex = 0; streamsIndex < streamsJsonList.GetLength(); ++streamsIndex) + { + m_streams.push_back(streamsJsonList[streamsIndex].AsObject()); + } + } + + if(jsonValue.ValueExists("NextToken")) + { + m_nextToken = jsonValue.GetString("NextToken"); + + } + + + + return *this; +} diff --git a/pool/shard001/C++/0022614_clock.cc b/pool/shard001/C++/0022614_clock.cc new file mode 100644 index 0000000000000000000000000000000000000000..7c17be36758a7ad06178311ebed5a025f88cbae6 --- /dev/null +++ b/pool/shard001/C++/0022614_clock.cc @@ -0,0 +1,64 @@ +#include "clock.h" + +#include + +#ifdef __MACH__ + +#include + +#endif + +namespace RPiClock { + + int32_t setDelayNs(const int32_t durationNs) { + const int32_t startNs = getNowNs(); + + if (startNs == -1) { + return -1; + } + + while (1) { + int32_t stopNs = getNowNs(); + + if (stopNs == -1) { + return -1; + } + + if (getDurationNs(startNs, stopNs) >= durationNs) { + break; + } + } + + return 0; + } + + int32_t getDurationNs(const int32_t startNs, const int32_t stopNs) { + int32_t durationNs = stopNs - startNs; + + if (durationNs < 0) { + durationNs += 1000000000; + } + + return durationNs; + } + + int32_t getNowNs() { + #ifndef __MACH__ + + struct timespec now; + + if (clock_gettime(CLOCK_REALTIME, &now) == -1) { + return -1; + } + + return now.tv_nsec; + + #else + + errno = EPERM; + + return -1; + + #endif + } +} diff --git a/pool/shard001/C++/0022623_GUISound.cpp b/pool/shard001/C++/0022623_GUISound.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7e954bf94c25052d5c99bf5ce2beb2348324aac3 --- /dev/null +++ b/pool/shard001/C++/0022623_GUISound.cpp @@ -0,0 +1,280 @@ +/* + * 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 "system.h" +#include "GUISound.h" +#include "AudioContext.h" +#include "settings/Settings.h" +#include "filesystem/File.h" +#include "utils/log.h" +#ifdef HAS_SDL_AUDIO +#include +#endif +#include "filesystem/SpecialProtocol.h" +#ifndef HAS_SDL_AUDIO + +typedef struct +{ + char chunk_id[4]; + long chunksize; +} WAVE_CHUNK; + +typedef struct +{ + char riff[4]; + long filesize; + char rifftype[4]; +} WAVE_RIFFHEADER; +#else +#define GUI_SOUND_CHANNEL 0 +#endif + +CGUISound::CGUISound() +{ + m_soundBuffer=NULL; +} + +CGUISound::~CGUISound() +{ +#ifdef _WIN32 + FreeBuffer(); +#elif defined(HAS_SDL_AUDIO) + Mix_FreeChunk(m_soundBuffer); +#endif +} + +// \brief Loads a wav file by filename +bool CGUISound::Load(const CStdString& strFile) +{ +#ifdef _WIN32 + LPBYTE pbData=NULL; + WAVEFORMATEX wfx; + int size=0; + if (!LoadWav(strFile, &wfx, &pbData, &size)) + return false; + + bool bReady=(CreateBuffer(&wfx, size) && FillBuffer(pbData, size)); + + if (!bReady) + FreeBuffer(); + + delete[] pbData; + + return bReady; +#elif defined(HAS_SDL_AUDIO) + m_soundBuffer = Mix_LoadWAV(_P(strFile)); + if (!m_soundBuffer) + return false; + + return true; +#else + return false; +#endif +} + +// \brief Starts playback of the sound +void CGUISound::Play() +{ + if (m_soundBuffer) + { +#ifdef _WIN32 + m_soundBuffer->Play(0, 0, 0); +#elif defined(HAS_SDL_AUDIO) + Mix_PlayChannel(GUI_SOUND_CHANNEL, m_soundBuffer, 0); +#endif + } +} + +// \brief returns true if the sound is playing +bool CGUISound::IsPlaying() +{ +#ifdef _WIN32 + if (m_soundBuffer) + { + DWORD dwStatus; + m_soundBuffer->GetStatus(&dwStatus); + return (dwStatus & DSBSTATUS_PLAYING); + } + + return false; +#elif defined(HAS_SDL_AUDIO) + return Mix_Playing(GUI_SOUND_CHANNEL) != 0; +#else + return false; +#endif +} + +// \brief Stops playback if the sound +void CGUISound::Stop() +{ + if (m_soundBuffer) + { +#ifdef _WIN32 + m_soundBuffer->Stop(); +#elif defined(HAS_SDL_AUDIO) + Mix_HaltChannel(GUI_SOUND_CHANNEL); +#endif + Wait(); + } +} + +// \brief Sets the volume of the sound +void CGUISound::SetVolume(int level) +{ + if (m_soundBuffer) + { +#ifdef _WIN32 + m_soundBuffer->SetVolume(level); +#elif defined(HAS_SDL_AUDIO) + Mix_Volume(GUI_SOUND_CHANNEL, level); +#endif + } +} + +void CGUISound::Wait(uint32_t millis/*=500*/) +{ + millis /= 10; + while (IsPlaying() && millis--) + Sleep(10); +} + +#ifdef _WIN32 +bool CGUISound::CreateBuffer(LPWAVEFORMATEX wfx, int iLength) +{ + // Set up DSBUFFERDESC structure + DSBUFFERDESC dsbdesc; + memset(&dsbdesc, 0, sizeof(DSBUFFERDESC)); + dsbdesc.dwSize=sizeof(DSBUFFERDESC); + // directsound requires ctrlvolume to be set + dsbdesc.dwFlags = DSBCAPS_CTRLVOLUME; + dsbdesc.dwBufferBytes=iLength; + dsbdesc.lpwfxFormat=wfx; + + LPDIRECTSOUND directSound=g_audioContext.GetDirectSoundDevice(); + if (!directSound) + return false; + + // Create buffer + if (FAILED(directSound->CreateSoundBuffer(&dsbdesc, &m_soundBuffer, NULL))) + { + m_soundBuffer = NULL; + CLog::Log(LOGERROR, __FUNCTION__" Creating sound buffer failed!"); + return false; + } + + // Make effects as loud as possible + m_soundBuffer->SetVolume(g_settings.m_nVolumeLevel); + + return true; +} + +bool CGUISound::FillBuffer(LPBYTE pbData, int iLength) +{ + if (!m_soundBuffer) + return false; + + LPVOID lpvWrite; + DWORD dwLength; + + if (SUCCEEDED(m_soundBuffer->Lock(0, 0, &lpvWrite, &dwLength, NULL, NULL, DSBLOCK_ENTIREBUFFER))) + { + memcpy(lpvWrite, pbData, iLength); + m_soundBuffer->Unlock(lpvWrite, dwLength, NULL, 0); + return true; + } + + CLog::Log(LOGERROR, __FUNCTION__" Filling sound buffer failed!"); + + return false; +} + +void CGUISound::FreeBuffer() +{ + if (IsPlaying()) + Stop(); + + SAFE_RELEASE(m_soundBuffer); +} + +bool CGUISound::LoadWav(const CStdString& strFile, WAVEFORMATEX* wfx, LPBYTE* ppWavData, int* pDataSize) +{ + XFILE::CFile file; + if (!file.Open(strFile)) + return false; + + // read header + WAVE_RIFFHEADER riffh; + file.Read(&riffh, sizeof(WAVE_RIFFHEADER)); + + // file valid? + if (strncmp(riffh.riff, "RIFF", 4)!=0 && strncmp(riffh.rifftype, "WAVE", 4)!=0) + { + file.Close(); + return false; + } + + long offset=0; + offset += sizeof(WAVE_RIFFHEADER); + offset -= sizeof(WAVE_CHUNK); + + // parse chunks + do + { + WAVE_CHUNK chunk; + + // always seeking to the start of a chunk + file.Seek(offset + sizeof(WAVE_CHUNK), SEEK_SET); + file.Read(&chunk, sizeof(WAVE_CHUNK)); + + if (!strncmp(chunk.chunk_id, "fmt ", 4)) + { // format chunk + memset(wfx, 0, sizeof(WAVEFORMATEX)); + file.Read(wfx, 16); + // we only need 16 bytes of the fmt chunk + if (chunk.chunksize-16>0) + file.Seek(chunk.chunksize-16, SEEK_CUR); + } + else if (!strncmp(chunk.chunk_id, "data", 4)) + { // data chunk + *ppWavData=new BYTE[chunk.chunksize+1]; + file.Read(*ppWavData, chunk.chunksize); + *pDataSize=chunk.chunksize; + + if (chunk.chunksize & 1) + offset++; + } + else + { // other chunk - unused, just skip + file.Seek(chunk.chunksize, SEEK_CUR); + } + + offset+=(chunk.chunksize+sizeof(WAVE_CHUNK)); + + if (offset & 1) + offset++; + + } while (offset+(int)sizeof(WAVE_CHUNK) < riffh.filesize); + + file.Close(); + return (*ppWavData!=NULL); +} + +#endif diff --git a/pool/shard001/C++/0022624_2.cc b/pool/shard001/C++/0022624_2.cc new file mode 100644 index 0000000000000000000000000000000000000000..3fea6be857ab6002823c8f1accec03fba492e461 --- /dev/null +++ b/pool/shard001/C++/0022624_2.cc @@ -0,0 +1,63 @@ +// 2002-05-24 bkoz + +// 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 +// . + + +// 22.2.1.3.2 ctype members + +#include +#include +#include + +void test02() +{ + using namespace std; + typedef char wide_type; + + const char dfault = '?'; + const locale loc_c = locale::classic(); + const ctype& ctype_c = use_facet >(loc_c); + + // Construct non-asci string. + basic_string wide("wibble"); + wide += wide_type(1240); + wide += "kibble"; + basic_string narrow("wibble"); + narrow += char(1240); + narrow += "kibble"; + vector narrow_chars(wide.length() + 1); + + // narrow(charT c, char dfault) const + for (size_t i = 0; i < wide.length(); ++i) + { + char c = ctype_c.narrow(wide[i], dfault); + VERIFY( c == narrow[i] ); + } + + // narrow(const charT* low, const charT* high, char dfault, char* dest) const + ctype_c.narrow(&wide[0], &wide[0] + wide.length(), dfault, &narrow_chars[0]); + VERIFY( narrow_chars[0] != dfault ); + for (size_t i = 0; i < wide.length(); ++i) + VERIFY( narrow_chars[i] == narrow[i] ); +} + +int main() +{ + test02(); + return 0; +} diff --git a/pool/shard001/C++/0022627_overviewpage.cpp b/pool/shard001/C++/0022627_overviewpage.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c8981e35c9e68d50023d2faec03934f0f24231ab --- /dev/null +++ b/pool/shard001/C++/0022627_overviewpage.cpp @@ -0,0 +1,213 @@ +#include "overviewpage.h" +#include "ui_overviewpage.h" + +#include "clientmodel.h" +#include "walletmodel.h" +#include "bitcoinunits.h" +#include "optionsmodel.h" +#include "transactiontablemodel.h" +#include "transactionfilterproxy.h" +#include "guiutil.h" +#include "guiconstants.h" + +#include +#include + +#define DECORATION_SIZE 64 +#define NUM_ITEMS 3 + +class TxViewDelegate : public QAbstractItemDelegate +{ + Q_OBJECT +public: + TxViewDelegate(): QAbstractItemDelegate(), unit(BitcoinUnits::CC) + { + + } + + inline void paint(QPainter *painter, const QStyleOptionViewItem &option, + const QModelIndex &index ) const + { + painter->save(); + + QIcon icon = qvariant_cast(index.data(Qt::DecorationRole)); + QRect mainRect = option.rect; + QRect decorationRect(mainRect.topLeft(), QSize(DECORATION_SIZE, DECORATION_SIZE)); + int xspace = DECORATION_SIZE + 8; + int ypad = 6; + int halfheight = (mainRect.height() - 2*ypad)/2; + QRect amountRect(mainRect.left() + xspace, mainRect.top()+ypad, mainRect.width() - xspace, halfheight); + QRect addressRect(mainRect.left() + xspace, mainRect.top()+ypad+halfheight, mainRect.width() - xspace, halfheight); + icon.paint(painter, decorationRect); + + QDateTime date = index.data(TransactionTableModel::DateRole).toDateTime(); + QString address = index.data(Qt::DisplayRole).toString(); + qint64 amount = index.data(TransactionTableModel::AmountRole).toLongLong(); + bool confirmed = index.data(TransactionTableModel::ConfirmedRole).toBool(); + QVariant value = index.data(Qt::ForegroundRole); + QColor foreground = option.palette.color(QPalette::Text); + if(value.canConvert()) + { + QBrush brush = qvariant_cast(value); + foreground = brush.color(); + } + + painter->setPen(foreground); + painter->drawText(addressRect, Qt::AlignLeft|Qt::AlignVCenter, address); + + if(amount < 0) + { + foreground = COLOR_NEGATIVE; + } + else if(!confirmed) + { + foreground = COLOR_UNCONFIRMED; + } + else + { + foreground = option.palette.color(QPalette::Text); + } + painter->setPen(foreground); + QString amountText = BitcoinUnits::formatWithUnit(unit, amount, true); + if(!confirmed) + { + amountText = QString("[") + amountText + QString("]"); + } + painter->drawText(amountRect, Qt::AlignRight|Qt::AlignVCenter, amountText); + + painter->setPen(option.palette.color(QPalette::Text)); + painter->drawText(amountRect, Qt::AlignLeft|Qt::AlignVCenter, GUIUtil::dateTimeStr(date)); + + painter->restore(); + } + + inline QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const + { + return QSize(DECORATION_SIZE, DECORATION_SIZE); + } + + int unit; + +}; +#include "overviewpage.moc" + +OverviewPage::OverviewPage(QWidget *parent) : + QWidget(parent), + ui(new Ui::OverviewPage), + clientModel(0), + walletModel(0), + currentBalance(-1), + currentUnconfirmedBalance(-1), + currentImmatureBalance(-1), + txdelegate(new TxViewDelegate()), + filter(0) +{ + ui->setupUi(this); + + // Recent transactions + ui->listTransactions->setItemDelegate(txdelegate); + ui->listTransactions->setIconSize(QSize(DECORATION_SIZE, DECORATION_SIZE)); + ui->listTransactions->setMinimumHeight(NUM_ITEMS * (DECORATION_SIZE + 2)); + ui->listTransactions->setAttribute(Qt::WA_MacShowFocusRect, false); + + connect(ui->listTransactions, SIGNAL(clicked(QModelIndex)), this, SLOT(handleTransactionClicked(QModelIndex))); + + // init "out of sync" warning labels + ui->labelWalletStatus->setText("(" + tr("out of sync") + ")"); + ui->labelTransactionsStatus->setText("(" + tr("out of sync") + ")"); + + // start with displaying the "out of sync" warnings + showOutOfSyncWarning(true); +} + +void OverviewPage::handleTransactionClicked(const QModelIndex &index) +{ + if(filter) + emit transactionClicked(filter->mapToSource(index)); +} + +OverviewPage::~OverviewPage() +{ + delete ui; +} + +void OverviewPage::setBalance(qint64 balance, qint64 unconfirmedBalance, qint64 immatureBalance) +{ + int unit = walletModel->getOptionsModel()->getDisplayUnit(); + currentBalance = balance; + currentUnconfirmedBalance = unconfirmedBalance; + currentImmatureBalance = immatureBalance; + ui->labelBalance->setText(BitcoinUnits::formatWithUnit(unit, balance)); + ui->labelUnconfirmed->setText(BitcoinUnits::formatWithUnit(unit, unconfirmedBalance)); + ui->labelImmature->setText(BitcoinUnits::formatWithUnit(unit, immatureBalance)); + + // only show immature (newly mined) balance if it's non-zero, so as not to complicate things + // for the non-mining users + bool showImmature = immatureBalance != 0; + ui->labelImmature->setVisible(showImmature); + ui->labelImmatureText->setVisible(showImmature); +} + +void OverviewPage::setClientModel(ClientModel *model) +{ + this->clientModel = model; + if(model) + { + // Show warning if this is a prerelease version + connect(model, SIGNAL(alertsChanged(QString)), this, SLOT(updateAlerts(QString))); + updateAlerts(model->getStatusBarWarnings()); + } +} + +void OverviewPage::setWalletModel(WalletModel *model) +{ + this->walletModel = model; + if(model && model->getOptionsModel()) + { + // Set up transaction list + filter = new TransactionFilterProxy(); + filter->setSourceModel(model->getTransactionTableModel()); + filter->setLimit(NUM_ITEMS); + filter->setDynamicSortFilter(true); + filter->setSortRole(Qt::EditRole); + filter->sort(TransactionTableModel::Status, Qt::DescendingOrder); + + ui->listTransactions->setModel(filter); + ui->listTransactions->setModelColumn(TransactionTableModel::ToAddress); + + // Keep up to date with wallet + setBalance(model->getBalance(), model->getUnconfirmedBalance(), model->getImmatureBalance()); + connect(model, SIGNAL(balanceChanged(qint64, qint64, qint64)), this, SLOT(setBalance(qint64, qint64, qint64))); + + connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); + } + + // update the display unit, to not use the default ("CC") + updateDisplayUnit(); +} + +void OverviewPage::updateDisplayUnit() +{ + if(walletModel && walletModel->getOptionsModel()) + { + if(currentBalance != -1) + setBalance(currentBalance, currentUnconfirmedBalance, currentImmatureBalance); + + // Update txdelegate->unit with the current unit + txdelegate->unit = walletModel->getOptionsModel()->getDisplayUnit(); + + ui->listTransactions->update(); + } +} + +void OverviewPage::updateAlerts(const QString &warnings) +{ + this->ui->labelAlerts->setVisible(!warnings.isEmpty()); + this->ui->labelAlerts->setText(warnings); +} + +void OverviewPage::showOutOfSyncWarning(bool fShow) +{ + ui->labelWalletStatus->setVisible(fShow); + ui->labelTransactionsStatus->setVisible(fShow); +} diff --git a/pool/shard001/C++/0022630_main.cpp b/pool/shard001/C++/0022630_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..51c6414f512d11930853f28e5570e7e3c7ab14c2 --- /dev/null +++ b/pool/shard001/C++/0022630_main.cpp @@ -0,0 +1,68 @@ +#include +#include +#include + +using namespace std; +const int oo = 0x3f3f3f3f; + +int N; +int cache[10001][10]; +int choices[10001][10]; +int values[10001][10]; +int S[10001], O[10001]; + +int solve(int n, int k); +void trace(int n, int k); +int main() +{ + memset(cache, -1, sizeof(cache)); + scanf("%d", &N); + string s,o; + cin >> s >> o; + for(int i=0; i(stats.replicationThrottleWriteQueueCap); +} + +bool ReplicationThrottleEP::hasSomeMemory() const { + auto memoryUsed = + static_cast(stats.getEstimatedTotalMemoryUsed()); + auto maxSize = static_cast(stats.getMaxDataSize()); + + return memoryUsed <= (maxSize * stats.replicationThrottleThreshold); +} + +ReplicationThrottleEP::Status ReplicationThrottleEP::getStatus() const { + return (persistenceQueueSmallEnough() && hasSomeMemory()) ? Status::Process + : Status::Pause; +} + +void ReplicationThrottleEP::adjustWriteQueueCap(size_t totalItems) { + if (queueCap == -1) { + stats.replicationThrottleWriteQueueCap.store(-1); + return; + } + auto qcap = static_cast(queueCap); + size_t throttleCap = 0; + if (capPercent > 0) { + throttleCap = (static_cast(capPercent) / 100.0) * totalItems; + } + stats.replicationThrottleWriteQueueCap.store(throttleCap > qcap ? throttleCap : + qcap); +} + +ReplicationThrottleEphe::ReplicationThrottleEphe(const Configuration& config, + EPStats& s) + : ReplicationThrottleEP(config, s), config(config) { +} + +ReplicationThrottleEP::Status ReplicationThrottleEphe::getStatus() const { + auto status = ReplicationThrottleEP::getStatus(); + if (status == Status::Pause) { + if (config.getEphemeralFullPolicy() == "fail_new_data") { + return Status::Disconnect; + } + } + return status; +} + +bool ReplicationThrottleEphe::doDisconnectOnNoMem() const { + if (config.getEphemeralFullPolicy() == "fail_new_data") { + return true; + } + return false; +} diff --git a/pool/shard001/C++/0022637_SumandColor.cpp b/pool/shard001/C++/0022637_SumandColor.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d8a2ff2cb7af62ee66e3082e76057adb6af3961a --- /dev/null +++ b/pool/shard001/C++/0022637_SumandColor.cpp @@ -0,0 +1,47 @@ +#include +#include + +int getDigitAddition(int number) { + if (number <= 9) return number; + int addition = getDigitAddition(number % 10 + getDigitAddition(number / 10)); + return addition; +} + +int main() +{ + int tests = 0; + scanf("%d", &tests); + char* colors[] = { + "red", + "blue", + "pink", + "white", + "black", + "violet", + "cyan", + "yellow", + "green", + "brown" + }; + + + for (int test = 0; test < tests; test++) + { + int N = 0; scanf("%d", &N); + int max = 0; + + for (int numIndex = 0; numIndex < N; numIndex++) + { + int number = 0, addition; + scanf("%d", &number); + + addition = getDigitAddition(number); + + max = (max >= addition) ? max : addition; + } + + printf("%s\n", colors[max]); + + } + return 0; +} \ No newline at end of file diff --git a/pool/shard001/C++/0022641_scheduler_tests.cpp b/pool/shard001/C++/0022641_scheduler_tests.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2e5a7549b7820233ed17b299f4944584092305d7 --- /dev/null +++ b/pool/shard001/C++/0022641_scheduler_tests.cpp @@ -0,0 +1,206 @@ +// Copyright (c) 2012-2020 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 + +BOOST_AUTO_TEST_SUITE(scheduler_tests) + +static void microTask(CScheduler& s, std::mutex& mutex, int& counter, int delta, std::chrono::system_clock::time_point rescheduleTime) +{ + { + std::lock_guard lock(mutex); + counter += delta; + } + std::chrono::system_clock::time_point noTime = std::chrono::system_clock::time_point::min(); + if (rescheduleTime != noTime) { + CScheduler::Function f = std::bind(µTask, std::ref(s), std::ref(mutex), std::ref(counter), -delta + 1, noTime); + s.schedule(f, rescheduleTime); + } +} + +BOOST_AUTO_TEST_CASE(manythreads) +{ + // Stress test: hundreds of microsecond-scheduled tasks, + // serviced by 10 threads. + // + // So... ten shared counters, which if all the tasks execute + // properly will sum to the number of tasks done. + // Each task adds or subtracts a random amount from one of the + // counters, and then schedules another task 0-1000 + // microseconds in the future to subtract or add from + // the counter -random_amount+1, so in the end the shared + // counters should sum to the number of initial tasks performed. + CScheduler microTasks; + + std::mutex counterMutex[10]; + int counter[10] = { 0 }; + FastRandomContext rng{/* fDeterministic */ true}; + auto zeroToNine = [](FastRandomContext& rc) -> int { return rc.randrange(10); }; // [0, 9] + auto randomMsec = [](FastRandomContext& rc) -> int { return -11 + (int)rc.randrange(1012); }; // [-11, 1000] + auto randomDelta = [](FastRandomContext& rc) -> int { return -1000 + (int)rc.randrange(2001); }; // [-1000, 1000] + + std::chrono::system_clock::time_point start = std::chrono::system_clock::now(); + std::chrono::system_clock::time_point now = start; + std::chrono::system_clock::time_point first, last; + size_t nTasks = microTasks.getQueueInfo(first, last); + BOOST_CHECK(nTasks == 0); + + for (int i = 0; i < 100; ++i) { + std::chrono::system_clock::time_point t = now + std::chrono::microseconds(randomMsec(rng)); + std::chrono::system_clock::time_point tReschedule = now + std::chrono::microseconds(500 + randomMsec(rng)); + int whichCounter = zeroToNine(rng); + CScheduler::Function f = std::bind(µTask, std::ref(microTasks), + std::ref(counterMutex[whichCounter]), std::ref(counter[whichCounter]), + randomDelta(rng), tReschedule); + microTasks.schedule(f, t); + } + nTasks = microTasks.getQueueInfo(first, last); + BOOST_CHECK(nTasks == 100); + BOOST_CHECK(first < last); + BOOST_CHECK(last > now); + + // As soon as these are created they will start running and servicing the queue + boost::thread_group microThreads; + for (int i = 0; i < 5; i++) + microThreads.create_thread(std::bind(&CScheduler::serviceQueue, µTasks)); + + UninterruptibleSleep(std::chrono::microseconds{600}); + now = std::chrono::system_clock::now(); + + // More threads and more tasks: + for (int i = 0; i < 5; i++) + microThreads.create_thread(std::bind(&CScheduler::serviceQueue, µTasks)); + for (int i = 0; i < 100; i++) { + std::chrono::system_clock::time_point t = now + std::chrono::microseconds(randomMsec(rng)); + std::chrono::system_clock::time_point tReschedule = now + std::chrono::microseconds(500 + randomMsec(rng)); + int whichCounter = zeroToNine(rng); + CScheduler::Function f = std::bind(µTask, std::ref(microTasks), + std::ref(counterMutex[whichCounter]), std::ref(counter[whichCounter]), + randomDelta(rng), tReschedule); + microTasks.schedule(f, t); + } + + // Drain the task queue then exit threads + microTasks.StopWhenDrained(); + microThreads.join_all(); // ... wait until all the threads are done + + int counterSum = 0; + for (int i = 0; i < 10; i++) { + BOOST_CHECK(counter[i] != 0); + counterSum += counter[i]; + } + BOOST_CHECK_EQUAL(counterSum, 200); +} + +BOOST_AUTO_TEST_CASE(wait_until_past) +{ + std::condition_variable condvar; + Mutex mtx; + WAIT_LOCK(mtx, lock); + + const auto no_wait= [&](const std::chrono::seconds& d) { + return condvar.wait_until(lock, std::chrono::system_clock::now() - d); + }; + + BOOST_CHECK(std::cv_status::timeout == no_wait(std::chrono::seconds{1})); + BOOST_CHECK(std::cv_status::timeout == no_wait(std::chrono::minutes{1})); + BOOST_CHECK(std::cv_status::timeout == no_wait(std::chrono::hours{1})); + BOOST_CHECK(std::cv_status::timeout == no_wait(std::chrono::hours{10})); + BOOST_CHECK(std::cv_status::timeout == no_wait(std::chrono::hours{100})); + BOOST_CHECK(std::cv_status::timeout == no_wait(std::chrono::hours{1000})); +} + +BOOST_AUTO_TEST_CASE(singlethreadedscheduler_ordered) +{ + CScheduler scheduler; + + // each queue should be well ordered with respect to itself but not other queues + SingleThreadedSchedulerClient queue1(&scheduler); + SingleThreadedSchedulerClient queue2(&scheduler); + + // create more threads than queues + // if the queues only permit execution of one task at once then + // the extra threads should effectively be doing nothing + // if they don't we'll get out of order behaviour + boost::thread_group threads; + for (int i = 0; i < 5; ++i) { + threads.create_thread(std::bind(&CScheduler::serviceQueue, &scheduler)); + } + + // these are not atomic, if SinglethreadedSchedulerClient prevents + // parallel execution at the queue level no synchronization should be required here + int counter1 = 0; + int counter2 = 0; + + // just simply count up on each queue - if execution is properly ordered then + // the callbacks should run in exactly the order in which they were enqueued + for (int i = 0; i < 100; ++i) { + queue1.AddToProcessQueue([i, &counter1]() { + bool expectation = i == counter1++; + assert(expectation); + }); + + queue2.AddToProcessQueue([i, &counter2]() { + bool expectation = i == counter2++; + assert(expectation); + }); + } + + // finish up + scheduler.StopWhenDrained(); + threads.join_all(); + + BOOST_CHECK_EQUAL(counter1, 100); + BOOST_CHECK_EQUAL(counter2, 100); +} + +BOOST_AUTO_TEST_CASE(mockforward) +{ + CScheduler scheduler; + + int counter{0}; + CScheduler::Function dummy = [&counter]{counter++;}; + + // schedule jobs for 2, 5 & 8 minutes into the future + + scheduler.scheduleFromNow(dummy, std::chrono::minutes{2}); + scheduler.scheduleFromNow(dummy, std::chrono::minutes{5}); + scheduler.scheduleFromNow(dummy, std::chrono::minutes{8}); + + // check taskQueue + std::chrono::system_clock::time_point first, last; + size_t num_tasks = scheduler.getQueueInfo(first, last); + BOOST_CHECK_EQUAL(num_tasks, 3ul); + + std::thread scheduler_thread([&]() { scheduler.serviceQueue(); }); + + // bump the scheduler forward 5 minutes + scheduler.MockForward(std::chrono::minutes{5}); + + // ensure scheduler has chance to process all tasks queued for before 1 ms from now. + scheduler.scheduleFromNow([&scheduler] { scheduler.stop(); }, std::chrono::milliseconds{1}); + scheduler_thread.join(); + + // check that the queue only has one job remaining + num_tasks = scheduler.getQueueInfo(first, last); + BOOST_CHECK_EQUAL(num_tasks, 1ul); + + // check that the dummy function actually ran + BOOST_CHECK_EQUAL(counter, 2); + + // check that the time of the remaining job has been updated + std::chrono::system_clock::time_point now = std::chrono::system_clock::now(); + int delta = std::chrono::duration_cast(first - now).count(); + // should be between 2 & 3 minutes from now + BOOST_CHECK(delta > 2*60 && delta < 3*60); +} + +BOOST_AUTO_TEST_SUITE_END() diff --git a/pool/shard001/C++/0022643_dns_service_resolve.cpp b/pool/shard001/C++/0022643_dns_service_resolve.cpp new file mode 100644 index 0000000000000000000000000000000000000000..eda7dc3c64daa5b9f7418a11c5013cc0a781379e --- /dev/null +++ b/pool/shard001/C++/0022643_dns_service_resolve.cpp @@ -0,0 +1,114 @@ +#include "mdns.hpp" + +#include + +#ifndef WIN32 // XXX +#include +#endif + +#include +#include + +#include "mdns_utils.hpp" +#include "dns_service_ref.hpp" + + +using namespace v8; +using namespace node; + +namespace node_mdns { + +void +DNSSD_API +OnResolve(DNSServiceRef sdRef, DNSServiceFlags flags, + uint32_t interfaceIndex, DNSServiceErrorType errorCode, + const char * fullname, const char * hosttarget, uint16_t port, + uint16_t txtLen, const unsigned char * txtRecord, void * context) +{ + + Nan::HandleScope scope; + ServiceRef * serviceRef = static_cast(context); + Local callback = serviceRef->GetCallback(); + Local this_ = serviceRef->GetThis(); + + const size_t argc(9); + Local info[argc]; + info[0] = serviceRef->handle(); + info[1] = Nan::New(flags); + info[2] = Nan::New(interfaceIndex); + info[3] = Nan::New(errorCode); + info[4] = stringOrUndefined(fullname); + info[5] = stringOrUndefined(hosttarget); + info[6] = Nan::New( ntohs(port) ); + Local buffer = Nan::NewBuffer(txtLen).ToLocalChecked(); + memcpy(Buffer::Data(buffer), txtRecord, txtLen); + info[7] = buffer; + if (serviceRef->GetContext().IsEmpty()) { + info[8] = Nan::Undefined(); + } else { + info[8] = serviceRef->GetContext(); + } + Nan::AsyncResource asyncResource(LOC(__FILE__, __LINE__)); + asyncResource.runInAsyncScope(this_, callback, argc, info); +} + +NAN_METHOD(DNSServiceResolve) { + + if (argumentCountMismatch(info, 8)) { + return throwArgumentCountMismatchException(info, 8); + } + + if ( ! ServiceRef::HasInstance(info[0])) { + return throwTypeError("argument 1 must be a DNSServiceRef (sdRef)"); + } + ServiceRef * serviceRef = Nan::ObjectWrap::Unwrap(ToObject(info[0])); + if (serviceRef->IsInitialized()) { + return throwError("DNSServiceRef is already initialized"); + } + + if ( ! info[1]->IsInt32()) { + return throwError("argument 2 must be an integer (DNSServiceFlags)"); + } + DNSServiceFlags flags = ToInt32(info[1]); + + if ( ! info[2]->IsUint32() && ! info[2]->IsInt32()) { + return throwTypeError("argument 3 must be an integer (interfaceIndex)"); + } + uint32_t interfaceIndex = ToUint32(info[2]); + + if ( ! info[3]->IsString()) { + return throwTypeError("argument 4 must be a string (name)"); + } + Nan::Utf8String name(info[3]); + + if ( ! info[4]->IsString()) { + return throwTypeError("argument 5 must be a string (service type)"); + } + Nan::Utf8String serviceType(info[4]); + + if ( ! info[5]->IsString()) { + return throwTypeError("argument 6 must be a string (domain)"); + } + Nan::Utf8String domain(info[5]); + + if ( ! info[6]->IsFunction()) { + return throwTypeError("argument 7 must be a function (callBack)"); + } + serviceRef->SetCallback(Local::Cast(info[6])); + + if ( ! info[7]->IsNull() && ! info[7]->IsUndefined()) { + serviceRef->SetContext(info[7]); + } + + DNSServiceErrorType error = DNSServiceResolve( & serviceRef->GetServiceRef(), + flags, interfaceIndex, *name, *serviceType, *domain, OnResolve, serviceRef); + + if (error != kDNSServiceErr_NoError) { + return throwMdnsError(error); + } + if ( ! serviceRef->SetSocketFlags()) { + return throwError("Failed to set socket flags (O_NONBLOCK, FD_CLOEXEC)"); + } +} + +} // end of namespace node_mdns diff --git a/pool/shard001/C++/0022646_fullscreensettings.cpp b/pool/shard001/C++/0022646_fullscreensettings.cpp new file mode 100644 index 0000000000000000000000000000000000000000..29480487cb905d81ffeac972be328054b7432b99 --- /dev/null +++ b/pool/shard001/C++/0022646_fullscreensettings.cpp @@ -0,0 +1,120 @@ +/* ============================================================ + * + * This file is a part of digiKam project + * http://www.digikam.org + * + * Date : 2013-04-29 + * Description : a full screen settings widget + * + * Copyright (C) 2013 by Gilles Caulier + * + * 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. + * + * ============================================================ */ + +// Qt includes + +#include +#include +#include + +// KDE includes + +#include +#include +#include +#include + +// Local includes + +#include "dxmlguiwindow.h" +#include "fullscreensettings.h" + +namespace Digikam +{ + +class FullScreenSettings::Private +{ +public: + + Private() + { + options = FS_NONE; + hideToolBars = 0; + hideThumbBar = 0; + hideSideBars = 0; + } + + int options; + + QCheckBox* hideToolBars; + QCheckBox* hideThumbBar; + QCheckBox* hideSideBars; +}; + +FullScreenSettings::FullScreenSettings(int options, QWidget* const parent) + : QGroupBox(i18n("Full-screen Options"), parent), d(new Private) +{ + d->options = options; + QVBoxLayout* const vlay = new QVBoxLayout(this); + d->hideToolBars = new QCheckBox(i18n("H&ide toolbars"), this); + d->hideToolBars->setWhatsThis(i18n("Hide all toolbars when window switch in full-screen mode.")); + + d->hideThumbBar = new QCheckBox(i18n("Hide &thumbbar"), this); + d->hideThumbBar->setWhatsThis(i18n("Hide thumbbar view when window switch in full-screen mode.")); + + d->hideSideBars = new QCheckBox(i18n("Hide &sidebars"), this); + d->hideSideBars->setWhatsThis(i18n("Hide all side-bars when window switch in full-screen mode.")); + + vlay->addWidget(d->hideToolBars); + vlay->addWidget(d->hideThumbBar); + vlay->addWidget(d->hideSideBars); + vlay->setMargin(0); + vlay->setSpacing(KDialog::spacingHint()); + + if (!(options & FS_TOOLBARS)) d->hideToolBars->hide(); + if (!(options & FS_THUMBBAR)) d->hideThumbBar->hide(); + if (!(options & FS_SIDEBARS)) d->hideSideBars->hide(); +} + +FullScreenSettings::~FullScreenSettings() +{ + delete d; +} + +void FullScreenSettings::readSettings(const KConfigGroup& group) +{ + if (d->options & FS_TOOLBARS) + d->hideToolBars->setChecked(group.readEntry(s_configFullScreenHideToolBarsEntry, false)); + + if (d->options & FS_THUMBBAR) + d->hideThumbBar->setChecked(group.readEntry(s_configFullScreenHideThumbBarEntry, true)); + + if (d->options & FS_SIDEBARS) + d->hideSideBars->setChecked(group.readEntry(s_configFullScreenHideSideBarsEntry, false)); +} + +void FullScreenSettings::saveSettings(KConfigGroup& group) +{ + if (d->options & FS_TOOLBARS) + group.writeEntry(s_configFullScreenHideToolBarsEntry, d->hideToolBars->isChecked()); + + if (d->options & FS_THUMBBAR) + group.writeEntry(s_configFullScreenHideThumbBarEntry, d->hideThumbBar->isChecked()); + + if (d->options & FS_SIDEBARS) + group.writeEntry(s_configFullScreenHideSideBarsEntry, d->hideSideBars->isChecked()); + + group.sync(); +} + +} // namespace Digikam diff --git a/pool/shard001/C++/0022647_SlimeXSlimonadeTycoon.cpp b/pool/shard001/C++/0022647_SlimeXSlimonadeTycoon.cpp new file mode 100644 index 0000000000000000000000000000000000000000..dc128791dae10731e503f382c1c47379fde57726 --- /dev/null +++ b/pool/shard001/C++/0022647_SlimeXSlimonadeTycoon.cpp @@ -0,0 +1,168 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace std; + + +class SlimeXSlimonadeTycoon { +public: + int sell(vector A, vector B, int k) { + int c = 0; + + for(int i=0; i= x) { + c += x; + B[j] -= x; + x = 0; + } else { + c += B[j]; + x -= B[j]; + B[j] = 0; + } + j++; + l--; + } + } + + return c; + } +}; + + +// BEGIN KAWIGIEDIT TESTING +// Generated by KawigiEdit 2.1.4 (beta) modified by pivanof +bool KawigiEdit_RunTest(int testNum, vector p0, vector p1, int p2, bool hasAnswer, int p3) { + cout << "Test " << testNum << ": [" << "{"; + for (int i = 0; int(p0.size()) > i; ++i) { + if (i > 0) { + cout << ","; + } + cout << p0[i]; + } + cout << "}" << "," << "{"; + for (int i = 0; int(p1.size()) > i; ++i) { + if (i > 0) { + cout << ","; + } + cout << p1[i]; + } + cout << "}" << "," << p2; + cout << "]" << endl; + SlimeXSlimonadeTycoon *obj; + int answer; + obj = new SlimeXSlimonadeTycoon(); + clock_t startTime = clock(); + answer = obj->sell(p0, p1, p2); + 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" << p3 << endl; + } + cout << "Your answer:" << endl; + cout << "\t" << answer << endl; + if (hasAnswer) { + res = answer == p3; + } + 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; + all_right = true; + + vector p0; + vector p1; + int p2; + int p3; + + { + // ----- test 0 ----- + int t0[] = {5,1,1}; + p0.assign(t0, t0 + sizeof(t0) / sizeof(t0[0])); + int t1[] = {1,2,3}; + p1.assign(t1, t1 + sizeof(t1) / sizeof(t1[0])); + p2 = 2; + p3 = 5; + all_right = KawigiEdit_RunTest(0, p0, p1, p2, true, p3) && all_right; + // ------------------ + } + + { + // ----- test 1 ----- + int t0[] = {10,20,30}; + p0.assign(t0, t0 + sizeof(t0) / sizeof(t0[0])); + int t1[] = {30,20,10}; + p1.assign(t1, t1 + sizeof(t1) / sizeof(t1[0])); + p2 = 1; + p3 = 40; + all_right = KawigiEdit_RunTest(1, p0, p1, p2, true, p3) && all_right; + // ------------------ + } + + { + // ----- test 2 ----- + int t0[] = {1,2,3,4,5}; + p0.assign(t0, t0 + sizeof(t0) / sizeof(t0[0])); + int t1[] = {5,5,5,5,5}; + p1.assign(t1, t1 + sizeof(t1) / sizeof(t1[0])); + p2 = 5; + p3 = 15; + all_right = KawigiEdit_RunTest(2, p0, p1, p2, true, p3) && all_right; + // ------------------ + } + + { + // ----- test 3 ----- + int t0[] = {10000,0,0,0,0,0,0}; + p0.assign(t0, t0 + sizeof(t0) / sizeof(t0[0])); + int t1[] = {1,2,4,8,16,32,64}; + p1.assign(t1, t1 + sizeof(t1) / sizeof(t1[0])); + p2 = 4; + p3 = 15; + all_right = KawigiEdit_RunTest(3, p0, p1, p2, true, p3) && all_right; + // ------------------ + } + + if (all_right) { + cout << "You're a stud (at least on the example cases)!" << endl; + } else { + cout << "Some of the test cases had errors." << endl; + } + return 0; +} +// END KAWIGIEDIT TESTING +//Powered by KawigiEdit 2.1.4 (beta) modified by pivanof! diff --git a/pool/shard001/C++/0022648_fileenc.cpp b/pool/shard001/C++/0022648_fileenc.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4f3fc3e1a9e64ebec0ebe3f6180067d4b1434f62 --- /dev/null +++ b/pool/shard001/C++/0022648_fileenc.cpp @@ -0,0 +1,140 @@ +/* + --------------------------------------------------------------------------- + Copyright (c) 2002, Dr Brian Gladman < >, Worcester, UK. + All rights reserved. + + LICENSE TERMS + + The free distribution and use of this software in both source and binary + form is allowed (with or without changes) provided that: + + 1. distributions of this source code include the above copyright + notice, this list of conditions and the following disclaimer; + + 2. distributions in binary form include the above copyright + notice, this list of conditions and the following disclaimer + in the documentation and/or other associated materials; + + 3. the copyright holder's name is not used to endorse products + built using this software without specific written permission. + + ALTERNATIVELY, provided that this notice is retained in full, this product + may be distributed under the terms of the GNU General Public License (GPL), + in which case the provisions of the GPL apply INSTEAD OF those given above. + + DISCLAIMER + + This software is provided 'as is' with no explicit or implied warranties + in respect of its properties, including, but not limited to, correctness + and/or fitness for purpose. + ------------------------------------------------------------------------- + Issue Date: 26/08/2003 + + This file implements password based file encryption and authentication + using AES in CTR mode, HMAC-SHA1 authentication and RFC2898 password + based key derivation. + +*/ + +#include + +#include "fileenc.h" + +/* subroutine for data encryption/decryption */ +/* this could be speeded up a lot by aligning */ +/* buffers and using 32 bit operations */ + +static void encr_data(unsigned char data[], unsigned long d_len, fcrypt_ctx cx[1]) +{ + unsigned long i = 0, pos = cx->encr_pos; + + while(i < d_len) + { + if(pos == BLOCK_SIZE) + { unsigned int j = 0; + /* increment encryption nonce */ + while(j < 8 && !++cx->nonce[j]) + ++j; + /* encrypt the nonce to form next xor buffer */ + aes_encrypt(cx->nonce, cx->encr_bfr, cx->encr_ctx); + pos = 0; + } + + data[i++] ^= cx->encr_bfr[pos++]; + } + + cx->encr_pos = pos; +} + +int fcrypt_init( + int mode, /* the mode to be used (input) */ + const unsigned char pwd[], /* the user specified password (input) */ + unsigned int pwd_len, /* the length of the password (input) */ + const unsigned char salt[], /* the salt (input) */ +#ifdef PASSWORD_VERIFIER + unsigned char pwd_ver[PWD_VER_LENGTH], /* 2 byte password verifier (output) */ +#endif + fcrypt_ctx cx[1]) /* the file encryption context (output) */ +{ + unsigned char kbuf[2 * MAX_KEY_LENGTH + PWD_VER_LENGTH]; + + if(pwd_len > MAX_PWD_LENGTH) + return PASSWORD_TOO_LONG; + + if(mode < 1 || mode > 3) + return BAD_MODE; + + cx->mode = mode; + cx->pwd_len = pwd_len; + /* initialise the encryption nonce and buffer pos */ + cx->encr_pos = BLOCK_SIZE; + + /* if we need a random component in the encryption */ + /* nonce, this is where it would have to be set */ + memset(cx->nonce, 0, BLOCK_SIZE * sizeof(unsigned char)); + /* initialise for authentication */ + hmac_sha_begin(cx->auth_ctx); + + /* derive the encryption and authetication keys and the password verifier */ + derive_key(pwd, pwd_len, salt, SALT_LENGTH(mode), KEYING_ITERATIONS, + kbuf, 2 * KEY_LENGTH(mode) + PWD_VER_LENGTH); + /* set the encryption key */ + aes_encrypt_key(kbuf, KEY_LENGTH(mode), cx->encr_ctx); + /* set the authentication key */ + hmac_sha_key(kbuf + KEY_LENGTH(mode), KEY_LENGTH(mode), cx->auth_ctx); +#ifdef PASSWORD_VERIFIER + memcpy(pwd_ver, kbuf + 2 * KEY_LENGTH(mode), PWD_VER_LENGTH); +#endif + /* clear the buffer holding the derived key values */ + memset(kbuf, 0, 2 * KEY_LENGTH(mode) + PWD_VER_LENGTH); + + return GOOD_RETURN; +} + +/* perform 'in place' encryption and authentication */ + +void fcrypt_encrypt(unsigned char data[], unsigned int data_len, fcrypt_ctx cx[1]) +{ + encr_data(data, data_len, cx); + hmac_sha_data(data, data_len, cx->auth_ctx); +} + +/* perform 'in place' authentication and decryption */ + +void fcrypt_decrypt(unsigned char data[], unsigned int data_len, fcrypt_ctx cx[1]) +{ + hmac_sha_data(data, data_len, cx->auth_ctx); + encr_data(data, data_len, cx); +} + +/* close encryption/decryption and return the MAC value */ + +int fcrypt_end(unsigned char mac[], fcrypt_ctx cx[1]) +{ + unsigned int res = cx->mode; + + hmac_sha_end(mac, MAC_LENGTH(cx->mode), cx->auth_ctx); + memset(cx, 0, sizeof(fcrypt_ctx)); /* clear the encryption context */ + return MAC_LENGTH(res); /* return MAC length in bytes */ +} + diff --git a/pool/shard001/C++/0022652_MusicSearchDirectory.cpp b/pool/shard001/C++/0022652_MusicSearchDirectory.cpp new file mode 100644 index 0000000000000000000000000000000000000000..43234b99682500e965c16b672893fd60cfd25155 --- /dev/null +++ b/pool/shard001/C++/0022652_MusicSearchDirectory.cpp @@ -0,0 +1,65 @@ +/* + * Copyright (C) 2005-2013 Team XBMC + * http://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, see + * . + * + */ + +#include "threads/SystemClock.h" +#include "MusicSearchDirectory.h" +#include "music/MusicDatabase.h" +#include "URL.h" +#include "FileItem.h" +#include "utils/log.h" +#include "utils/TimeUtils.h" +#include "guilib/LocalizeStrings.h" + +using namespace XFILE; + +CMusicSearchDirectory::CMusicSearchDirectory(void) +{ +} + +CMusicSearchDirectory::~CMusicSearchDirectory(void) +{ +} + +bool CMusicSearchDirectory::GetDirectory(const CURL& url, CFileItemList &items) +{ + // break up our path + // format is: musicsearch:// + CStdString search(url.GetHostName()); + + if (search.empty()) + return false; + + // and retrieve the search details + items.SetURL(url); + unsigned int time = XbmcThreads::SystemClockMillis(); + CMusicDatabase db; + db.Open(); + db.Search(search, items); + db.Close(); + CLog::Log(LOGDEBUG, "%s (%s) took %u ms", + __FUNCTION__, url.GetRedacted().c_str(), XbmcThreads::SystemClockMillis() - time); + items.SetLabel(g_localizeStrings.Get(137)); // Search + return true; +} + +bool CMusicSearchDirectory::Exists(const CURL& url) +{ + return true; +} diff --git a/pool/shard001/C++/0022653_main.cpp b/pool/shard001/C++/0022653_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..032a9ae7a9ff49c84eccb913934a90d1c308a04e --- /dev/null +++ b/pool/shard001/C++/0022653_main.cpp @@ -0,0 +1,90 @@ +#include +#include +#include +#include +#include + +/* + * Solution: the algorithm works as follows + * + * 1. Handle edge cases --> if the string is empty, return s. If the string has only spaces, return the empty string. + * + * 2. Loop over all the spaces in the front of the string. + * + * 3. Iterate through the rest of the string and parse out the individual words and put them in a std::deque + * front-first. This way, the words will be reversed when we remove them from the std::deque front-first. + * + * 4. While the std::deque is not empty, remove each word from the front of the std::deque and add it to s. If the + * word is not the last word in the std::deque, add a space after it. + * + * 5. Return the input string. + * + * Time complexity: O(n) [where n is the length of the input string] + * Space complexity: O(m) [where m is the number of non-space characters] + */ + +class Solution +{ + public: + + std::string reverseWords(std::string s) + { + if(s.empty()) + { + return s; + } + + if(std::all_of(s.begin(), s.end(), [] (const auto & character) {return std::isspace(character);})) + { + return ""; + } + + std::deque words; + + int n=int(s.size()); + + int index=0; + + while(index < n && std::isspace(s[index])) + { + index++; + } + + std::string word{}; + + while(index < n) + { + while(index < n && !std::isspace(s[index])) + { + word+=s[index]; + + index++; + } + + words.emplace_front(word); + + word.clear(); + + while(index < n && std::isspace(s[index])) + { + index++; + } + } + + s.clear(); + + while(!words.empty()) + { + s+=words.front(); + + if(words.size() > 1) + { + s+=" "; + } + + words.pop_front(); + } + + return s; + } +}; \ No newline at end of file diff --git a/pool/shard001/C++/0022654_connector.cc b/pool/shard001/C++/0022654_connector.cc new file mode 100644 index 0000000000000000000000000000000000000000..4879ae822d903b120e64473f63b80705dfd4584f --- /dev/null +++ b/pool/shard001/C++/0022654_connector.cc @@ -0,0 +1,63 @@ +#include "network/connector.h" +#include "network/event_pool.h" +#include "network/socket.h" +#include + +using namespace yohub; + +Connector::Connector(EventPool* event_pool, + const InetAddress& remote_addr) + : event_pool_(event_pool), + remote_addr_(remote_addr), + connect_(0), + status_(kDisconnected) +{ +} + +Connector::~Connector() { +} + +void Connector::Connect() { + if (AtomicGetValue(status_) == kDisconnected) { + AtomicSetValue(connect_, 1); + event_pool_->PostJob(boost::bind(&Connector::QueueConnect, this)); + } +} + +void Connector::QueueConnect() { + int newfd = Socket::CreateNonblockingSocket(); + int result = Socket::Connect(newfd, remote_addr_.sockaddr_in()); + if (result == 0 || errno == EINPROGRESS) { + Connecting(newfd); + } else { + ::close(newfd); + LOG_WARN("connect error: %s", strerror(errno)); + } +} + +void Connector::Connecting(int sockfd) { + AtomicSetValue(status_, kConnecting); + + conn_channel_.reset(new Channel(event_pool_, sockfd)); + conn_channel_->SetWriteCallback( + boost::bind(&Connector::OnConnect, this)); + + conn_channel_->Register(); +} + +void Connector::OnConnect() { + if (AtomicSetValue(status_, kConnected) == kConnecting) { + conn_channel_->Unregister(); + int fd = conn_channel_->fd(); + if (AtomicGetValue(connect_) == 1) + on_new_connection_cb_(fd); + else + ::close(fd); + } else { + LOG_WARN("OnConnect error occur"); + } +} + +void Connector::Retry() { + +} diff --git a/pool/shard001/C++/0022655_run.cpp b/pool/shard001/C++/0022655_run.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bfcd3485adf3d29e824cee2b59f01866405ca8ad --- /dev/null +++ b/pool/shard001/C++/0022655_run.cpp @@ -0,0 +1,126 @@ +/* + * run.cpp + * + * Created on: Dec 7, 2013 + * Author: vassik + */ + +#include +#include +#include + +#include "client-server/WebSocketMirrorServer.h" +#include "libs/Log.h" +#include "libs/Utility.h" + +#include "client-server/WebSocketFacade.h" +#include "client-server/WebSocketClient.h" + +using namespace std; +using namespace WebSockets; + +void on_open_callback(void* instance, ...){ + Log::Write(LogLevel_Info, "on_open_callback is called by 0x%08x", instance); +} + +void on_close_callback(void* instance, ...){ + Log::Write(LogLevel_Info, "on_close_callback is called by 0x%08x", instance); +} + +void on_error_callback(void* instance, ...){ + va_list arguments; + va_start(arguments, instance); + char* message = va_arg(arguments, char*); + va_end(arguments); + Log::Write(LogLevel_Info, "on_error_callback is called by 0x%08x with message %s", instance, message); +} + +void on_message_callback(void* instance, ...){ + va_list arguments; + va_start(arguments, instance); + char* message = va_arg(arguments, char*); + va_end(arguments); + Log::Write(LogLevel_Info, "on_message_callback is called by 0x%08x with message %s", instance, message); +} + +void sighandler(int sig) +{ + WebSocketMirrorServer* wss = WebSocketMirrorServer::Get(); + wss->close(); + wss->Destroy(); +} + +int main(int argc, char **argv) { + //signal(SIGINT, sighandler); + + //WebSocketMirrorServer* wss = WebSocketMirrorServer::Init(7681); + WebSocketMirrorServer* wss = WebSocketFacade::InitWebSocketMirrorServer(7681, NULL); + + ThingMLCallback* tml_op_open_callback = new ThingMLCallback(on_open_callback, wss); + ThingMLCallback* tml_op_close_callback = new ThingMLCallback(on_close_callback, wss); + ThingMLCallback* tml_op_error_callback = new ThingMLCallback(on_error_callback, wss); + ThingMLCallback* tml_op_message_callback = new ThingMLCallback(on_message_callback, wss); + + wss->setCallbacks(tml_op_open_callback, tml_op_close_callback, tml_op_message_callback, tml_op_error_callback); + //wss = WebSocketMirrorServer::SetCallback(tml_op_open_callback, tml_op_close_callback, tml_op_message_callback, tml_op_error_callback); + + const char* localhost = "localhost"; + + //WebSocketClient* wsc1 = new WebSocketClient(WebSocketFacade::Init(), localhost, 7681, NULL); + //WebSocketClient* wsc2 = new WebSocketClient(WebSocketFacade::Init(), localhost, 7681, NULL); + + WebSocketClient* wsc1 = WebSocketFacade::InitWebSocketClient(localhost, 7681, NULL); + WebSocketClient* wsc2 = WebSocketFacade::InitWebSocketClient(localhost, 7681, NULL); + + ThingMLCallback* tml_op_open_callback1 = new ThingMLCallback(on_open_callback, wsc1); + ThingMLCallback* tml_op_close_callback1 = new ThingMLCallback(on_close_callback, wsc1); + ThingMLCallback* tml_op_error_callback1 = new ThingMLCallback(on_error_callback, wsc1); + ThingMLCallback* tml_op_message_callback1 = new ThingMLCallback(on_message_callback, wsc1); + + ThingMLCallback* tml_op_open_callback2 = new ThingMLCallback(on_open_callback, wsc2); + ThingMLCallback* tml_op_close_callback2 = new ThingMLCallback(on_close_callback, wsc2); + ThingMLCallback* tml_op_error_callback2 = new ThingMLCallback(on_error_callback, wsc2); + ThingMLCallback* tml_op_message_callback2 = new ThingMLCallback(on_message_callback, wsc2); + + wsc1->setCallbacks(tml_op_open_callback1, tml_op_close_callback1, tml_op_message_callback1, tml_op_error_callback1); + wsc2->setCallbacks(tml_op_open_callback2, tml_op_close_callback2, tml_op_message_callback2, tml_op_error_callback2); + + cout << "just before while !!!\n" << endl; + + string ch; + bool loop = true; + while (loop){ + getline(cin, ch); + if(ch == "c"){ + wss->close(); + } + if(ch == "q"){ + loop = false; + } + if(ch == "o"){ + wss->open(); + } + if(ch == "o1"){ + wsc1->open(); + } + if(ch == "o2"){ + wsc2->open(); + } + if(ch == "s1"){ + wsc1->sendMessage("wsc1->sendMessage"); + } + if(ch == "s2"){ + wsc2->sendMessage("wsc2->sendMessage"); + } + if(ch == "c1"){ + wsc1->close(); + } + if(ch == "c2"){ + wsc2->close(); + } + } + + //WebSocketMirrorServer::Halt(); + WebSocketFacade::Destroy(); + cout << "just before exit \n" << endl; +} diff --git a/pool/shard001/C++/0022666_ccn-grid.cc b/pool/shard001/C++/0022666_ccn-grid.cc new file mode 100644 index 0000000000000000000000000000000000000000..d5af24d8050563930b5fe6044383fb20039be9af --- /dev/null +++ b/pool/shard001/C++/0022666_ccn-grid.cc @@ -0,0 +1,130 @@ +/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */ +/* + * Copyright (c) 2011-2012 University of California, Los Angeles + * + * 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: Alexander Afanasyev + */ +// ccn-grid.cc +#include "ns3/core-module.h" +#include "ns3/network-module.h" +#include "ns3/point-to-point-module.h" +#include "ns3/point-to-point-layout-module.h" +#include "ns3/ccnSIM-module.h" +#include "ns3/packet.h" + +using namespace ns3; + +/** + * This scenario simulates a grid topology (using PointToPointGrid module) + * + * (consumer) -- ( ) ----- ( ) + * | | | + * ( ) ------ ( ) ----- ( ) + * | | | + * ( ) ------ ( ) -- (producer) + * + * All links are 1Mbps with propagation 10ms delay. + * + * FIB is populated using CcnGlobalRoutingHelper. + * + * Consumer requests data from producer with frequency 100 interests per second + * (interests contain constantly increasing sequence number). + * + * For every received interest, producer replies with a data packet, containing + * 1024 bytes of virtual payload. + * + * To run scenario and see what is happening, use the following command: + * + * NS_LOG=ccn.Consumer:ccn.Producer ./waf --run=ccn-grid + */ + +int +main (int argc, char *argv[]) +{ + + // Setting default parameters for PointToPoint links and channels + Config::SetDefault ("ns3::PointToPointNetDevice::DataRate", StringValue ("1Mbps")); + Config::SetDefault ("ns3::PointToPointChannel::Delay", StringValue ("10ms")); + Config::SetDefault ("ns3::DropTailQueue::MaxPackets", StringValue ("10")); + + // Read optional command-line parameters (e.g., enable visualizer with ./waf --run=<> --visualize + CommandLine cmd; + cmd.Parse (argc, argv); + + // Creating 3x3 topology + PointToPointHelper p2p; + PointToPointGridHelper grid (3, 3, p2p); + grid.BoundingBox(100,100,200,200); + + Packet::EnablePrinting (); +Packet::EnableChecking (); + + // Install CCN stack on all nodes + ccn::StackHelper ccnHelper; + ccnHelper.SetForwardingStrategy ("ns3::ccn::fw::SIFAH"); + //ccnHelper.SetForwardingStrategy ("ns3::ccn::fw::ccn"); + ccnHelper.SetDefaultRoutes(false); + ccnHelper.InstallAll (); + + //ccnHelper.EnablePcapAll ("prefix"); +/*AsciiTraceHelper ascii; + p2p.EnableAsciiAll (ascii.CreateFileStream ("myfirst.tr")); +p2p.EnablePcapAll ("myfirst");*/ + + // Installing global routing interface on all nodes + ccn::GlobalRoutingHelper ccnGlobalRoutingHelper; + ccnGlobalRoutingHelper.InstallAll (); + + // Getting containers for the consumer/producer + Ptr producer = grid.GetNode (2, 2); + NodeContainer consumerNodes; + consumerNodes.Add (grid.GetNode (0,0)); + + // Install CCN applications + std::string prefix = "/prefix"; + + ccn::AppHelper consumerHelper ("ns3::ccn::ConsumerCbr"); + consumerHelper.SetPrefix (prefix); + consumerHelper.SetAttribute ("Frequency", StringValue ("100")); // 100 interests a second + consumerHelper.SetAttribute ("HopLimit", UintegerValue (155)); + consumerHelper.SetAttribute ("KeyIdRestrSize", UintegerValue (2)); + consumerHelper.SetAttribute ("ObjectHashSize", UintegerValue (32)); + //consumerHelper.SetAttribute ("NameNonce", UintegerValue (5)); + consumerHelper.Install (consumerNodes); + + ccn::AppHelper producerHelper ("ns3::ccn::Producer"); + producerHelper.SetPrefix (prefix); + producerHelper.SetAttribute ("PayloadSize", StringValue("1024")); + //producerHelper.SetAttribute ("NameNonce", UintegerValue (5)); + producerHelper.SetAttribute ("KeyIdRestrSize", UintegerValue (2)); + producerHelper.SetAttribute ("ObjectHashSize", UintegerValue (32)); + producerHelper.Install (producer); + + // Add /prefix origins to ccn::GlobalRouter + ccnGlobalRoutingHelper.AddOrigins (prefix, producer); + + // Calculate and install FIBs + ccn::GlobalRoutingHelper::CalculateRoutes(); + + Simulator::Stop (Seconds (20.0)); + /*ccn::L3AggregateTracer::InstallAll ("aggregate-trace.txt", Seconds (0.1)); + ccn::L3RateTracer::InstallAll ("rate-trace.txt", Seconds (0.1));*/ + ccn::AppDelayTracer::InstallAll("results/grid-Delay.txt"); + Simulator::Run (); + Simulator::Destroy (); + + return 0; +} diff --git a/pool/shard001/C++/0022673_CharacterPlayed.cpp b/pool/shard001/C++/0022673_CharacterPlayed.cpp new file mode 100644 index 0000000000000000000000000000000000000000..59039e83c605b4ab30d738b013383918378011fd --- /dev/null +++ b/pool/shard001/C++/0022673_CharacterPlayed.cpp @@ -0,0 +1,75 @@ +#include "CharacterPlayed.hpp" + +#include + +CharacterPlayed::CharacterPlayed(const std::string& name, + unsigned short health, + unsigned short resistance, + unsigned short strenght, + unsigned short stamina) + : Character(name, health, resistance, strength, stamina), + currentHealth( (float) health), + currentStamina( (float) stamina), + receivedHits(0), + KOs(0), + vulnerable(true), + gainsStamina(true) +{ +} + +CharacterPlayed::CharacterPlayed(const CharacterPlayed& c) + : Character(c.getName(), c.getHealth(), c.getResistance(), + c.getStrength(), c.getStamina() ), + currentHealth(health), + currentStamina(stamina), + receivedHits(0), + KOs(0), + vulnerable(true), + gainsStamina(true) +{ +} + +CharacterPlayed::CharacterPlayed(const Character& c) + : Character(c.getName(), c.getHealth(), c.getResistance(), + c.getStrength(), c.getStamina() ), + currentHealth((float)health), + currentStamina((float)stamina), + receivedHits(0), + KOs(0), + vulnerable(true), + gainsStamina(true) +{ +} + + +void CharacterPlayed::gainStamina(float amount) +{ + currentStamina = std::min(currentStamina+amount, (float)stamina); +} + +void CharacterPlayed::loseStamina(float amount) +{ + currentStamina = std::max(currentStamina-amount, 0.0f); +} + +void CharacterPlayed::gainHealth(float amount) +{ + float maxhealth = health - 0.2f * KOs; + if (maxhealth <= 0) + maxhealth = 0.2f * health; + currentHealth = std::min(currentHealth+amount, maxhealth); +} + +void CharacterPlayed::loseHealth(float amount) +{ + currentHealth = std::max(currentHealth-amount, 0.0f); +} + +void CharacterPlayed::strike() +{ + if (not vulnerable) + { + vulnerable = false; + loseHealth(40); + } +} diff --git a/pool/shard001/C++/0022678_full_matrix_44.cc b/pool/shard001/C++/0022678_full_matrix_44.cc new file mode 100644 index 0000000000000000000000000000000000000000..3fe220521ffb84806ed7ba2e1ec753500914240a --- /dev/null +++ b/pool/shard001/C++/0022678_full_matrix_44.cc @@ -0,0 +1,47 @@ +// --------------------------------------------------------------------- +// +// Copyright (C) 2007 - 2014 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::Tmmult + + +#include "../tests.h" +#include "full_matrix_common.h" + + +std::string output_file_name = "output"; + + +template +void +check () +{ + FullMatrix m, n, o; + make_matrix (m); + make_matrix (n); + make_matrix (o); + + m.Tmmult (n, o, true); + print_matrix (m); + print_matrix (n); + print_matrix (o); + + m.Tmmult (n, o, false); + print_matrix (m); + print_matrix (n); + print_matrix (o); +} + diff --git a/pool/shard001/C++/0022679_file_metrics_provider_unittest.cc b/pool/shard001/C++/0022679_file_metrics_provider_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..3bffb1c44af6beb4d2a15b065b2da586a2a4f588 --- /dev/null +++ b/pool/shard001/C++/0022679_file_metrics_provider_unittest.cc @@ -0,0 +1,190 @@ +// 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 "components/metrics/file_metrics_provider.h" + +#include "base/files/file_util.h" +#include "base/files/memory_mapped_file.h" +#include "base/files/scoped_temp_dir.h" +#include "base/metrics/histogram.h" +#include "base/metrics/histogram_flattener.h" +#include "base/metrics/histogram_persistence.h" +#include "base/metrics/histogram_snapshot_manager.h" +#include "base/metrics/persistent_memory_allocator.h" +#include "base/metrics/statistics_recorder.h" +#include "base/test/test_simple_task_runner.h" +#include "base/thread_task_runner_handle.h" +#include "components/metrics/metrics_pref_names.h" +#include "components/prefs/pref_registry_simple.h" +#include "components/prefs/testing_pref_service.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace { +const char kMetricsName[] = "TestMetrics"; +const char kMetricsFilename[] = "file.metrics"; +} // namespace + +namespace metrics { + +class HistogramFlattenerDeltaRecorder : public base::HistogramFlattener { + public: + HistogramFlattenerDeltaRecorder() {} + + void RecordDelta(const base::HistogramBase& histogram, + const base::HistogramSamples& snapshot) override { + recorded_delta_histogram_names_.push_back(histogram.histogram_name()); + } + + void InconsistencyDetected(base::HistogramBase::Inconsistency problem) + override { + ASSERT_TRUE(false); + } + + void UniqueInconsistencyDetected( + base::HistogramBase::Inconsistency problem) override { + ASSERT_TRUE(false); + } + + void InconsistencyDetectedInLoggedCount(int amount) override { + ASSERT_TRUE(false); + } + + std::vector GetRecordedDeltaHistogramNames() { + return recorded_delta_histogram_names_; + } + + private: + std::vector recorded_delta_histogram_names_; + + DISALLOW_COPY_AND_ASSIGN(HistogramFlattenerDeltaRecorder); +}; + +class FileMetricsProviderTest : public testing::Test { + protected: + FileMetricsProviderTest() + : task_runner_(new base::TestSimpleTaskRunner()), + thread_task_runner_handle_(task_runner_), + prefs_(new TestingPrefServiceSimple) { + EXPECT_TRUE(temp_dir_.CreateUniqueTempDir()); + FileMetricsProvider::RegisterPrefs(prefs_->registry(), kMetricsName); + } + + TestingPrefServiceSimple* prefs() { return prefs_.get(); } + base::FilePath temp_dir() { return temp_dir_.path(); } + base::FilePath metrics_file() { + return temp_dir_.path().AppendASCII(kMetricsFilename); + } + + FileMetricsProvider* provider() { + if (!provider_) + provider_.reset(new FileMetricsProvider(task_runner_, prefs())); + return provider_.get(); + } + + void RunTasks() { + task_runner_->RunUntilIdle(); + } + + private: + scoped_refptr task_runner_; + base::ThreadTaskRunnerHandle thread_task_runner_handle_; + + base::ScopedTempDir temp_dir_; + scoped_ptr prefs_; + scoped_ptr provider_; + + DISALLOW_COPY_AND_ASSIGN(FileMetricsProviderTest); +}; + + +TEST_F(FileMetricsProviderTest, AccessMetrics) { + ASSERT_FALSE(PathExists(metrics_file())); + + { + // Get this first so it isn't created inside the persistent allocator. + base::GetCreateHistogramResultHistogram(); + + base::SetPersistentHistogramMemoryAllocator( + new base::LocalPersistentMemoryAllocator(64 << 10, 0, kMetricsName)); + base::HistogramBase* foo = + base::Histogram::FactoryGet("foo", 1, 100, 10, 0); + base::HistogramBase* bar = + base::Histogram::FactoryGet("bar", 1, 100, 10, 0); + foo->Add(42); + bar->Add(84); + + scoped_ptr allocator( + base::ReleasePersistentHistogramMemoryAllocatorForTesting()); + base::File writer(metrics_file(), + base::File::FLAG_CREATE | base::File::FLAG_WRITE); + ASSERT_TRUE(writer.IsValid()); + ASSERT_EQ(static_cast(allocator->used()), + writer.Write(0, (const char*)allocator->data(), + allocator->used())); + } + + // Register the file and allow the "checker" task to run. + ASSERT_TRUE(PathExists(metrics_file())); + provider()->RegisterFile(metrics_file(), + FileMetricsProvider::FILE_HISTOGRAMS_ATOMIC, + kMetricsName); + + // Record embedded snapshots via snapshot-manager. + provider()->OnDidCreateMetricsLog(); + RunTasks(); + { + HistogramFlattenerDeltaRecorder flattener; + base::HistogramSnapshotManager snapshot_manager(&flattener); + snapshot_manager.StartDeltas(); + provider()->RecordHistogramSnapshots(&snapshot_manager); + snapshot_manager.FinishDeltas(); + EXPECT_EQ(2U, flattener.GetRecordedDeltaHistogramNames().size()); + } + + // Make sure a second call to the snapshot-recorder doesn't break anything. + { + HistogramFlattenerDeltaRecorder flattener; + base::HistogramSnapshotManager snapshot_manager(&flattener); + snapshot_manager.StartDeltas(); + provider()->RecordHistogramSnapshots(&snapshot_manager); + snapshot_manager.FinishDeltas(); + EXPECT_EQ(0U, flattener.GetRecordedDeltaHistogramNames().size()); + } + + // Second full run on the same file should produce nothing. + provider()->OnDidCreateMetricsLog(); + RunTasks(); + { + HistogramFlattenerDeltaRecorder flattener; + base::HistogramSnapshotManager snapshot_manager(&flattener); + snapshot_manager.StartDeltas(); + provider()->RecordHistogramSnapshots(&snapshot_manager); + snapshot_manager.FinishDeltas(); + EXPECT_EQ(0U, flattener.GetRecordedDeltaHistogramNames().size()); + } + + // Update the time-stamp of the file to indicate that it is "new" and + // must be recorded. + { + base::File touch(metrics_file(), + base::File::FLAG_OPEN | base::File::FLAG_WRITE); + ASSERT_TRUE(touch.IsValid()); + base::Time next = base::Time::Now() + base::TimeDelta::FromSeconds(1); + touch.SetTimes(next, next); + } + + // This run should again have "new" histograms. + provider()->OnDidCreateMetricsLog(); + RunTasks(); + { + HistogramFlattenerDeltaRecorder flattener; + base::HistogramSnapshotManager snapshot_manager(&flattener); + snapshot_manager.StartDeltas(); + provider()->RecordHistogramSnapshots(&snapshot_manager); + snapshot_manager.FinishDeltas(); + EXPECT_EQ(2U, flattener.GetRecordedDeltaHistogramNames().size()); + } +} + +} // namespace metrics diff --git a/pool/shard001/C++/0022681_48476.cc b/pool/shard001/C++/0022681_48476.cc new file mode 100644 index 0000000000000000000000000000000000000000..b7add70354bc69b618a21bf982a3c9c757420981 --- /dev/null +++ b/pool/shard001/C++/0022681_48476.cc @@ -0,0 +1,83 @@ +// { dg-do run { target c++11 } } + +// Copyright (C) 2011-2021 Free Software Foundation, Inc. +// +// This file is part of the GNU ISO C++ Library. This library is free +// software; you can redistribute it and/or modify it under the +// terms of the GNU General Public License as published by the +// Free Software Foundation; either version 3, or (at your option) +// any later version. + +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License along +// with this library; see the file COPYING3. If not see +// . + +#include +#include +#include + +template + typename std::decay::type copy(T&& x) + { return std::forward(x); } + +template + void + check_tuple_cat(std::tuple t1, std::tuple t2) + { + typedef std::tuple concatenated; + + auto cat1 = std::tuple_cat( t1, t2 ); + auto cat2 = std::tuple_cat(copy(t1), t2 ); + auto cat3 = std::tuple_cat( t1, copy(t2)); + auto cat4 = std::tuple_cat(copy(t1), copy(t2)); + + static_assert( std::is_same::value, "" ); + static_assert( std::is_same::value, "" ); + static_assert( std::is_same::value, "" ); + static_assert( std::is_same::value, "" ); + + VERIFY( cat1 == cat2 ); + VERIFY( cat1 == cat3 ); + VERIFY( cat1 == cat4 ); + } + +// libstdc++/48476 +void test01() +{ + int i = 0; + std::tuple<> t0; + std::tuple t1(i); + std::tuple t2(i, 0); + std::tuple t3(i, 0, 0); + + check_tuple_cat(t0, t0); + check_tuple_cat(t0, t1); + check_tuple_cat(t0, t2); + check_tuple_cat(t0, t3); + + check_tuple_cat(t1, t0); + check_tuple_cat(t1, t1); + check_tuple_cat(t1, t2); + check_tuple_cat(t1, t3); + + check_tuple_cat(t2, t0); + check_tuple_cat(t2, t1); + check_tuple_cat(t2, t2); + check_tuple_cat(t2, t3); + + check_tuple_cat(t3, t0); + check_tuple_cat(t3, t1); + check_tuple_cat(t3, t2); + check_tuple_cat(t3, t3); +} + +int main() +{ + test01(); + return 0; +} diff --git a/pool/shard001/C++/0022682_main.cpp b/pool/shard001/C++/0022682_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..982ae728f77f9f6c7531f938a6df04dda4252cf5 --- /dev/null +++ b/pool/shard001/C++/0022682_main.cpp @@ -0,0 +1,131 @@ +#include "common.hpp" +#include "deputado.hpp" +#include "empresa.hpp" +#include "gasto.hpp" +#include "anomalia.hpp" +#include "comunidade.hpp" + +map deputados; +map empresas; +vector comunidades; +double custoTotal; + + +////////////////////////////////////////////////////////////////////////// +/// OBS: Tratar 'aa' como uma letra 'a' craseada. Tratar 'eh' como uma letra 'e' com acento agudo. +////////////////////////////////////////////////////////////////////////// + +int main(){ + ////////////////////////////////////////////////////////////////////////// + /// Cadeia de caracteres que armazena cada linha do arquivo csv lido + ////////////////////////////////////////////////////////////////////////// + string line; + + //Leitura do arquivo de planilha "dirty_deputies_v3.csv", com tratamento de erro + ifstream file("dirty_deputies_v3.csv"); + if(!file.is_open()){ + cout << "Erro ao abrir arquivo \"dirty_deputies_v3.csv\", o programa ira encerrar agora" << endl; + return EXIT_FAILURE; + } + + ////////////////////////////////////////////////////////////////////////// + /// Ignora a primeira linha de colunas da planilha + ////////////////////////////////////////////////////////////////////////// + getline(file,line); + + ////////////////////////////////////////////////////////////////////////// + /// Variaveis temporarias para armazenar os seguintes valores das colunas, respectivamente: + /// deputy_name,deputy_state,political_party,refund_description,company_name,company_id,refund_date,refund_value + ////////////////////////////////////////////////////////////////////////// + string nome; + string estado; + string partido; + string descricao; + string nomeEmpresa; + int empresaID; + string dataGasto; + double valorGasto; + string temp; + + + + ////////////////////////////////////////////////////////////////////////// + /// Lê o .csv + ////////////////////////////////////////////////////////////////////////// + while(getline(file,line)){ + nome = estado = partido = descricao = nomeEmpresa = dataGasto = "[]"; + empresaID = -1; + valorGasto = 0.0; + + std::stringstream ss(line); + getline(ss,nome,';'); + getline(ss,estado,';'); + getline(ss,partido,';'); + getline(ss,descricao,';'); + getline(ss,nomeEmpresa,';'); + getline(ss,temp,';');empresaID=atoi(temp.c_str()); + getline(ss,dataGasto,'T');getline(ss,temp,';'); + getline(ss,temp,';');valorGasto=atof(temp.c_str()); + + if( + (nome=="[]") || + (estado=="[]") || + (partido=="[]") || + (descricao=="[]") || + (nomeEmpresa=="[]") || + (dataGasto=="[]") || + (empresaID==-1) || + (valorGasto==0.0) + ){ + // cerr << "Linha '" << line << "' fora do padrão esperado." << endl; + continue; + } + + ////////////////////////////////////////////////////////////////////////// + /// Atribui os valores lidos em nodos do grafo + ////////////////////////////////////////////////////////////////////////// + deputados[nome].nome = nome; + deputados[nome].estado = estado; + deputados[nome].partido = partido; + + empresas[nomeEmpresa].nomeEmpresa = nomeEmpresa; + empresas[nomeEmpresa].empresaID = empresaID; + + gastoIndividual gi{descricao, dataGasto, abs(valorGasto)}; + deputados[nome]+=pair{gi,nomeEmpresa}; + } + + file.close(); + + ////////////////////////////////////////////////////////////////////////// + /// Imprime o resultado do grafo para verificar se a leitura obteve sucesso + ////////////////////////////////////////////////////////////////////////// + + // cout << "numero de grupos de deputado: " << grupoDep.size() << endl; + // for(auto &i:grupoDep){ + // cout << i.first << endl; + // } + // cout << endl; + // cout << "numero de grupos de empresa: " << grupoEmp.size() << endl; + + + ////////////////////////////////////////////////////////////////////////// + /// Metodo de encontrar as comunidades no grafo + ////////////////////////////////////////////////////////////////////////// + //auto coms = comunidades(); + + ////////////////////////////////////////////////////////////////////////// + /// Metodo principal do programa: o que encontra anomalias no grafo + ////////////////////////////////////////////////////////////////////////// + auto anos = anomalias(); + + ////////////////////////////////////////////////////////////////////////// + /// Impressão do resultado das anomalias + ////////////////////////////////////////////////////////////////////////// + //for(auto &com:coms)cout << "aa" << endl; + cout << "Anomalias: " << endl << endl; + for(auto &ano:anos)cout << ano.first << ": " << ano.second << endl; + + // cout << "aaa " << deputados.size() << " " << empresas.size() << endl; + return 0; +} diff --git a/pool/shard001/C++/0022694_http_auth_handler_basic.cc b/pool/shard001/C++/0022694_http_auth_handler_basic.cc new file mode 100644 index 0000000000000000000000000000000000000000..45367857297c8a488bc8a191d6b50d5971862afc --- /dev/null +++ b/pool/shard001/C++/0022694_http_auth_handler_basic.cc @@ -0,0 +1,126 @@ +// Copyright (c) 2011 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/http/http_auth_handler_basic.h" + +#include + +#include "base/base64.h" +#include "base/strings/string_util.h" +#include "base/strings/utf_string_conversions.h" +#include "net/base/net_errors.h" +#include "net/base/net_string_util.h" +#include "net/http/http_auth.h" +#include "net/http/http_auth_challenge_tokenizer.h" +#include "net/http/http_auth_scheme.h" + +namespace net { + +namespace { + +// Parses a realm from an auth challenge, and converts to UTF8-encoding. +// Returns whether the realm is invalid or the parameters are invalid. +// +// Note that if a realm was not specified, we will default it to ""; +// so specifying 'Basic realm=""' is equivalent to 'Basic'. +// +// This is more generous than RFC 2617, which is pretty clear in the +// production of challenge that realm is required. +// +// We allow it to be compatibility with certain embedded webservers that don't +// include a realm (see http://crbug.com/20984.) +// +// The over-the-wire realm is encoded as ISO-8859-1 (aka Latin-1). +// +// TODO(cbentzel): Realm may need to be decoded using RFC 2047 rules as +// well, see http://crbug.com/25790. +bool ParseRealm(const HttpAuthChallengeTokenizer& tokenizer, + std::string* realm) { + CHECK(realm); + realm->clear(); + HttpUtil::NameValuePairsIterator parameters = tokenizer.param_pairs(); + while (parameters.GetNext()) { + if (!base::LowerCaseEqualsASCII(parameters.name(), "realm")) + continue; + + if (!ConvertToUtf8AndNormalize(parameters.value(), kCharsetLatin1, realm)) { + return false; + } + } + return parameters.valid(); +} + +} // namespace + +bool HttpAuthHandlerBasic::Init(HttpAuthChallengeTokenizer* challenge) { + auth_scheme_ = HttpAuth::AUTH_SCHEME_BASIC; + score_ = 1; + properties_ = 0; + return ParseChallenge(challenge); +} + +bool HttpAuthHandlerBasic::ParseChallenge( + HttpAuthChallengeTokenizer* challenge) { + // Verify the challenge's auth-scheme. + if (!base::LowerCaseEqualsASCII(challenge->scheme(), kBasicAuthScheme)) + return false; + + std::string realm; + if (!ParseRealm(*challenge, &realm)) + return false; + + realm_ = realm; + return true; +} + +HttpAuth::AuthorizationResult HttpAuthHandlerBasic::HandleAnotherChallenge( + HttpAuthChallengeTokenizer* challenge) { + // Basic authentication is always a single round, so any responses + // should be treated as a rejection. However, if the new challenge + // is for a different realm, then indicate the realm change. + std::string realm; + if (!ParseRealm(*challenge, &realm)) + return HttpAuth::AUTHORIZATION_RESULT_INVALID; + return (realm_ != realm)? + HttpAuth::AUTHORIZATION_RESULT_DIFFERENT_REALM: + HttpAuth::AUTHORIZATION_RESULT_REJECT; +} + +int HttpAuthHandlerBasic::GenerateAuthTokenImpl( + const AuthCredentials* credentials, const HttpRequestInfo*, + const CompletionCallback&, std::string* auth_token) { + DCHECK(credentials); + // TODO(eroman): is this the right encoding of username/password? + std::string base64_username_password; + base::Base64Encode(base::UTF16ToUTF8(credentials->username()) + ":" + + base::UTF16ToUTF8(credentials->password()), + &base64_username_password); + *auth_token = "Basic " + base64_username_password; + return OK; +} + +HttpAuthHandlerBasic::Factory::Factory() { +} + +HttpAuthHandlerBasic::Factory::~Factory() { +} + +int HttpAuthHandlerBasic::Factory::CreateAuthHandler( + HttpAuthChallengeTokenizer* challenge, + HttpAuth::Target target, + const GURL& origin, + CreateReason reason, + int digest_nonce_count, + const BoundNetLog& net_log, + scoped_ptr* handler) { + // TODO(cbentzel): Move towards model of parsing in the factory + // method and only constructing when valid. + scoped_ptr tmp_handler(new HttpAuthHandlerBasic()); + if (!tmp_handler->InitFromChallenge(challenge, target, origin, net_log)) + return ERR_INVALID_RESPONSE; + handler->swap(tmp_handler); + return OK; +} + +} // namespace net diff --git a/pool/shard001/C++/0022700_OptimizationRemark.cpp b/pool/shard001/C++/0022700_OptimizationRemark.cpp new file mode 100644 index 0000000000000000000000000000000000000000..838ddc64fe07159767d831f0506c6e8518311306 --- /dev/null +++ b/pool/shard001/C++/0022700_OptimizationRemark.cpp @@ -0,0 +1,193 @@ +//===--- OptimizationRemark.cpp - Optimization diagnostics ------*- C++ -*-===// +// +// This source file is part of the Swift.org open source project +// +// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors +// +//===----------------------------------------------------------------------===// +// +/// \file +/// This file defines the remark type and the emitter class that passes can use +/// to emit optimization diagnostics. +// +//===----------------------------------------------------------------------===// + +#include "swift/SIL/OptimizationRemark.h" +#include "swift/AST/DiagnosticEngine.h" +#include "swift/AST/DiagnosticsSIL.h" +#include "swift/Demangling/Demangler.h" +#include "llvm/ADT/StringExtras.h" +#include "llvm/Support/YAMLTraits.h" +#include "llvm/Support/raw_ostream.h" + +using namespace swift; +using namespace OptRemark; + +Argument::Argument(StringRef Key, int N) : Key(Key), Val(llvm::itostr(N)) {} + +Argument::Argument(StringRef Key, long N) : Key(Key), Val(llvm::itostr(N)) {} + +Argument::Argument(StringRef Key, long long N) + : Key(Key), Val(llvm::itostr(N)) {} + +Argument::Argument(StringRef Key, unsigned N) + : Key(Key), Val(llvm::utostr(N)) {} + +Argument::Argument(StringRef Key, unsigned long N) + : Key(Key), Val(llvm::utostr(N)) {} + +Argument::Argument(StringRef Key, unsigned long long N) + : Key(Key), Val(llvm::utostr(N)) {} + +Argument::Argument(StringRef Key, SILFunction *F) + : Key(Key) { + auto DO = Demangle::DemangleOptions::SimplifiedUIDemangleOptions(); + // Enable module names so that we have a way of filtering out + // stdlib-related remarks. + DO.DisplayModuleNames = true; + + Val = (Twine("\"") + Demangle::demangleSymbolAsString(F->getName(), DO) + + "\"") + .str(); + + if (F->hasLocation()) + Loc = F->getLocation().getSourceLoc(); +} + +Argument::Argument(StringRef Key, SILType Ty) : Key(Key) { + llvm::raw_string_ostream OS(Val); + Ty.print(OS); +} + +Argument::Argument(StringRef Key, CanType Ty) : Key(Key) { + llvm::raw_string_ostream OS(Val); + Ty.print(OS); +} + +template std::string Remark::getMsg() const { + std::string Str; + llvm::raw_string_ostream OS(Str); + for (const Argument &Arg : Args) + OS << Arg.Val; + return OS.str(); +} + +template std::string Remark::getDebugMsg() const { + std::string Str; + llvm::raw_string_ostream OS(Str); + + if (IndentDebugWidth) + OS << std::string(" ", IndentDebugWidth); + + for (const Argument &Arg : Args) + OS << Arg.Val; + + OS << "\n"; + return OS.str(); +} + +Emitter::Emitter(StringRef PassName, SILModule &M) + : Module(M), PassName(PassName), + PassedEnabled( + M.getASTContext().LangOpts.OptimizationRemarkPassedPattern && + M.getASTContext().LangOpts.OptimizationRemarkPassedPattern->match( + PassName)), + MissedEnabled( + M.getASTContext().LangOpts.OptimizationRemarkMissedPattern && + M.getASTContext().LangOpts.OptimizationRemarkMissedPattern->match( + PassName)) {} + +template +static void emitRemark(SILModule &Module, const Remark &R, + Diag ID, bool DiagEnabled) { + if (R.getLocation().isInvalid()) + return; + if (auto *Out = Module.getOptRecordStream()) + // YAMLTraits takes a non-const reference even when outputting. + *Out << const_cast &>(R); + if (DiagEnabled) + Module.getASTContext().Diags.diagnose(R.getLocation(), ID, R.getMsg()); +} + +void Emitter::emit(const RemarkPassed &R) { + emitRemark(Module, R, diag::opt_remark_passed, isEnabled()); +} + +void Emitter::emit(const RemarkMissed &R) { + emitRemark(Module, R, diag::opt_remark_missed, isEnabled()); +} + +void Emitter::emitDebug(const RemarkPassed &R) { + llvm::dbgs() << R.getDebugMsg(); +} + +void Emitter::emitDebug(const RemarkMissed &R) { + llvm::dbgs() << R.getDebugMsg(); +} + +namespace llvm { +namespace yaml { + +template struct MappingTraits> { + static void mapping(llvm::yaml::IO &io, Remark &R) { + assert(io.outputting() && "input not implemented"); + + if (io.mapTag("!Passed", std::is_same::value)) + ; + else if (io.mapTag("!Missed", std::is_same::value)) + ; + else + llvm_unreachable("Unknown remark type"); + + // The attributes are read-only for now since we're only support outputting + // them. + StringRef PassName = R.getPassName(); + io.mapRequired("Pass", PassName); + std::string Id = (Twine("sil.") + R.getIdentifier()).str(); + io.mapRequired("Name", Id); + + SourceLoc Loc = R.getLocation(); + if (!io.outputting() || Loc.isValid()) + io.mapOptional("DebugLoc", Loc); + + std::string FN = Demangle::demangleSymbolAsString( + R.getFunction()->getName(), + Demangle::DemangleOptions::SimplifiedUIDemangleOptions()); + io.mapRequired("Function", FN); + io.mapOptional("Args", R.getArgs()); + } +}; + +template <> struct MappingTraits { + static void mapping(IO &io, SourceLoc &Loc) { + assert(io.outputting() && "input not yet implemented"); + + SourceManager *SM = static_cast(io.getContext()); + StringRef File = SM->getDisplayNameForLoc(Loc); + unsigned Line, Col; + std::tie(Line, Col) = SM->getLineAndColumn(Loc); + + io.mapRequired("File", File); + io.mapRequired("Line", Line); + io.mapRequired("Column", Col); + } +}; + +// Implement this as a mapping for now to get proper quotation for the value. +template <> struct MappingTraits { + static void mapping(IO &io, OptRemark::Argument &A) { + assert(io.outputting() && "input not yet implemented"); + io.mapRequired(A.Key.data(), A.Val); + if (A.Loc.isValid()) + io.mapOptional("DebugLoc", A.Loc); + } +}; + +} // end namespace yaml +} // end namespace llvm + +LLVM_YAML_IS_SEQUENCE_VECTOR(OptRemark::Argument) diff --git a/pool/shard001/C++/0022703_rtProcInitExePath-haiku.cpp b/pool/shard001/C++/0022703_rtProcInitExePath-haiku.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6be9cb8763436f7921d465192390592d3133d24f --- /dev/null +++ b/pool/shard001/C++/0022703_rtProcInitExePath-haiku.cpp @@ -0,0 +1,60 @@ +/* $Id$ */ +/** @file + * IPRT - rtProcInitName, Haiku. + */ + +/* + * Copyright (C) 2012 Oracle Corporation + * + * This file is part of VirtualBox Open Source Edition (OSE), as + * available from http://www.virtualbox.org. This file is free software; + * you can redistribute it and/or modify it under the terms of the GNU + * General Public License (GPL) as published by the Free Software + * Foundation, in version 2 as it comes in the "COPYING" file of the + * VirtualBox OSE distribution. VirtualBox OSE is distributed in the + * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. + * + * The contents of this file may alternatively be used under the terms + * of the Common Development and Distribution License Version 1.0 + * (CDDL) only, as it comes in the "COPYING.CDDL" file of the + * VirtualBox OSE distribution, in which case the provisions of the + * CDDL are applicable instead of those of the GPL. + * + * You may elect to license modified versions of this file under the + * terms and conditions of either the GPL or the CDDL or both. + */ + +/******************************************************************************* +* Header Files * +*******************************************************************************/ +#define LOG_GROUP RTLOGGROUP_PROCESS +#ifdef RT_OS_HAIKU +# include +#endif + +#include +#include +#include +#include +#include "internal/process.h" +#include "internal/path.h" + + +DECLHIDDEN(int) rtProcInitExePath(char *pszPath, size_t cchPath) +{ + image_info ImageInfo; + int32 Cookie = 0; + status_t status; + + /* + * Query the image name from the OS, convert and return it. + */ + status = get_next_image_info(0, &Cookie, &ImageInfo); + AssertReturn((status == B_OK), VERR_INTERNAL_ERROR); + + int rc = rtPathFromNativeCopy(pszPath, MIN(cchPath, MAXPATHLEN), ImageInfo.name, NULL); + AssertMsgRCReturn(rc, ("rc=%Rrc pszLink=\"%s\"\nhex: %.*Rhxs\n", rc, pszPath, MIN(cchPath, MAXPATHLEN), pszPath), rc); + + return VINF_SUCCESS; +} + diff --git a/pool/shard001/C++/0022707_FormWidget.cpp b/pool/shard001/C++/0022707_FormWidget.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a4ab681dea0311ef982c242f83ccc1aced0640ec --- /dev/null +++ b/pool/shard001/C++/0022707_FormWidget.cpp @@ -0,0 +1,167 @@ +#include "FormWidget.h" + +#include +#include +#include + +FormWidget::FormWidget(QWidget* parent /*= nullptr*/) + : QWidget(parent) +{ + initLayouts(); +} + +FormWidget::FormWidget(QString table, QWidget* parent /*= nullptr*/) + : QWidget(parent) +{ + initLayouts(); + initButtons(); + initModel(table); + initMapper(); + lock(true); +} + +FormWidget::FormWidget(QSqlTableModel* model, QWidget* parent /*= nullptr*/) + : QWidget(parent), model_(model) +{ + initLayouts(); + initButtons(); + model_->setEditStrategy(QSqlTableModel::OnFieldChange); + initMapper(); + lock(true); +} + +FormWidget::~FormWidget() +{ + delete mapper_; + delete model_; + delete unlockButton_; + delete lockButton_; + delete saveButton_; + delete cancelButton_; + delete deleteButton_; + delete formLayout_; + delete formWidget_; + delete buttonLayout_; + delete mainLayout_; +} + +void FormWidget::initLayouts() +{ + mainLayout_ = new QVBoxLayout(this); + + formWidget_ = new QWidget; + formLayout_ = new QFormLayout(formWidget_); + buttonLayout_ = new QHBoxLayout(); + buttonLayout_->addStretch(); + + mainLayout_->addWidget(formWidget_); + mainLayout_->addLayout(buttonLayout_); + mainLayout_->addStretch(); +} + +void FormWidget::initButtons() +{ + lockButton_ = new QPushButton(QIcon(tr("icon/locked59.png")), tr(":lock"), this); + unlockButton_ = new QPushButton(QIcon(tr("icon/tool683.png")), tr(":unlock"), this); + saveButton_ = new QPushButton(QIcon(tr("icon/save29.png")), tr(":save"), this); + cancelButton_ = new QPushButton(QIcon(tr("icon/delete85.png")), tr(":cancel"), this); + deleteButton_ = new QPushButton(QIcon(tr("icon/delete81.png")), tr(":delete"), this); + + buttonLayout_->addWidget(deleteButton_); + buttonLayout_->addWidget(saveButton_); + buttonLayout_->addWidget(cancelButton_); + buttonLayout_->addWidget(lockButton_); + buttonLayout_->addWidget(unlockButton_); + + saveButton_->setVisible(false); + cancelButton_->setVisible(false); + deleteButton_->setVisible(false); + + connect(lockButton_, &QPushButton::clicked, [=]{ + lock(true); + }); + connect(unlockButton_, &QPushButton::clicked, [=]{ + lock(false); + }); + connect(saveButton_, &QPushButton::clicked, [=]{ + mapper_->submit(); + emit saved(mapper_->currentIndex()); + }); + connect(cancelButton_, &QPushButton::clicked, [=]{ + revertModel(); + emit canceled(); + }); + connect(deleteButton_, &QPushButton::clicked, [=]{ + int index = mapper_->currentIndex(); + int id = model_->record(index).value("id").toInt(); + model_->removeRow(index); + emit deleted(id); + }); +} + +void FormWidget::initModel(QString table) +{ + model_ = new QSqlTableModel(this); + model_->setEditStrategy(QSqlTableModel::OnFieldChange); + model_->setTable(table); + model_->select(); +} + +void FormWidget::initMapper() +{ + mapper_ = new QDataWidgetMapper(this); + mapper_->setModel(model_); +} + +void FormWidget::setCurrentRowIndex(int rowIndex) +{ + mapper_->setCurrentIndex(rowIndex); + lock(true); + saveButton_->setVisible(false); + cancelButton_->setVisible(false); +} + +void FormWidget::setCurrentRowWithId(int rowId) +{ + for (int i = 0; i < model_->rowCount(); ++i) { + QSqlRecord record = model_->record(i); + if (record.value("id") == rowId) { + mapper_->setCurrentIndex(i); + lock(true); + saveButton_->setVisible(false); + cancelButton_->setVisible(false); + return; + } + } +} + +void FormWidget::addRow() +{ + int rowCount = model_->rowCount(); + qDebug() << "RowCOunt: " << rowCount; + if (!model_->insertRow(rowCount)) { + qDebug() << "[ERROR] Couldn't insert new row: " << model_->lastError().text(); + --rowCount; + } + mapper_->setCurrentIndex(rowCount); + lock(false); + lockButton_->setVisible(false); + saveButton_->setVisible(true); + cancelButton_->setVisible(true); + deleteButton_->setVisible(false); +} + +void FormWidget::lock(bool lock) +{ + formWidget_->setEnabled(!lock); + lockButton_->setVisible(!lock); + unlockButton_->setVisible(lock); + deleteButton_->setVisible(!lock); + emit locked(lock); +} + +void FormWidget::revertModel() +{ + model_->revertAll(); + emit model_->dataChanged(QModelIndex(), QModelIndex()); +} diff --git a/pool/shard001/C++/0022708_main.cpp b/pool/shard001/C++/0022708_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5e251fcefbaa12ff0a83f4d949bad3eff1c85098 --- /dev/null +++ b/pool/shard001/C++/0022708_main.cpp @@ -0,0 +1,103 @@ +#include +#include + +//extern World * world; +//extern TextRenderer * text; +//extern Menu * menu; +//extern Directory * project_directory; + +int main(void) { + + Grid * grid = new Grid(); + + world->setMenu(menu); + + glm::mat4 IModelMatrix = glm::scale(glm::translate(glm::mat4(), glm::vec3(0.0f, 0.0f, 0.0f)), glm::vec3(1.0f, 1.0f, 1.0f)); // A bit to the left + + std::string aaaaa = "technology"; + strings->add(aaaaa); + std::string aaaaaa = "templar"; + strings->add(aaaaaa); + std::string f = "test"; + strings->add(f); + std::string l = "telephone"; + strings->add(l); + std::string g = "terminal"; + strings->add(g); + + std::shared_ptr s = strings; + + do { + // Clear the screen + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + glClearColor(0, 0, 0, 0); + glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); + glEnable(GL_BLEND); + glEnable(GL_CULL_FACE); + + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + + world->update(); + + if (world->changed) { + std::cout << "[main.cpp][main]world changed\n"; + project_directory->update(); + world->changed = false; + } + + glm::mat4 MVP = world->ProjectionMatrix * world->ViewMatrix * IModelMatrix; + + project_directory->draw(&MVP); + text->draw(&MVP); + menu->draw(&MVP); + grid->draw(&MVP); + + Menu * aa = menu; + + glfwSwapBuffers(); + + }// Check if the ESC key was pressed or the window was closed + while (glfwGetKey(GLFW_KEY_ESC) != GLFW_PRESS && + glfwGetWindowParam(GLFW_OPENED)); + + // glDeleteProgram(box_shader); + + glfwTerminate(); + +// points of a rectangle visibile to initial view +// static const GLfloat test_vertex_data[] = { +// -0.1f, -0.1f, 1.0f, +// 0.1f, -0.1f, 1.0f, +// -0.1f, 0.1f, 1.0f, +// 0.1f, -0.1f, 1.0f, +// 0.1f, 0.1f, 1.0f, +// -0.1f, 0.1f, 1.0f +// }; +// +// +// +// GLuint tbuffer; +// glGenBuffers(1, &tbuffer); +// glBindBuffer(GL_ARRAY_BUFFER, tbuffer); +// glBufferData(GL_ARRAY_BUFFER, sizeof (test_vertex_data), test_vertex_data, GL_STATIC_DRAW); +// +// //create shaders +// GLuint box_shader = LoadShaders("box.vertexshader", "box.fragmentshader"); +// +// GLuint mvp_uniform = glGetUniformLocation(box_shader, "MVP"); +// +// glUseProgram(box_shader); +// +// glBindBuffer(GL_ARRAY_BUFFER, tbuffer); +// glEnableVertexAttribArray(0); +// glVertexAttribPointer( +// 0, 3, GL_FLOAT, GL_FALSE, 0, (void*) 0); +// +// glUniformMatrix4fv(mvp_uniform, 1, GL_FALSE, &MVP[0][0]); +// glDrawArrays(GL_TRIANGLES, 0, 6); +// glDisableVertexAttribArray(0); + + + return 0; +} + diff --git a/pool/shard001/C++/0022709_AFE-Main-BMX80.cpp b/pool/shard001/C++/0022709_AFE-Main-BMX80.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cf5d433502394a72f382bf87d09fd91dd44bc112 --- /dev/null +++ b/pool/shard001/C++/0022709_AFE-Main-BMX80.cpp @@ -0,0 +1,36 @@ +/* AFE Firmware for smarthome devices, More info: https://afe.smartnydom.pl/ */ +#ifdef AFE_CONFIG_HARDWARE_BMEX80 + +/* ---------Headers ---------*/ + +void initializeBMX80Sensor(void); +void BMX80SensorEventsListener(void); + +/* --------- Body -----------*/ + +void initializeBMX80Sensor(void) { + if (Device.configuration.noOfBMEX80s > 0) { + for (uint8_t i = 0; i < Device.configuration.noOfBMEX80s; i++) { +#ifdef AFE_ESP32 + BMEX80Sensor[i].begin(i, &WirePort0, &WirePort1); +#else + BMEX80Sensor[i].begin(i, &WirePort0); +#endif + } + } +} + +void BMX80SensorEventsListener(void) { + if (Device.configuration.noOfBMEX80s > 0) { + for (uint8_t i = 0; i < Device.configuration.noOfBMEX80s; i++) { + BMEX80Sensor[i].listener(); + if (BMEX80Sensor[i].isReady()) { + MqttAPI.publishBMx80SensorData(i); +#if AFE_FIRMWARE_API == AFE_FIRMWARE_API_DOMOTICZ + HttpDomoticzAPI.publishBMx80SensorData(i); +#endif + } + } + } +} +#endif // AFE_CONFIG_HARDWARE_BMEX80 diff --git a/pool/shard001/C++/0022713_testconfig.cpp b/pool/shard001/C++/0022713_testconfig.cpp new file mode 100644 index 0000000000000000000000000000000000000000..12422e7489714e56da34a811b9360eac855d295d --- /dev/null +++ b/pool/shard001/C++/0022713_testconfig.cpp @@ -0,0 +1,140 @@ + +#include +#include +#include "plictests.h" + +TEST_GROUP(Config) +{ + void teardown() + { + /* Remove all log files generated in ./misc/output: */ + PyRun_SimpleString("import os;import glob;\ + [os.remove(logFile) for logFile in glob.glob('misc/output/*.log')]"); + } + + bool doesFileExist(const char *filename) + { + FILE *fp(fopen(filename, "r")); + + if (fp == NULL) + return false; + + fclose(fp); + + return true; + } +}; + +TEST(Config, config01SimpleString) +{ + const std::string expected("DEBUG:root:" + debugMsg + "\n" + "INFO:root:" + infoMsg + "\n"); + plic::configStr("import logging;\ + logging.getLogger().handlers = [];\ + logging.basicConfig(filename = 'misc/output/test01.log', level = logging.DEBUG)"); + + /* logging.basicConfig() configures the root logger, so don't log to the 'test' logger: */ + plic::debug("") << debugMsg; + plic::info("") << infoMsg; + + CHECK_EQUAL(expected, getContent("misc/output/test01.log")); +} + +TEST(Config, config02SimpleFile) +{ + const std::string expected("test - WARNING - " + warningMsg + "\n"); + const char *outputFilename = "misc/output/test02.log"; + + CHECK_FALSE(doesFileExist(outputFilename)); + + plic::configFile("test/config02.py"); + + plic::debug("test") << debugMsg; + plic::info("test") << infoMsg; + plic::warning("test") << warningMsg; + + CHECK(doesFileExist(outputFilename)); + + CHECK_EQUAL(expected, getContent(outputFilename)); +} + +TEST(Config, config03Utf8ConfigFile) +{ + const std::string logger("test.test-äüöß"); + const std::string nonAsciiMsg("Critical msg. with ä, ö, ü, ß"); + const std::string expected(logger + " : " + nonAsciiMsg + "\n"); + + plic::configFile("test/config03.py"); + + plic::critical(logger) << nonAsciiMsg; + + CHECK_EQUAL(expected, getContent("misc/output/test03.log")); +} + +TEST(Config, config04Latin1ConfigFile) +{ +#if PY_MAJOR_VERSION > 2 + /* Everything is converted to a unicode representation in python3. */ + const std::string logger("test.test-äüöß"); +#else + const std::string logger("test.test-\xe4\xfc\xf6\xdf"); +#endif + const std::string nonAsciiMsg("Error msg. with ä, ö, ü, ß"); + const std::string expected(logger + " : " + nonAsciiMsg + "\n"); + + plic::configFile("test/config04.py"); + + plic::error(logger) << nonAsciiMsg; + + CHECK_EQUAL(expected, getContent("misc/output/test04.log")); +} + +TEST(Config, config05FileWithSyntaxError) +{ + setupLogStream(); + + plic::configFile("test/config05.py"); + + plic::critical("") << criticalMsg; + + CHECK(getLogString().empty()); + + cleanUpLogStream(); +} + +TEST(Config, config06MetaInformation) +{ + const std::string expected("12345: " + debugMsg + "\n"); + const char *outputFilename = "misc/output/test06.log"; + + plic::configFile("test/config06.py"); + + plic::debug("test", plic::LINE, 12345, debugMsg); + + CHECK_EQUAL(expected, getContent(outputFilename)); +} + +TEST(Config, config07StringWithSyntaxError) +{ + setupLogStream(); + + plic::configStr("&&& intended invalid syntax"); + + plic::critical("") << criticalMsg; + + CHECK(getLogString().empty()); + + cleanUpLogStream(); +} + +TEST(Config, nonExistingFile) +{ + setupLogStream(); + + plic::configFile("test/nonexisting.py"); + + plic::critical("") << criticalMsg; + + CHECK(getLogString().empty()); + + cleanUpLogStream(); +} diff --git a/pool/shard001/C++/0022716_http_stream_factory_impl.cc b/pool/shard001/C++/0022716_http_stream_factory_impl.cc new file mode 100644 index 0000000000000000000000000000000000000000..624bdced9b46e7d0a19f3bd5fd03123fde29aa57 --- /dev/null +++ b/pool/shard001/C++/0022716_http_stream_factory_impl.cc @@ -0,0 +1,279 @@ +// 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 "net/http/http_stream_factory_impl.h" + +#include + +#include "base/logging.h" +#include "base/stl_util.h" +#include "net/base/net_util.h" +#include "net/http/http_network_session.h" +#include "net/http/http_server_properties.h" +#include "net/http/http_stream_factory_impl_job.h" +#include "net/http/http_stream_factory_impl_request.h" +#include "net/log/net_log.h" +#include "net/spdy/spdy_http_stream.h" +#include "url/gurl.h" + +namespace net { + +HttpStreamFactoryImpl::HttpStreamFactoryImpl(HttpNetworkSession* session, + bool for_websockets) + : session_(session), + for_websockets_(for_websockets) {} + +HttpStreamFactoryImpl::~HttpStreamFactoryImpl() { + DCHECK(request_map_.empty()); + DCHECK(spdy_session_request_map_.empty()); + + std::set tmp_job_set; + tmp_job_set.swap(orphaned_job_set_); + STLDeleteContainerPointers(tmp_job_set.begin(), tmp_job_set.end()); + DCHECK(orphaned_job_set_.empty()); + + tmp_job_set.clear(); + tmp_job_set.swap(preconnect_job_set_); + STLDeleteContainerPointers(tmp_job_set.begin(), tmp_job_set.end()); + DCHECK(preconnect_job_set_.empty()); +} + +HttpStreamRequest* HttpStreamFactoryImpl::RequestStream( + const HttpRequestInfo& request_info, + RequestPriority priority, + const SSLConfig& server_ssl_config, + const SSLConfig& proxy_ssl_config, + HttpStreamRequest::Delegate* delegate, + const BoundNetLog& net_log) { + DCHECK(!for_websockets_); + return RequestStreamInternal(request_info, + priority, + server_ssl_config, + proxy_ssl_config, + delegate, + NULL, + net_log); +} + +HttpStreamRequest* HttpStreamFactoryImpl::RequestWebSocketHandshakeStream( + const HttpRequestInfo& request_info, + RequestPriority priority, + const SSLConfig& server_ssl_config, + const SSLConfig& proxy_ssl_config, + HttpStreamRequest::Delegate* delegate, + WebSocketHandshakeStreamBase::CreateHelper* create_helper, + const BoundNetLog& net_log) { + DCHECK(for_websockets_); + DCHECK(create_helper); + return RequestStreamInternal(request_info, + priority, + server_ssl_config, + proxy_ssl_config, + delegate, + create_helper, + net_log); +} + +HttpStreamRequest* HttpStreamFactoryImpl::RequestStreamInternal( + const HttpRequestInfo& request_info, + RequestPriority priority, + const SSLConfig& server_ssl_config, + const SSLConfig& proxy_ssl_config, + HttpStreamRequest::Delegate* delegate, + WebSocketHandshakeStreamBase::CreateHelper* + websocket_handshake_stream_create_helper, + const BoundNetLog& net_log) { + Request* request = new Request(request_info.url, + this, + delegate, + websocket_handshake_stream_create_helper, + net_log); + Job* job = new Job(this, session_, request_info, priority, server_ssl_config, + proxy_ssl_config, net_log.net_log()); + request->AttachJob(job); + + const AlternativeServiceVector alternative_service_vector = + GetAlternativeServicesFor(request_info.url); + if (!alternative_service_vector.empty()) { + // TODO(bnc): Pass on multiple alternative services to Job. + const AlternativeService& alternative_service = + alternative_service_vector[0]; + // Never share connection with other jobs for FTP requests. + DCHECK(!request_info.url.SchemeIs("ftp")); + + Job* alternative_job = + new Job(this, session_, request_info, priority, server_ssl_config, + proxy_ssl_config, alternative_service, net_log.net_log()); + request->AttachJob(alternative_job); + + job->WaitFor(alternative_job); + // Make sure to wait until we call WaitFor(), before starting + // |alternative_job|, otherwise |alternative_job| will not notify |job| + // appropriately. + alternative_job->Start(request); + } + + // Even if |alternative_job| has already finished, it will not have notified + // the request yet, since we defer that to the next iteration of the + // MessageLoop, so starting |job| is always safe. + job->Start(request); + return request; +} + +void HttpStreamFactoryImpl::PreconnectStreams( + int num_streams, + const HttpRequestInfo& request_info, + RequestPriority priority, + const SSLConfig& server_ssl_config, + const SSLConfig& proxy_ssl_config) { + DCHECK(!for_websockets_); + AlternativeService alternative_service; + AlternativeServiceVector alternative_service_vector = + GetAlternativeServicesFor(request_info.url); + if (!alternative_service_vector.empty()) { + // TODO(bnc): Pass on multiple alternative services to Job. + alternative_service = alternative_service_vector[0]; + } + Job* job = + new Job(this, session_, request_info, priority, server_ssl_config, + proxy_ssl_config, alternative_service, session_->net_log()); + preconnect_job_set_.insert(job); + job->Preconnect(num_streams); +} + +const HostMappingRules* HttpStreamFactoryImpl::GetHostMappingRules() const { + return session_->params().host_mapping_rules; +} + +AlternativeServiceVector HttpStreamFactoryImpl::GetAlternativeServicesFor( + const GURL& original_url) { + if (!session_->params().use_alternate_protocols) + return AlternativeServiceVector(); + + if (original_url.SchemeIs("ftp")) + return AlternativeServiceVector(); + + HostPortPair origin = HostPortPair::FromURL(original_url); + HttpServerProperties& http_server_properties = + *session_->http_server_properties(); + const AlternativeServiceVector alternative_service_vector = + http_server_properties.GetAlternativeServices(origin); + if (alternative_service_vector.empty()) + return AlternativeServiceVector(); + + AlternativeServiceVector enabled_alternative_service_vector; + for (const AlternativeService& alternative_service : + alternative_service_vector) { + DCHECK(IsAlternateProtocolValid(alternative_service.protocol)); + if (http_server_properties.IsAlternativeServiceBroken( + alternative_service)) { + HistogramAlternateProtocolUsage(ALTERNATE_PROTOCOL_USAGE_BROKEN); + continue; + } + + // Some shared unix systems may have user home directories (like + // http://foo.com/~mike) which allow users to emit headers. This is a bad + // idea already, but with Alternate-Protocol, it provides the ability for a + // single user on a multi-user system to hijack the alternate protocol. + // These systems also enforce ports <1024 as restricted ports. So don't + // allow protocol upgrades to user-controllable ports. + const int kUnrestrictedPort = 1024; + if (!session_->params().enable_user_alternate_protocol_ports && + (alternative_service.port >= kUnrestrictedPort && + origin.port() < kUnrestrictedPort)) + continue; + + origin.set_port(alternative_service.port); + if (alternative_service.protocol >= NPN_SPDY_MINIMUM_VERSION && + alternative_service.protocol <= NPN_SPDY_MAXIMUM_VERSION) { + if (!HttpStreamFactory::spdy_enabled()) + continue; + + if (session_->HasSpdyExclusion(origin)) + continue; + + enabled_alternative_service_vector.push_back(alternative_service); + continue; + } + + DCHECK_EQ(QUIC, alternative_service.protocol); + if (!session_->params().enable_quic) + continue; + + if (session_->quic_stream_factory()->IsQuicDisabled(origin.port())) + continue; + + if (session_->params().disable_insecure_quic && + !original_url.SchemeIs("https")) { + continue; + } + + enabled_alternative_service_vector.push_back(alternative_service); + } + return enabled_alternative_service_vector; +} + +void HttpStreamFactoryImpl::OrphanJob(Job* job, const Request* request) { + DCHECK(ContainsKey(request_map_, job)); + DCHECK_EQ(request_map_[job], request); + DCHECK(!ContainsKey(orphaned_job_set_, job)); + + request_map_.erase(job); + + orphaned_job_set_.insert(job); + job->Orphan(request); +} + +void HttpStreamFactoryImpl::OnNewSpdySessionReady( + const base::WeakPtr& spdy_session, + bool direct, + const SSLConfig& used_ssl_config, + const ProxyInfo& used_proxy_info, + bool was_npn_negotiated, + NextProto protocol_negotiated, + bool using_spdy, + const BoundNetLog& net_log) { + while (true) { + if (!spdy_session) + break; + const SpdySessionKey& spdy_session_key = spdy_session->spdy_session_key(); + // Each iteration may empty out the RequestSet for |spdy_session_key| in + // |spdy_session_request_map_|. So each time, check for RequestSet and use + // the first one. + // + // TODO(willchan): If it's important, switch RequestSet out for a FIFO + // queue (Order by priority first, then FIFO within same priority). Unclear + // that it matters here. + if (!ContainsKey(spdy_session_request_map_, spdy_session_key)) + break; + Request* request = *spdy_session_request_map_[spdy_session_key].begin(); + request->Complete(was_npn_negotiated, protocol_negotiated, using_spdy); + if (for_websockets_) { + // TODO(ricea): Restore this code path when WebSocket over SPDY + // implementation is ready. + NOTREACHED(); + } else { + bool use_relative_url = direct || request->url().SchemeIs("https"); + request->OnStreamReady( + NULL, + used_ssl_config, + used_proxy_info, + new SpdyHttpStream(spdy_session, use_relative_url)); + } + } + // TODO(mbelshe): Alert other valid requests. +} + +void HttpStreamFactoryImpl::OnOrphanedJobComplete(const Job* job) { + orphaned_job_set_.erase(job); + delete job; +} + +void HttpStreamFactoryImpl::OnPreconnectsComplete(const Job* job) { + preconnect_job_set_.erase(job); + delete job; + OnPreconnectsCompleteInternal(); +} + +} // namespace net diff --git a/pool/shard001/C++/0022725_TestCPUInfo.cpp b/pool/shard001/C++/0022725_TestCPUInfo.cpp new file mode 100644 index 0000000000000000000000000000000000000000..37484a52aeac21e48c618a9d5bbda58ea53c1223 --- /dev/null +++ b/pool/shard001/C++/0022725_TestCPUInfo.cpp @@ -0,0 +1,130 @@ +/* + * Copyright (C) 2005-2018 Team Kodi + * This file is part of Kodi - https://kodi.tv + * + * SPDX-License-Identifier: GPL-2.0-or-later + * See LICENSES/README.md for more information. + */ + +#if defined(TARGET_WINDOWS) +# include +#endif + +#include "utils/CPUInfo.h" +#include "utils/Temperature.h" +#include "ServiceBroker.h" +#include "settings/AdvancedSettings.h" +#include "settings/SettingsComponent.h" + +#ifdef TARGET_POSIX +#include "platform/posix/XTimeUtils.h" +#endif + +#include "gtest/gtest.h" + +TEST(TestCPUInfo, getUsedPercentage) +{ + EXPECT_GE(g_cpuInfo.getUsedPercentage(), 0); +} + +TEST(TestCPUInfo, getCPUCount) +{ + EXPECT_GT(g_cpuInfo.getCPUCount(), 0); +} + +TEST(TestCPUInfo, getCPUFrequency) +{ + EXPECT_GE(g_cpuInfo.getCPUFrequency(), 0.f); +} + +namespace +{ +class TemporarySetting +{ +public: + + TemporarySetting(std::string &setting, const char *newValue) : + m_Setting(setting), + m_OldValue(setting) + { + m_Setting = newValue; + } + + ~TemporarySetting() + { + m_Setting = m_OldValue; + } + +private: + + std::string &m_Setting; + std::string m_OldValue; +}; +} + +//Disabled for windows because there is no implementation to get the CPU temp and there will probably never be one +#ifndef TARGET_WINDOWS +TEST(TestCPUInfo, getTemperature) +{ + TemporarySetting command(CServiceBroker::GetSettingsComponent()->GetAdvancedSettings()->m_cpuTempCmd, "echo '50 c'"); + CTemperature t; + EXPECT_TRUE(g_cpuInfo.getTemperature(t)); + EXPECT_TRUE(t.IsValid()); +} +#endif + +TEST(TestCPUInfo, getCPUModel) +{ + std::string s = g_cpuInfo.getCPUModel(); + EXPECT_STRNE("", s.c_str()); +} + +TEST(TestCPUInfo, getCPUBogoMips) +{ + std::string s = g_cpuInfo.getCPUBogoMips(); + EXPECT_STRNE("", s.c_str()); +} + +TEST(TestCPUInfo, getCPUHardware) +{ + std::string s = g_cpuInfo.getCPUHardware(); + EXPECT_STRNE("", s.c_str()); +} + +TEST(TestCPUInfo, getCPURevision) +{ + std::string s = g_cpuInfo.getCPURevision(); + EXPECT_STRNE("", s.c_str()); +} + +TEST(TestCPUInfo, getCPUSerial) +{ + std::string s = g_cpuInfo.getCPUSerial(); + EXPECT_STRNE("", s.c_str()); +} + +TEST(TestCPUInfo, CoreInfo) +{ + ASSERT_TRUE(g_cpuInfo.HasCoreId(0)); + const CoreInfo c = g_cpuInfo.GetCoreInfo(0); + EXPECT_FALSE(c.m_strModel.empty()); +} + +TEST(TestCPUInfo, GetCoresUsageString) +{ + EXPECT_STRNE("", g_cpuInfo.GetCoresUsageString().c_str()); +} + +TEST(TestCPUInfo, GetCPUFeatures) +{ + unsigned int a = g_cpuInfo.GetCPUFeatures(); + (void)a; +} + +TEST(TestCPUInfo, getUsedPercentage_output) +{ + CCPUInfo c; + Sleep(1); //! @todo Support option from main that sets this parameter + int r = c.getUsedPercentage(); + std::cout << "Percentage: " << testing::PrintToString(r) << std::endl; +} diff --git a/pool/shard001/C++/0022726_test_features.cpp b/pool/shard001/C++/0022726_test_features.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d7819550201dd9d4e921c4ebd48884edf0fc04e5 --- /dev/null +++ b/pool/shard001/C++/0022726_test_features.cpp @@ -0,0 +1,137 @@ +/* + * Copyright (c) 2015, The Regents of the University of California (Regents). + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * Please contact the author(s) of this library if you have any questions. + * Authors: Erik Nelson ( eanelson@eecs.berkeley.edu ) + * David Fridovich-Keil ( dfk@eecs.berkeley.edu ) + */ + +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +DEFINE_string(features_image_file, "lenna.png", + "Name of the image used for testing."); + +namespace bsfm { + +class TestFeatures : public ::testing::Test { + protected: + const std::string test_image = strings::JoinFilepath( + BSFM_TEST_DATA_DIR, FLAGS_features_image_file.c_str()); + + const std::vector detector_types = { + "SIFT", "SURF", "FAST", "STAR", "ORB", + "BRISK", "MSER", "GFTT", "HARRIS", "Dense", "SimpleBlob" + }; + + const std::vector descriptor_types = { + "SIFT", "SURF", "BRIEF", "BRISK", "FREAK" + }; + + const std::vector expected_keypoint_counts = { + 1098, 1462, 3603, 180, 500, 163, 172, 1000, 635, 7396, 1 + }; + + const std::vector expected_descriptor_counts = { + 1098, 1098, 1037, 1033, 1019 + }; + + const std::vector expected_descriptor_lengths = { + 128, 64, 32, 64, 64 + }; +}; //\class TestFeatures + +TEST_F(TestFeatures, TestDetectKeypoints) { + // Load the test image. + Image image(test_image.c_str()); + + // Run through the different detector types, detecting keypoints and making + // sure we get the right number. + KeypointDetector detector; + for (size_t ii = 0; ii < detector_types.size(); ++ii) { + detector.SetDetector(detector_types[ii]); + + // Detect keypoints. + KeypointList keypoints; + EXPECT_TRUE(detector.DetectKeypoints(image, keypoints)); + + // Check for the right value. + EXPECT_EQ(expected_keypoint_counts[ii], keypoints.size()); + LOG(INFO) << "Detected " << keypoints.size() + << " keypoints using detector type " << detector_types[ii] << "."; + } +} + +TEST_F(TestFeatures, TestDescribeFeatures) { + // Load the test image. + Image image(test_image.c_str()); + + // Detect keypoints in the image. + KeypointDetector detector; + detector.SetDetector("SIFT"); + + KeypointList keypoints; + detector.DetectKeypoints(image, keypoints); + + DescriptorExtractor extractor; + for (size_t ii = 0; ii < descriptor_types.size(); ++ii) { + EXPECT_TRUE(extractor.SetDescriptor(descriptor_types[ii])); + + // Extract descriptors. + std::vector features; + std::vector descriptors; + EXPECT_TRUE( + extractor.DescribeFeatures(image, keypoints, features, descriptors)); + + // We should get the right number of descriptors. + EXPECT_EQ(expected_descriptor_counts[ii], features.size()); + + // All descriptors should have the correct dimensions. + for (size_t jj = 0; jj < descriptors.size(); ++jj) { + EXPECT_EQ(expected_descriptor_lengths[ii], descriptors[jj].rows()); + } + + LOG(INFO) << "Extracted " << features.size() << " descriptors with " + << descriptors[0].rows() << " dimensions using descriptor type " + << descriptor_types[ii] << "."; + } +} + +} //\namespace bsfm diff --git a/pool/shard001/C++/0022732_interface_test.cpp b/pool/shard001/C++/0022732_interface_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b879c94e9dc4c866a1f791b21c03b838654a774a --- /dev/null +++ b/pool/shard001/C++/0022732_interface_test.cpp @@ -0,0 +1,185 @@ +#include + +#include "interface.hh" +#include "../mock_fooable.hh" + +namespace +{ + using VTableCOW::Fooable; + using Mock::MockFooable; + + void death_tests( Fooable& fooable ) + { +#ifndef NDEBUG + EXPECT_DEATH( fooable.foo(), "" ); + EXPECT_DEATH( fooable.set_value( Mock::other_value ), "" ); +#endif + } + + void test_interface( Fooable& fooable, int initial_value, int new_value ) + { + EXPECT_EQ( fooable.foo(), initial_value ); + fooable.set_value( new_value ); + EXPECT_EQ( fooable.foo(), new_value ); + } + + void test_ref_interface( Fooable& fooable, const MockFooable& mock_fooable, + int new_value ) + { + test_interface(fooable, mock_fooable.foo(), new_value); + EXPECT_EQ( mock_fooable.foo(), new_value ); + } + + void test_copies( Fooable& copy, const Fooable& fooable, int new_value ) + { + auto value = fooable.foo(); + test_interface( copy, value, new_value ); + EXPECT_EQ( fooable.foo(), value ); + ASSERT_NE( value, new_value ); + EXPECT_NE( fooable.foo(), copy.foo() ); + } +} + +TEST( TestVTableCOWFooable, Empty ) +{ + Fooable fooable; + death_tests(fooable); + + Fooable copy(fooable); + death_tests(copy); + + Fooable move( std::move(fooable) ); + death_tests(move); + + Fooable copy_assign; + copy_assign = move; + death_tests(copy_assign); + + Fooable move_assign; + move_assign = std::move(fooable); + death_tests(move_assign); +} + +TEST( TestVTableCOWFooable, CopyFromValue ) +{ + MockFooable mock_fooable; + auto value = mock_fooable.foo(); + Fooable fooable( mock_fooable ); + + test_interface( fooable, value, Mock::other_value ); +} + +TEST( TestVTableCOWFooable, CopyConstruction ) +{ + Fooable fooable = MockFooable(); + Fooable other( fooable ); + test_copies( other, fooable, Mock::other_value ); +} + +TEST( TestVTableCOWFooable, CopyFromValueWithReferenceWrapper ) +{ + MockFooable mock_fooable; + Fooable fooable( std::ref(mock_fooable) ); + + test_ref_interface( fooable, mock_fooable, Mock::other_value ); +} + +TEST( TestVTableCOWFooable, MoveFromValue ) +{ + MockFooable mock_fooable; + auto value = mock_fooable.foo(); + Fooable fooable( std::move(mock_fooable) ); + + test_interface( fooable, value, Mock::other_value ); +} + +TEST( TestVTableCOWFooable, MoveConstruction ) +{ + Fooable fooable = MockFooable(); + auto value = fooable.foo(); + Fooable other( std::move(fooable) ); + + test_interface( other, value, Mock::other_value ); + death_tests(fooable); +} + +TEST( TestVTableCOWFooable, MoveFromValueWithReferenceWrapper ) +{ + MockFooable mock_fooable; + Fooable fooable( std::move(std::ref(mock_fooable)) ); + + test_ref_interface( fooable, mock_fooable, Mock::other_value ); +} + +TEST( TestVTableCOWFooable, CopyAssignFromValue ) +{ + MockFooable mock_fooable; + Fooable fooable; + + auto value = mock_fooable.foo(); + fooable = mock_fooable; + test_interface(fooable, value, Mock::other_value); +} + +TEST( TestVTableCOWFooable, CopyAssignment ) +{ + Fooable fooable = MockFooable(); + Fooable other; + other = fooable; + test_copies( other, fooable, Mock::other_value ); +} + +TEST( TestVTableCOWFooable, CopyAssignFromValueWithReferenceWrapper ) +{ + MockFooable mock_fooable; + Fooable fooable; + + fooable = std::ref(mock_fooable); + test_ref_interface( fooable, mock_fooable, Mock::other_value ); +} + +TEST( TestVTableCOWFooable, MoveAssignFromValue ) +{ + MockFooable mock_fooable; + Fooable fooable; + + auto value = mock_fooable.foo(); + fooable = std::move(mock_fooable); + test_interface(fooable, value, Mock::other_value); +} + +TEST( TestVTableCOWFooable, MoveAssignment ) +{ + Fooable fooable = MockFooable(); + auto value = fooable.foo(); + Fooable other; + other = std::move(fooable); + + test_interface( other, value, Mock::other_value ); + death_tests(fooable); +} + +TEST( TestVTableCOWFooable, MoveAssignFromValueWithReferenceWrapper ) +{ + MockFooable mock_fooable; + Fooable fooable; + + fooable = std::move(std::ref(mock_fooable)); + test_ref_interface( fooable, mock_fooable, Mock::other_value ); +} + +TEST( TestVTableCOWFooable, Cast ) +{ + Fooable fooable = MockFooable(); + + ASSERT_FALSE( fooable.target() == nullptr ); + EXPECT_EQ( fooable.target()->foo(), Mock::value ); +} + +TEST( TestVTableCOWFooable, ConstCast ) +{ + const Fooable fooable = MockFooable(); + + ASSERT_FALSE( fooable.target() == nullptr ); + EXPECT_EQ( fooable.target()->foo(), Mock::value ); +} diff --git a/pool/shard001/C++/0022734_myimageslist.cpp b/pool/shard001/C++/0022734_myimageslist.cpp new file mode 100644 index 0000000000000000000000000000000000000000..98979614455a3dcbc7c1d01bef94798785f7689e --- /dev/null +++ b/pool/shard001/C++/0022734_myimageslist.cpp @@ -0,0 +1,245 @@ +/* ============================================================ + * + * This file is a part of kipi-plugins project + * http://www.kipi-plugins.org + * + * Date : 2008-05-21 + * Description : a widget to display the imagelist + * + * Copyright (C) 2008-2009 by Andi Clemens + * + * 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. + * + * ============================================================ */ + +#define ICONSIZE 64 + +#include "myimageslist.h" +#include "myimageslist.moc" + +// Qt includes. + +#include +#include +#include +#include +#include +#include + +// KDE includes. + +#include + +// LibKIPI includes. + +#include +#include + +// Local includes. + +#include "imagedialog.h" + +using namespace KIPIPlugins; + +namespace KIPIRemoveRedEyesPlugin +{ + +struct MyImagesListPriv +{ + MyImagesListPriv() + { + iface = 0; + totalLabel = 0; + processedLabel = 0; + failedLabel = 0; + } + + int total; + int processed; + int failed; + + QLabel* totalLabel; + QLabel* processedLabel; + QLabel* failedLabel; + + KIPI::Interface* iface; +}; + +MyImagesList::MyImagesList(KIPI::Interface *iface, QWidget* parent) + : ImagesList(iface, parent), d(new MyImagesListPriv) +{ + d->iface = iface; + setAllowRAW(false); + + // -------------------------------------------------------- + + listView()->setColumn(ImagesListView::User1, i18n("Corrected Eyes"), true); + listView()->header()->setResizeMode(QHeaderView::Stretch); + listView()->setWhatsThis(i18n("This is the list of images to remove red eyes from.")); + + // -------------------------------------------------------- + + QGroupBox* summaryGroupBox = new QGroupBox(i18n("Summary")); + + d->totalLabel = new QLabel; + d->processedLabel = new QLabel; + d->failedLabel = new QLabel; + + d->totalLabel->setAlignment(Qt::AlignRight | Qt::AlignTop); + d->processedLabel->setAlignment(Qt::AlignRight | Qt::AlignTop); + d->failedLabel->setAlignment(Qt::AlignRight | Qt::AlignTop); + + QLabel* l1 = new QLabel(i18nc("The total number of images in the list", + "Total:")); + QLabel* l2 = new QLabel(i18nc("number of images successfully processed", + "Success:")); + QLabel* l3 = new QLabel(i18nc("number of images failed to process", + "Failed:")); + + QGridLayout* summaryGroupBoxLayout = new QGridLayout; + summaryGroupBoxLayout->addWidget(l1, 0, 0, 1, 1); + summaryGroupBoxLayout->addWidget(l2, 1, 0, 1, 1); + summaryGroupBoxLayout->addWidget(l3, 2, 0, 1, 1); + summaryGroupBoxLayout->addWidget(d->totalLabel, 0, 1, 1, 1); + summaryGroupBoxLayout->addWidget(d->processedLabel, 1, 1, 1, 1); + summaryGroupBoxLayout->addWidget(d->failedLabel, 2, 1, 1, 1); + summaryGroupBox->setLayout(summaryGroupBoxLayout); + + // -------------------------------------------------------- + + QGridLayout* mainLayout = new QGridLayout(plainPage()); + mainLayout->addWidget(summaryGroupBox, 0, 0, 1, 1); + mainLayout->setMargin(0); + mainLayout->setSpacing(0); + + // -------------------------------------------------------- + + connect(this, SIGNAL(signalImageListChanged(bool)), + this, SLOT(updateSummary())); +} + +MyImagesList::~MyImagesList() +{ + delete d; +} + +void MyImagesList::addEyeCounterByUrl(const KUrl& url, int eyes) +{ + QTreeWidgetItemIterator it(listView()); + while (*it) + { + ImagesListViewItem* item = dynamic_cast(*it); + if (item->url() == url) + { + item->setText(ImagesListView::User1, QString::number(eyes)); + break; + } + ++it; + } + emit signalImageListChanged(imageUrls().isEmpty()); +} + +void MyImagesList::resetEyeCounterColumn() +{ + QTreeWidgetItemIterator it(listView()); + while (*it) + { + ImagesListViewItem* item = dynamic_cast(*it); + item->setText(ImagesListView::User1, QString("")); + ++it; + } + emit signalImageListChanged(imageUrls().isEmpty()); +} + +bool MyImagesList::hasUnprocessedImages() +{ + bool hasNone = false; + + QTreeWidgetItemIterator it(listView()); + while (*it) + { + ImagesListViewItem* item = dynamic_cast(*it); + if (item->text(ImagesListView::User1).toInt() <= 0) + { + hasNone = true; + break; + } + ++it; + } + return hasNone; +} + +void MyImagesList::removeUnprocessedImages() +{ + QTreeWidgetItemIterator it(listView()); + while (*it) + { + ImagesListViewItem* item = dynamic_cast(*it); + // first, deselect item if selected + item->setSelected(false); + + // select the item if no corrections were made + if (item->text(ImagesListView::User1).toInt() <= 0 && + !item->text(ImagesListView::User1).isEmpty()) + { + item->setSelected(true); + } + ++it; + } + slotRemoveItems(); +} + +int MyImagesList::totalImages() const +{ + return d->total; +} + +int MyImagesList::processedImages() const +{ + return d->processed; +} + +int MyImagesList::failedImages() const +{ + return d->failed; +} + +void MyImagesList::resetCounters() +{ + d->total = imageUrls().count(); + d->processed = 0; + d->failed = 0; +} + +void MyImagesList::updateSummary() +{ + resetCounters(); + + QTreeWidgetItemIterator it(listView()); + while (*it) + { + ImagesListViewItem* item = dynamic_cast(*it); + if (!item->text(ImagesListView::User1).isEmpty()) + { + if (item->text(ImagesListView::User1).toInt() > 0) + d->processed++; + else + d->failed++; + } + ++it; + } + + d->totalLabel->setText(QString("%1").arg(d->total)); + d->processedLabel->setText(QString("%1").arg(d->processed)); + d->failedLabel->setText(QString("%1").arg(d->failed)); +} + +} // namespace KIPIRemoveRedEyesPlugin diff --git a/pool/shard001/C++/0022739_plMultistageMsg.cpp b/pool/shard001/C++/0022739_plMultistageMsg.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9bc32f229ba553f920c3ca37f43850a310c27dcc --- /dev/null +++ b/pool/shard001/C++/0022739_plMultistageMsg.cpp @@ -0,0 +1,64 @@ +/*==LICENSE==* + +CyanWorlds.com Engine - MMOG client, server and tools +Copyright (C) 2011 Cyan Worlds, Inc. + +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 . + +Additional permissions under GNU GPL version 3 section 7 + +If you modify this Program, or any covered work, by linking or +combining it with any of RAD Game Tools Bink SDK, Autodesk 3ds Max SDK, +NVIDIA PhysX SDK, Microsoft DirectX SDK, OpenSSL library, Independent +JPEG Group JPEG library, Microsoft Windows Media SDK, or Apple QuickTime SDK +(or a modified version of those libraries), +containing parts covered by the terms of the Bink SDK EULA, 3ds Max EULA, +PhysX SDK EULA, DirectX SDK EULA, OpenSSL and SSLeay licenses, IJG +JPEG Library README, Windows Media SDK EULA, or QuickTime SDK EULA, the +licensors of this Program grant you additional +permission to convey the resulting work. Corresponding Source for a +non-source form of such a combination shall include the source code for +the parts of OpenSSL and IJG JPEG Library used as well as that of the covered +work. + +You can contact Cyan Worlds, Inc. by email legal@cyan.com + or by snail mail at: + Cyan Worlds, Inc. + 14617 N Newport Hwy + Mead, WA 99021 + +*==LICENSE==*/ + +#include "hsStream.h" +#pragma hdrstop + +#include "plMultistageMsg.h" + +void plMultistageModMsg::Read(hsStream *stream, hsResMgr *mgr) +{ + plMessage::IMsgRead(stream, mgr); + + fCmds.Read(stream); + fStageNum = stream->ReadByte(); + fNumLoops = stream->ReadByte(); +} + +void plMultistageModMsg::Write(hsStream *stream, hsResMgr *mgr) +{ + plMessage::IMsgWrite(stream, mgr); + + fCmds.Write(stream); + stream->WriteByte(fStageNum); + stream->WriteByte(fNumLoops); +} diff --git a/pool/shard001/C++/0022755_d3d11_structured_buffer_misaligned_dirty.cpp b/pool/shard001/C++/0022755_d3d11_structured_buffer_misaligned_dirty.cpp new file mode 100644 index 0000000000000000000000000000000000000000..53b3459fb13cab8784e4666083e83695b0737a57 --- /dev/null +++ b/pool/shard001/C++/0022755_d3d11_structured_buffer_misaligned_dirty.cpp @@ -0,0 +1,144 @@ +/****************************************************************************** + * The MIT License (MIT) + * + * Copyright (c) 2015-2019 Baldur Karlsson + * + * 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 "d3d11_test.h" + +struct Structured_Buffer_MisalignedDirty : D3D11GraphicsTest +{ + static constexpr const char *Description = + "Test updating a misaligned chunk of a structured buffer"; + + std::string pixel = R"EOSHADER( + +struct mystruct +{ + uint data[5]; +}; + +StructuredBuffer buf1 : register(t0); +StructuredBuffer buf2 : register(t1); + +float4 main() : SV_Target0 +{ + float3 first = float3(buf1[0].data[0], buf1[0].data[1], buf1[0].data[2]) + + float3(buf2[0].data[0], buf2[0].data[1], buf2[0].data[2]); + + float last = float(buf1[0].data[4]) + float(buf2[0].data[4]); + + return float4(first, last)/100.0f; +} + +)EOSHADER"; + + int main(int argc, char **argv) + { + // initialise, create window, create device, etc + if(!Init(argc, argv)) + return 3; + + if(!opts.MapNoOverwriteOnDynamicBufferSRV) + TEST_ERROR("Can't run Structured_Buffer_MisalignedDirty test without mappable SRVs"); + + ID3DBlobPtr vsblob = Compile(D3DDefaultVertex, "main", "vs_5_0"); + ID3DBlobPtr psblob = Compile(pixel, "main", "ps_5_0"); + + CreateDefaultInputLayout(vsblob); + + ID3D11VertexShaderPtr vs = CreateVS(vsblob); + ID3D11PixelShaderPtr ps = CreatePS(psblob); + + ID3D11BufferPtr vb = MakeBuffer().Vertex().Data(DefaultTri); + + uint32_t data[5 * 100]; + + for(int i = 0; i < 5 * 100; i++) + data[i] = uint32_t(i); + + ID3D11BufferPtr structbuf = + MakeBuffer().Structured(5 * sizeof(uint32_t)).Data(data).SRV().Mappable(); + ID3D11ShaderResourceViewPtr structbufSRV[2] = { + MakeSRV(structbuf), MakeSRV(structbuf).FirstElement(5).NumElements(1), + }; + + while(Running()) + { + ctx->Flush(); + + ClearRenderTargetView(bbRTV, {0.4f, 0.5f, 0.6f, 1.0f}); + + // map the buffer, but only update a misaligned section - so the update won't be aligned to + // structured size. + { + D3D11_MAPPED_SUBRESOURCE mapped = Map(structbuf, 0, D3D11_MAP_WRITE_NO_OVERWRITE); + + uint32_t *ptr = (uint32_t *)mapped.pData; + + if(ptr) + { + // find the 5th element (first in structbufSRV[1]) + ptr += 5 * 5; + + // move to the 3rd uint + ptr += 3; + + // set the next 5 uints to 0 - that means [3], [4] in this element and [0], [1], [2] in + // the next + memset(ptr, 0, sizeof(uint32_t) * 5); + + ctx->Unmap(structbuf, 0); + } + } + + IASetVertexBuffer(vb, sizeof(DefaultA2V), 0); + ctx->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + ctx->IASetInputLayout(defaultLayout); + + ctx->VSSetShader(vs, NULL, 0); + ctx->PSSetShader(ps, NULL, 0); + + ctx->PSSetShaderResources(0, 2, (ID3D11ShaderResourceView **)structbufSRV); + + RSSetViewport({0.0f, 0.0f, (float)screenWidth, (float)screenHeight, 0.0f, 1.0f}); + + ctx->OMSetRenderTargets(1, &bbRTV.GetInterfacePtr(), NULL); + + ctx->Draw(3, 0); + + // ensure the initial state at the start of each frame is always pristine + { + D3D11_MAPPED_SUBRESOURCE mapped = Map(structbuf, 0, D3D11_MAP_WRITE_DISCARD); + + memcpy(mapped.pData, data, sizeof(data)); + + ctx->Unmap(structbuf, 0); + } + + Present(); + } + + return 0; + } +}; + +REGISTER_TEST(Structured_Buffer_MisalignedDirty); \ No newline at end of file diff --git a/pool/shard001/C++/0022759_Latency.cpp b/pool/shard001/C++/0022759_Latency.cpp new file mode 100644 index 0000000000000000000000000000000000000000..54626d93ea3048d96d696383b52dd8ff4092f227 --- /dev/null +++ b/pool/shard001/C++/0022759_Latency.cpp @@ -0,0 +1,215 @@ +/* +* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"). +* You may not use this file except in compliance with the License. +* A copy of the License is located at +* +* http://aws.amazon.com/apache2.0 +* +* or in the "license" file accompanying this file. This file is distributed +* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +* express or implied. See the License for the specific language governing +* permissions and limitations under the License. +*/ + +#include +#include +#include +#include + +#include + +using namespace Aws::Utils::Xml; +using namespace Aws::Utils; + +namespace Aws +{ +namespace ElasticBeanstalk +{ +namespace Model +{ + +Latency::Latency() : + m_p999(0.0), + m_p999HasBeenSet(false), + m_p99(0.0), + m_p99HasBeenSet(false), + m_p95(0.0), + m_p95HasBeenSet(false), + m_p90(0.0), + m_p90HasBeenSet(false), + m_p85(0.0), + m_p85HasBeenSet(false), + m_p75(0.0), + m_p75HasBeenSet(false), + m_p50(0.0), + m_p50HasBeenSet(false), + m_p10(0.0), + m_p10HasBeenSet(false) +{ +} + +Latency::Latency(const XmlNode& xmlNode) : + m_p999(0.0), + m_p999HasBeenSet(false), + m_p99(0.0), + m_p99HasBeenSet(false), + m_p95(0.0), + m_p95HasBeenSet(false), + m_p90(0.0), + m_p90HasBeenSet(false), + m_p85(0.0), + m_p85HasBeenSet(false), + m_p75(0.0), + m_p75HasBeenSet(false), + m_p50(0.0), + m_p50HasBeenSet(false), + m_p10(0.0), + m_p10HasBeenSet(false) +{ + *this = xmlNode; +} + +Latency& Latency::operator =(const XmlNode& xmlNode) +{ + XmlNode resultNode = xmlNode; + + if(!resultNode.IsNull()) + { + XmlNode p999Node = resultNode.FirstChild("P999"); + if(!p999Node.IsNull()) + { + m_p999 = StringUtils::ConvertToDouble(StringUtils::Trim(p999Node.GetText().c_str()).c_str()); + m_p999HasBeenSet = true; + } + XmlNode p99Node = resultNode.FirstChild("P99"); + if(!p99Node.IsNull()) + { + m_p99 = StringUtils::ConvertToDouble(StringUtils::Trim(p99Node.GetText().c_str()).c_str()); + m_p99HasBeenSet = true; + } + XmlNode p95Node = resultNode.FirstChild("P95"); + if(!p95Node.IsNull()) + { + m_p95 = StringUtils::ConvertToDouble(StringUtils::Trim(p95Node.GetText().c_str()).c_str()); + m_p95HasBeenSet = true; + } + XmlNode p90Node = resultNode.FirstChild("P90"); + if(!p90Node.IsNull()) + { + m_p90 = StringUtils::ConvertToDouble(StringUtils::Trim(p90Node.GetText().c_str()).c_str()); + m_p90HasBeenSet = true; + } + XmlNode p85Node = resultNode.FirstChild("P85"); + if(!p85Node.IsNull()) + { + m_p85 = StringUtils::ConvertToDouble(StringUtils::Trim(p85Node.GetText().c_str()).c_str()); + m_p85HasBeenSet = true; + } + XmlNode p75Node = resultNode.FirstChild("P75"); + if(!p75Node.IsNull()) + { + m_p75 = StringUtils::ConvertToDouble(StringUtils::Trim(p75Node.GetText().c_str()).c_str()); + m_p75HasBeenSet = true; + } + XmlNode p50Node = resultNode.FirstChild("P50"); + if(!p50Node.IsNull()) + { + m_p50 = StringUtils::ConvertToDouble(StringUtils::Trim(p50Node.GetText().c_str()).c_str()); + m_p50HasBeenSet = true; + } + XmlNode p10Node = resultNode.FirstChild("P10"); + if(!p10Node.IsNull()) + { + m_p10 = StringUtils::ConvertToDouble(StringUtils::Trim(p10Node.GetText().c_str()).c_str()); + m_p10HasBeenSet = true; + } + } + + return *this; +} + +void Latency::OutputToStream(Aws::OStream& oStream, const char* location, unsigned index, const char* locationValue) const +{ + if(m_p999HasBeenSet) + { + oStream << location << index << locationValue << ".P999=" << StringUtils::URLEncode(m_p999) << "&"; + } + + if(m_p99HasBeenSet) + { + oStream << location << index << locationValue << ".P99=" << StringUtils::URLEncode(m_p99) << "&"; + } + + if(m_p95HasBeenSet) + { + oStream << location << index << locationValue << ".P95=" << StringUtils::URLEncode(m_p95) << "&"; + } + + if(m_p90HasBeenSet) + { + oStream << location << index << locationValue << ".P90=" << StringUtils::URLEncode(m_p90) << "&"; + } + + if(m_p85HasBeenSet) + { + oStream << location << index << locationValue << ".P85=" << StringUtils::URLEncode(m_p85) << "&"; + } + + if(m_p75HasBeenSet) + { + oStream << location << index << locationValue << ".P75=" << StringUtils::URLEncode(m_p75) << "&"; + } + + if(m_p50HasBeenSet) + { + oStream << location << index << locationValue << ".P50=" << StringUtils::URLEncode(m_p50) << "&"; + } + + if(m_p10HasBeenSet) + { + oStream << location << index << locationValue << ".P10=" << StringUtils::URLEncode(m_p10) << "&"; + } + +} + +void Latency::OutputToStream(Aws::OStream& oStream, const char* location) const +{ + if(m_p999HasBeenSet) + { + oStream << location << ".P999=" << StringUtils::URLEncode(m_p999) << "&"; + } + if(m_p99HasBeenSet) + { + oStream << location << ".P99=" << StringUtils::URLEncode(m_p99) << "&"; + } + if(m_p95HasBeenSet) + { + oStream << location << ".P95=" << StringUtils::URLEncode(m_p95) << "&"; + } + if(m_p90HasBeenSet) + { + oStream << location << ".P90=" << StringUtils::URLEncode(m_p90) << "&"; + } + if(m_p85HasBeenSet) + { + oStream << location << ".P85=" << StringUtils::URLEncode(m_p85) << "&"; + } + if(m_p75HasBeenSet) + { + oStream << location << ".P75=" << StringUtils::URLEncode(m_p75) << "&"; + } + if(m_p50HasBeenSet) + { + oStream << location << ".P50=" << StringUtils::URLEncode(m_p50) << "&"; + } + if(m_p10HasBeenSet) + { + oStream << location << ".P10=" << StringUtils::URLEncode(m_p10) << "&"; + } +} + +} // namespace Model +} // namespace ElasticBeanstalk +} // namespace Aws diff --git a/pool/shard001/C++/0022776_220Contains_Duplicate_III.cpp b/pool/shard001/C++/0022776_220Contains_Duplicate_III.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c1e67528e831c67380d1af073f37bbf0bcfbbe86 --- /dev/null +++ b/pool/shard001/C++/0022776_220Contains_Duplicate_III.cpp @@ -0,0 +1,25 @@ +#include "Header.h" + +/* +*Given an array of integers, find out whether there are two distinct +*indices i and j in the array such that the difference between nums[i] and +*nums[j] is at most t and the difference between i and j is at most k. +*/ + + + +class Solution { +public: + bool bool containsNearbyAlmostDuplicate(vector& nums, int k, int t) { + multiset ms; + for (int i = 0; i < nums.size(); ++i) { + if (ms.size() == k + 1) + ms.erase(nums[i - k - 1]); + auto iter = ms.lower_bound(nums[i] - t); + if (iter != ms.end() && (*iter - nums[i]) <= t) + return true; + ms.insert(nums[i]); + } + retrun false; + } +}; \ No newline at end of file diff --git a/pool/shard001/C++/0022794_well.cpp b/pool/shard001/C++/0022794_well.cpp new file mode 100644 index 0000000000000000000000000000000000000000..971f0ce8e9e88800f1367358581ce5ae8fd837c9 --- /dev/null +++ b/pool/shard001/C++/0022794_well.cpp @@ -0,0 +1,75 @@ +/****************************************************************************** + * + * well.cpp + * + * Created: 22.09.2015 2015 by einar + * + * This file is part of the FieldOpt project. + * + * Copyright (C) 2015-2015 Einar J.M. Baumann + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + *****************************************************************************/ + +#include "well.h" +#include "well_exceptions.h" + +namespace Model { +namespace Wells { + +Well::Well(Utilities::Settings::Model settings, + int well_number, + Properties::VariablePropertyContainer *variable_container, + ::Model::Properties::VariablePropertyHandler *variable_handler, + Reservoir::Reservoir *reservoir) +{ + Utilities::Settings::Model::Well well_settings = settings.wells().at(well_number); + + name_ = well_settings.name; + group_ = well_settings.group; + type_ = well_settings.type; + prefered_phase_ = well_settings.prefered_phase; + + heel_.i = new Properties::DiscreteProperty(well_settings.heel.i); + heel_.j = new Properties::DiscreteProperty(well_settings.heel.j); + heel_.k = new Properties::DiscreteProperty(well_settings.heel.k); + + wellbore_radius_ = new Properties::ContinousProperty(well_settings.wellbore_radius); + + controls_ = new QList(); + for (int i = 0; i < well_settings.controls.size(); ++i) + controls_->append(new Control(well_settings.controls[i], well_settings, variable_container, variable_handler)); + + trajectory_ = new Wellbore::Trajectory(well_settings, variable_container, variable_handler, reservoir); +} + +bool Well::IsProducer() +{ + if (type_ == ::Utilities::Settings::Model::WellType::Producer) + return true; + else + return false; +} + +bool Well::IsInjector() +{ + if (type_ == ::Utilities::Settings::Model::WellType::Injector) + return true; + else + return false; +} + +} +} diff --git a/pool/shard001/C++/0022799_botclean.cpp b/pool/shard001/C++/0022799_botclean.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d9116fdd0170a44d2ae8bd27be8dfc148348b187 --- /dev/null +++ b/pool/shard001/C++/0022799_botclean.cpp @@ -0,0 +1,64 @@ +/* + * Same solution for botclean-stochastic + */ +#include +#include +#include +#include + +using namespace std; + +struct coord { + int x, y; + coord() : x(0), y(0) {} + coord(int x, int y) : x(x), y(y) {} + int distance(const coord &other) { + return abs(this->x - other.x) + abs(this->y - other.y); + } +}; + +void next_move(int posr, int posc, vector board) { + vector dirty_cells; + coord bot(posr, posc), next; + int min_dist = INT_MAX, dist, n = board.size(); + + if (board[bot.x][bot.y] == 'd') { + cout << "CLEAN" << endl; + return; + } + + // grid size seems fixed to 5x5, enumerate all the possible dirty cells + for (int i = 0; i < n; i++) + for (int j = 0; j < n; j++) + if (board[i][j] == 'd') dirty_cells.emplace_back(i, j); + + for (coord &c : dirty_cells) { + dist = bot.distance(c); + if (dist < min_dist) { + next = c; + min_dist = dist; + } + } + + if (bot.x < next.x) + cout << "DOWN" << endl; + else if (bot.x > next.x) + cout << "UP" << endl; + else if (bot.y > next.y) + cout << "LEFT" << endl; + else if (bot.y < next.y) + cout << "RIGHT" << endl; +} + +int main(void) { + int pos[2]; + vector board; + cin >> pos[0] >> pos[1]; + for (int i = 0; i < 5; i++) { + string s; + cin >> s; + board.push_back(s); + } + next_move(pos[0], pos[1], board); + return 0; +} diff --git a/pool/shard001/C++/0022805_timer_context.cpp b/pool/shard001/C++/0022805_timer_context.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5fc86deab0893acfc5f0ead308711044f4b23e71 --- /dev/null +++ b/pool/shard001/C++/0022805_timer_context.cpp @@ -0,0 +1,48 @@ +/* + * Copyright 2000-2014 NeuStar, Inc. All rights reserved. + * NeuStar, the Neustar logo and related names and logos are registered + * trademarks, service marks or tradenames of NeuStar, Inc. All other + * product names, company names, marks, logos and symbols may be trademarks + * of their respective owners. + */ + +/* + * timer_context.cpp + * + * Created on: Jun 5, 2014 + * Author: vpoliboy + */ + +#include "cppmetrics/core/timer_context.h" +#include "cppmetrics/core/timer.h" + +namespace cppmetrics { +namespace core { + +TimerContext::TimerContext(Timer &timer) + : timer_(timer) +{ + reset(); +} + +TimerContext::~TimerContext() { stop(); } + +void TimerContext::reset() +{ + active_ = true; + start_time_ = Clock::now(); +} + +std::chrono::nanoseconds TimerContext::stop(uint64_t count) +{ + if (active_) { + std::chrono::nanoseconds dur = Clock::now() - start_time_; + timer_.update(dur, count); + active_ = false; + return dur; + } + return std::chrono::nanoseconds(0); +} + +} /* namespace core */ +} /* namespace cppmetrics */ diff --git a/pool/shard001/C++/0022808_map.cc b/pool/shard001/C++/0022808_map.cc new file mode 100644 index 0000000000000000000000000000000000000000..bed2ea17febbcff6429470de008d82984a91277a --- /dev/null +++ b/pool/shard001/C++/0022808_map.cc @@ -0,0 +1,51 @@ +// 2003-03-01 gp dot bolton at computer dot org + +// Copyright (C) 2003-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 +// . + + +#include + +template + void + do_loop() + { + Container obj; + const int iterations = 250000; + for (int i = 0; i < iterations; ++i) + obj[i] = i; + } + +int +main() +{ +#ifdef TEST_S1 +#define thread_type false +#endif + +#ifdef TEST_T1 +#define thread_type true +#endif + + typedef __gnu_test::maps::type container_types; + typedef test_sequence test_type; + test_type test("create"); + __gnu_cxx::typelist::apply(test, container_types()); + + return 0; +} + diff --git a/pool/shard001/C++/0022813_DatabaseCommand_AddClientAuth.cpp b/pool/shard001/C++/0022813_DatabaseCommand_AddClientAuth.cpp new file mode 100644 index 0000000000000000000000000000000000000000..31b6200e76ee6fabc3495e390b1ec7ecb3fd87fc --- /dev/null +++ b/pool/shard001/C++/0022813_DatabaseCommand_AddClientAuth.cpp @@ -0,0 +1,56 @@ +/* === This file is part of Tomahawk Player - === + * + * Copyright 2010-2011, Leo Franchi + * + * Tomahawk 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. + * + * Tomahawk 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 Tomahawk. If not, see . + */ + +#include "DatabaseCommand_AddClientAuth.h" + +#include "DatabaseImpl.h" +#include "TomahawkSqlQuery.h" +#include "utils/Logger.h" +#include "Source.h" + + +DatabaseCommand_AddClientAuth::DatabaseCommand_AddClientAuth( const QString& clientToken, + const QString& website, + const QString& name, + const QString& userAgent, + QObject* parent ) + : DatabaseCommand( parent ) + , m_clientToken( clientToken ) + , m_website( website ) + , m_name( name ) + , m_userAgent( userAgent ) +{ +} + + +void DatabaseCommand_AddClientAuth::exec( DatabaseImpl* lib ) +{ + TomahawkSqlQuery q = lib->newquery(); + q.prepare( "INSERT INTO http_client_auth (token, website, name, ua, mtime, permissions) VALUES (?, ?, ?, ?, ?, ?)" ); + q.addBindValue( m_clientToken ); + q.addBindValue( m_website ); + q.addBindValue( m_name ); + q.addBindValue( m_userAgent ); + q.addBindValue( 0 ); + q.addBindValue( "*" ); + + if ( !q.exec() ) + { + qWarning() << "Failed to insert http client into auth table!"; + } +} diff --git a/pool/shard001/C++/0022818_plotCursor.cpp b/pool/shard001/C++/0022818_plotCursor.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6803cc1b689f27c6d5c551e27905b38e412b0d11 --- /dev/null +++ b/pool/shard001/C++/0022818_plotCursor.cpp @@ -0,0 +1,210 @@ +/*=================================================================================== + CarDesigner + Copyright Kerry R. Loux 2008-2016 + + No requirement for distribution of wxWidgets libraries, source, or binaries. + (http://www.wxwidgets.org/) + +===================================================================================*/ + +// File: plotCursor.cpp +// Created: 5/5/2011 +// Author: K. Loux +// Description: Represents an oscilloscope cursor on-screen. +// History: +// 5/12/2011 - Renamed to PlotCursor from Cursor due to conflict in X.h, K. Loux + +// Local headers +#include "vRenderer/primitives/plotCursor.h" +#include "vRenderer/primitives/axis.h" +#include "vRenderer/renderWindow.h" +#include "vRenderer/line.h" + +//========================================================================== +// Class: PlotCursor +// Function: PlotCursor +// +// Description: Constructor for the PlotCursor class. +// +// Input Arguments: +// renderWindow = RenderWindow& +// axis = Axis& with which we are associated +// +// Output Arguments: +// None +// +// Return Value: +// None +// +//========================================================================== +PlotCursor::PlotCursor(RenderWindow &renderWindow, const Axis &axis) + : Primitive(renderWindow), axis(axis) +{ + isVisible = false; + color = Color::ColorBlack; +} + +//========================================================================== +// Class: PlotCursor +// Function: Calculate +// +// Description: Updates the value associated with the cursor. +// +// Input Arguments: +// None +// +// Output Arguments: +// None +// +// Return Value: +// None +// +//========================================================================== +void PlotCursor::Calculate() +{ + // Update the value of the cursor (required for accuracy when zoom changes, for example) + value = axis.PixelToValue(locationAlongAxis); +} + +//========================================================================== +// Class: PlotCursor +// Function: GenerateGeometry +// +// Description: Generates OpenGL commands to draw the cursor. +// +// Input Arguments: +// None +// +// Output Arguments: +// None +// +// Return Value: +// None +// +//========================================================================== +void PlotCursor::GenerateGeometry() +{ + Line line; + if (axis.IsHorizontal()) + { + line.Draw(locationAlongAxis, axis.GetOffsetFromWindowEdge(), + locationAlongAxis, renderWindow.GetSize().GetHeight() + - axis.GetOppositeAxis()->GetOffsetFromWindowEdge()); + } + else + { + line.Draw(axis.GetOffsetFromWindowEdge(), locationAlongAxis, + renderWindow.GetSize().GetWidth() + - axis.GetOppositeAxis()->GetOffsetFromWindowEdge(), locationAlongAxis); + } + + Calculate(); +} + +//========================================================================== +// Class: PlotCursor +// Function: HasValidParameters +// +// Description: Checks to see if we're OK to draw the cursor. +// +// Input Arguments: +// None +// +// Output Arguments: +// None +// +// Return Value: +// None +// +//========================================================================== +bool PlotCursor::HasValidParameters() +{ + // Make sure the value is within the axis limits + if (value >= axis.GetMinimum() && value <= axis.GetMaximum() && + axis.GetAxisAtMaxEnd() && axis.GetAxisAtMinEnd()) + return true; + + // If the parameters aren't valid, also hide this to prevent the cursor values from updating + isVisible = false; + + return false; +} + +//========================================================================== +// Class: PlotCursor +// Function: IsUnder +// +// Description: Checks to see if the cursor is located under the specified +// point. +// +// Input Arguments: +// pixel = const unsigned int& describing the location of the point +// in screen coordinates +// +// Output Arguments: +// None +// +// Return Value: +// True is the cursor is under the specified point, false otherwise +// +//========================================================================== +bool PlotCursor::IsUnder(const unsigned int &pixel) +{ + // Apparent line width for clicking + int width = 2;// [pixels] + + if (abs(int(locationAlongAxis - pixel)) <= width && isVisible) + return true; + + return false; +} + +//========================================================================== +// Class: PlotCursor +// Function: SetLocation +// +// Description: Sets the x position where the cursor should appear on the plot. +// +// Input Arguments: +// location = const int& location to set +// +// Output Arguments: +// None +// +// Return Value: +// None +// +//========================================================================== +void PlotCursor::SetLocation(const int& location) +{ + locationAlongAxis = location; + value = axis.PixelToValue(location); + modified = true; +} + +//========================================================================== +// Class: PlotCursor +// Function: operator= +// +// Description: Sets the x-value where the cursor should appear on the plot. +// +// Input Arguments: +// _value = const double& value to set +// +// Output Arguments: +// None +// +// Return Value: +// PlotCursor& reference to this object +// +//========================================================================== +PlotCursor& PlotCursor::operator=(const PlotCursor &target) +{ + if (&target == this) + return *this; + + value = target.value; + locationAlongAxis = target.locationAlongAxis; + + return *this; +} diff --git a/pool/shard001/C++/0022821_Main.cpp b/pool/shard001/C++/0022821_Main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5b766d55e51d842d254ab81b7fb0478ae265add0 --- /dev/null +++ b/pool/shard001/C++/0022821_Main.cpp @@ -0,0 +1,165 @@ +#include "Class.h" +#include "Database.h" +#include "Function.h" +#include "Namespace.h" +#include "Variable.h" +#include "Type.h" + +void Tab(int depth) +{ + for (int i = 0; i < depth; ++i) + std::cout << " "; +} + +void DebugPrint(metagen::Variable *node, int depth = 0) +{ + Tab(depth); + std::cout << node->GetType()->GetDecoratedFullName() << " "; + std::cout << node->GetName() << std::endl; +} + +void DebugPrint(metagen::Function *node, int depth = 0) +{ + Tab(depth); + + switch (node->GetFunctionType()) + { + case metagen::FunctionType::Function: std::cout << "Function: "; break; + case metagen::FunctionType::Method: std::cout << "Method: "; break; + case metagen::FunctionType::Constructor: std::cout << "Constructor: "; break; + case metagen::FunctionType::Destructor: std::cout << "Destructor: "; break; + + default: + break; + } + + std::cout << node->GetReturnType()->GetDecoratedFullName() << " "; + std::cout << node->GetName() << std::endl; + + for (auto &p : node->GetArguments()) + DebugPrint(p.get(), depth + 1); +} + +void DebugPrint(const metagen::Namespace::tOverloads &overloads, int depth) +{ + for (auto &kvp : overloads) + DebugPrint(static_cast(kvp.second.get()), depth); +} + +void DebugPrint(metagen::Namespace *node, int depth = 0) +{ + Tab(depth); + + bool isClass = node->GetNodeType() == metagen::NodeType::Class; + std::cout << (isClass ? "Class: " : "Namespace: ") << node->GetName() << std::endl; + + if (isClass) + { + auto c = static_cast(node); + + for (auto base : c->GetBases()) + { + Tab(depth + 1); + std::cout << " + " << base->GetFullName() << std::endl; + } + + for (auto &ctor : c->GetConstructors()) + DebugPrint(ctor.get(), depth + 1); + + if (c->GetDestructor()) + DebugPrint(c->GetDestructor(), depth + 1); + } + + for (auto &kvp : node->GetChildren()) + { + auto ch = kvp.second.get(); + DebugPrint(ch, depth + 1); + } + + for (auto &kvp : node->GetFunctions()) + DebugPrint(kvp.second, depth + 1); +} + +int main(int argc, char *argv[]) +{ + if (argc < 2) + { + std::cerr << "Not enough arguments!" << std::endl; + return -1; + } + + metagen::Path dir = argv[1]; + + metagen::Database db; + metagen::Path dbFile = "metagen.db"; + db.LoadFromFile(dbFile); + + metagen::Directory::Enumerate(dir, [&](const metagen::Path &fileName) + { + db.ScheduleForProcessing(dir + fileName); + }); + + metagen::Database::tClangArguments args; + + // Clang arguments to make sure everything works with latest Visual Studio 2015 + args.push_back("-xc++"); + args.push_back("-std=c++11"); + args.push_back("-Wno-unknown-attributes"); + args.push_back("-Wno-ignored-attributes"); + args.push_back("-Wno-constant-conversion"); + args.push_back("-Wno-user-defined-literals"); + args.push_back("-fms-compatibility-version=19.00.22609"); + args.push_back("-fdelayed-template-parsing"); + args.push_back("-fms-extensions"); + args.push_back("-D_M_X64"); + args.push_back("-D_WIN64"); + args.push_back("-DWIN64"); + args.push_back("-D_WIN32"); + args.push_back("-DWIN32"); + args.push_back("-D_WIN32_WINNT=0x0601"); + args.push_back("-DWINVER=0x0601"); + args.push_back("-DNTDDI_VERSION=0x06010000"); + args.push_back("-D_MSC_VER=1900"); + args.push_back("-D_MBCS"); + args.push_back("-D_WCHAR_T_DEFINED"); + args.push_back("-D_CRT_SECURE_NO_WARNINGS"); + args.push_back("-DMETAGEN_RUNNING"); + + for (int i = 2; i < argc; ++i) + { + std::string arg = argv[i]; + + if (!arg.compare(0, 2, "-I") || !arg.compare(0, 2, "/I")) + { + arg = arg.substr(2); + + while (true) + { + auto pos = arg.find(';'); + if (pos == std::string::npos) + break; + + auto path = arg.substr(0, pos); + + if (!path.empty()) + args.push_back("-I" + path); + + arg = arg.substr(pos + 1); + } + + if (!arg.empty()) + args.push_back("-I" + arg); + } + else + args.push_back(arg); + } + + db.Process(dir, args); + db.SaveToFile(dbFile); + + std::cout << std::endl; + DebugPrint(db.GetGlobalNamespace()); + std::cout << std::endl; + + return 0; +} diff --git a/pool/shard001/C++/0022822_configstorage.cpp b/pool/shard001/C++/0022822_configstorage.cpp new file mode 100644 index 0000000000000000000000000000000000000000..78d055494c6be44fda7287a6a5dd01059cabdbbc --- /dev/null +++ b/pool/shard001/C++/0022822_configstorage.cpp @@ -0,0 +1,39 @@ +#include "configstorage.h" +#include +#include +#include +#include + +ConfigStorage::ConfigStorage(QObject* parent) + : QObject(parent) +{ + configFilePath = qApp->applicationDirPath() + +#ifdef Q_OS_WIN + "/Data/config_windows.json"; +#elif defined Q_OS_MAC + "/../Resources/Data/config_mac.json"; +#else +#ERROR "usupported platform" +#endif //platform + configFilePath = QDir::toNativeSeparators(configFilePath); +} + +QString ConfigStorage::GetJSONTextFromConfigFile() const +{ + if (!QFile::exists(configFilePath)) + { + QMessageBox::critical(nullptr, QObject::tr("Config file not available!"), QObject::tr("Can not find config file %1").arg(configFilePath)); + exit(0); + } + QFile configFile(configFilePath); + if (configFile.open(QIODevice::ReadOnly)) + { + return configFile.readAll(); + } + else + { + QMessageBox::critical(nullptr, QObject::tr("Failed to open config file!"), QObject::tr("Failed to open config file %1").arg(configFilePath)); + exit(0); + } + return QString(); +} diff --git a/pool/shard001/C++/0022826_common.cpp b/pool/shard001/C++/0022826_common.cpp new file mode 100644 index 0000000000000000000000000000000000000000..903804b769b2f544144747adc5879030ae686ffe --- /dev/null +++ b/pool/shard001/C++/0022826_common.cpp @@ -0,0 +1,65 @@ +#include "common.hpp" +#include + +namespace isis::util +{ + +std::string getLastSystemError() +{ +#ifdef WIN32 + std::string ret; + LPTSTR s; + DWORD err = GetLastError(); + + if( ::FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, + NULL, + err, + 0, + ( LPTSTR )&s, + 0, + NULL ) == 0 ) { /* failed */ + ret = std::string( "Unknown error " ) + std::to_string( err ); + } else { /* success */ + ret = s; + ret.resize( ret.rfind( '\r' ) ); //FormatMessage appends a newline + ::LocalFree( s ); + } + + return ret; +#else + return strerror( errno ); +#endif +} +///in a list of paths shorten those paths until they are equal +std::filesystem::path getRootPath(std::list< std::filesystem::path > sources,bool sorted) +{ + //remove all entries of the list that are already equal + if(!sorted) + sources.sort(); + sources.erase( std::unique( sources.begin(), sources.end() ), sources.end() ); + + // that's too short + if( sources.empty() ) { + LOG( Runtime, error ) << "Failed to get root path (list is empty)"; + } else if( sources.size() == 1 ) // ok, we got one unique path, return that + return *sources.begin(); + else { // no unique path yet, try to shorten + bool abort=true; + for( std::filesystem::path & ref : sources ){ + if(ref.has_parent_path()){//remove last element + ref=ref.parent_path(); + abort=false; //if at least one path can be shortened + } + } + + if(!abort){//if shortening was possible, check again for unique + return getRootPath( sources,true ); + } else { // no more shortening possible, abort + LOG( Runtime, error ) << "Failed to get root path for " << sources; + } + } + return std::filesystem::path(); +} + + +} diff --git a/pool/shard001/C++/0022831_wifitester.cpp b/pool/shard001/C++/0022831_wifitester.cpp new file mode 100644 index 0000000000000000000000000000000000000000..04b913da3e5b22bc9fa847b0dca4be94e7c532f2 --- /dev/null +++ b/pool/shard001/C++/0022831_wifitester.cpp @@ -0,0 +1,58 @@ +/** + ****************************************************************************** + * @file wifitester.cpp + * @authors David Middlecamp, Matthew McGowan + * @version V1.0.0 + ****************************************************************************** + Copyright (c) 2015 Particle Industries, 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 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 . + ****************************************************************************** + */ + +#include "application.h" +#include "spark_wiring_wifitester.h" + +SYSTEM_MODE(MANUAL); + +#define USE_SERIAL1 1 + +#ifndef USE_SERIAL1 +#define USE_SERIAL1 0 +#endif + +WiFiTester tester; + +void setup() +{ + Serial.begin(9600); +#if USE_SERIAL1 + Serial1.begin(9600); +#endif + tester.setup(USE_SERIAL1); +} + +void loop() +{ + int c = -1; + if (tester.serialAvailable()) { + c = tester.serialRead(); + char s[2]; + s[0] = c; + s[1] = 0; + tester.serialPrint(s); + } + tester.loop(c); +} + diff --git a/pool/shard001/C++/0022833_TextBreakIteratorQt.cpp b/pool/shard001/C++/0022833_TextBreakIteratorQt.cpp new file mode 100644 index 0000000000000000000000000000000000000000..dda443f20b237dab2ef7c79b038cbdaf2f8162fe --- /dev/null +++ b/pool/shard001/C++/0022833_TextBreakIteratorQt.cpp @@ -0,0 +1,139 @@ +/* + * Copyright (C) 2006 Lars Knoll + * + * 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" +#include "TextBreakIterator.h" + +#include +#include + +// #define DEBUG_TEXT_ITERATORS +#ifdef DEBUG_TEXT_ITERATORS +#define DEBUG qDebug +#else +#define DEBUG if (1) {} else qDebug +#endif + +namespace WebCore { + + static unsigned char buffer[1024]; + + class TextBreakIterator : public QTextBoundaryFinder { + public: + TextBreakIterator(QTextBoundaryFinder::BoundaryType type, const UChar* string, int length) + : QTextBoundaryFinder(type, (const QChar*)string, length, buffer, sizeof(buffer)) + , length(length) + , string(string) {} + TextBreakIterator() + : QTextBoundaryFinder() + , length(0) + , string(0) {} + + int length; + const UChar* string; + }; + + TextBreakIterator* setUpIterator(TextBreakIterator& iterator, QTextBoundaryFinder::BoundaryType type, const UChar* string, int length) + { + if (!string || !length) + return 0; + + if (iterator.isValid() && type == iterator.type() && length == iterator.length + && memcmp(string, iterator.string, length) == 0) { + iterator.toStart(); + return &iterator; + } + + iterator = TextBreakIterator(type, string, length); + + return &iterator; + } + + TextBreakIterator* wordBreakIterator(const UChar* string, int length) + { + static TextBreakIterator staticWordBreakIterator; + return setUpIterator(staticWordBreakIterator, QTextBoundaryFinder::Word, string, length); + } + + TextBreakIterator* characterBreakIterator(const UChar* string, int length) + { + static TextBreakIterator staticCharacterBreakIterator; + return setUpIterator(staticCharacterBreakIterator, QTextBoundaryFinder::Grapheme, string, length); + } + + TextBreakIterator* cursorMovementIterator(const UChar* string, int length) + { + return characterBreakIterator(string, length); + } + + TextBreakIterator* lineBreakIterator(const UChar* string, int length) + { + static TextBreakIterator staticLineBreakIterator; + return setUpIterator(staticLineBreakIterator, QTextBoundaryFinder::Line, string, length); + } + + TextBreakIterator* sentenceBreakIterator(const UChar* string, int length) + { + static TextBreakIterator staticSentenceBreakIterator; + return setUpIterator(staticSentenceBreakIterator, QTextBoundaryFinder::Sentence, string, length); + + } + + int textBreakFirst(TextBreakIterator* bi) + { + bi->toStart(); + DEBUG() << "textBreakFirst" << bi->position(); + return bi->position(); + } + + int textBreakNext(TextBreakIterator* bi) + { + int pos = bi->toNextBoundary(); + DEBUG() << "textBreakNext" << pos; + return pos; + } + + int textBreakPreceding(TextBreakIterator* bi, int pos) + { + bi->setPosition(pos); + int newpos = bi->toPreviousBoundary(); + DEBUG() << "textBreakPreceding" << pos << newpos; + return newpos; + } + + int textBreakFollowing(TextBreakIterator* bi, int pos) + { + bi->setPosition(pos); + int newpos = bi->toNextBoundary(); + DEBUG() << "textBreakFollowing" << pos << newpos; + return newpos; + } + + int textBreakCurrent(TextBreakIterator* bi) + { + return bi->position(); + } + + bool isTextBreak(TextBreakIterator*, int) + { + return true; + } + +} diff --git a/pool/shard001/C++/0022835_external_protocol_dialog_delegate.cc b/pool/shard001/C++/0022835_external_protocol_dialog_delegate.cc new file mode 100644 index 0000000000000000000000000000000000000000..5fa4e3845093a5b76ce9d579243563d421a5f9e5 --- /dev/null +++ b/pool/shard001/C++/0022835_external_protocol_dialog_delegate.cc @@ -0,0 +1,78 @@ +// 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/ui/external_protocol_dialog_delegate.h" + +#include + +#include "base/threading/thread.h" +#include "base/threading/thread_restrictions.h" +#include "base/utf_string_conversions.h" +#include "chrome/browser/external_protocol/external_protocol_handler.h" +#include "grit/chromium_strings.h" +#include "grit/generated_resources.h" +#include "ui/base/l10n/l10n_util.h" +#include "ui/base/text/text_elider.h" + +ExternalProtocolDialogDelegate::ExternalProtocolDialogDelegate(const GURL& url) + : ProtocolDialogDelegate(url) { +} + +ExternalProtocolDialogDelegate::~ExternalProtocolDialogDelegate() { +} + +string16 ExternalProtocolDialogDelegate::GetMessageText() const { + const int kMaxUrlWithoutSchemeSize = 256; + const int kMaxCommandSize = 256; + // TODO(calamity): Look up the command in ExternalProtocolHandler and pass it + // into the constructor. Will require simultaneous change of + // ExternalProtocolHandler::RunExternalProtocolDialog across all platforms. + string16 command = + UTF8ToUTF16(ShellIntegration::GetApplicationForProtocol(url())); + string16 elided_url_without_scheme; + string16 elided_command; + ui::ElideString(ASCIIToUTF16(url().possibly_invalid_spec()), + kMaxUrlWithoutSchemeSize, &elided_url_without_scheme); + ui::ElideString(command, kMaxCommandSize, &elided_command); + + string16 message_text = l10n_util::GetStringFUTF16( + IDS_EXTERNAL_PROTOCOL_INFORMATION, + ASCIIToUTF16(url().scheme() + ":"), + elided_url_without_scheme) + ASCIIToUTF16("\n\n"); + + message_text += l10n_util::GetStringFUTF16( + IDS_EXTERNAL_PROTOCOL_APPLICATION_TO_LAUNCH, + elided_command) + ASCIIToUTF16("\n\n"); + + message_text += l10n_util::GetStringUTF16(IDS_EXTERNAL_PROTOCOL_WARNING); + return message_text; +} + +string16 ExternalProtocolDialogDelegate::GetCheckboxText() const { + return l10n_util::GetStringUTF16(IDS_EXTERNAL_PROTOCOL_CHECKBOX_TEXT); +} + +string16 ExternalProtocolDialogDelegate::GetTitleText() const { + return l10n_util::GetStringUTF16(IDS_EXTERNAL_PROTOCOL_TITLE); +} + +void ExternalProtocolDialogDelegate::DoAccept( + const GURL& url, + bool dont_block) const { + if (dont_block) { + ExternalProtocolHandler::SetBlockState( + url.scheme(), ExternalProtocolHandler::DONT_BLOCK); + } + + ExternalProtocolHandler::LaunchUrlWithoutSecurityCheck(url); +} + +void ExternalProtocolDialogDelegate::DoCancel( + const GURL& url, + bool dont_block) const { + if (dont_block) { + ExternalProtocolHandler::SetBlockState( + url.scheme(), ExternalProtocolHandler::BLOCK); + } +} diff --git a/pool/shard001/C++/0022836_binding.cpp b/pool/shard001/C++/0022836_binding.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6d71ae81aef2074f205c38b99d20f9c217ffac9e --- /dev/null +++ b/pool/shard001/C++/0022836_binding.cpp @@ -0,0 +1,121 @@ +/* Copyright 2007-2015 QReal Research Group + * + * 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 "generatorBase/simpleGenerators/binding.h" + +using namespace generatorBase::simple; +using namespace qReal; + +Binding::ConverterInterface::~ConverterInterface() +{ +} + +Binding::MultiConverterInterface::~MultiConverterInterface() +{ +} + +QString Binding::EmptyConverter::convert(const QString &data) const +{ + return data; +} + +Binding *Binding::createStatic(const QString &label, const QString &value) +{ + return new Binding(label, value, false); +} + +Binding *Binding::createStaticConverting(const QString &label, const QString &value + , const ConverterInterface *converter) +{ + return new Binding(label, value, false, converter); +} + +Binding *Binding::createDirect(const QString &label, const QString &property) +{ + return new Binding(label, property, true); +} + +Binding *Binding::createConverting(const QString &label, const QString &property + , const ConverterInterface *converter) +{ + return new Binding(label, property, true, converter); +} + +Binding *Binding::createMultiTarget(const QString &label, const QString &property + , const MultiConverterInterface *converter) +{ + return new Binding(label, property, converter); +} + +Binding::Binding(const QString &label, const QString &propertyOrValue, bool takeFromRepo) + : mLabel(label) + , mProperty(takeFromRepo ? propertyOrValue : "") + , mValue(takeFromRepo ? "" : propertyOrValue) + , mConverter(new EmptyConverter) + , mMultiConverter(nullptr) +{ +} + +Binding::Binding(const QString &label, const QString &propertyOrValue, bool takeFromRepo + , const ConverterInterface *converter) + : mLabel(label) + , mProperty(takeFromRepo ? propertyOrValue : "") + , mValue(takeFromRepo ? "" : propertyOrValue) + , mConverter(converter) + , mMultiConverter(nullptr) +{ +} + +Binding::Binding(const QString &label, const QString &property + , const MultiConverterInterface *converter) + : mLabel(label) + , mProperty(property) + , mConverter(nullptr) + , mMultiConverter(converter) +{ +} + +Binding::~Binding() +{ + delete mConverter; +} + +void Binding::apply(const qrRepo::RepoApi &repo + , const Id &id, QString &data) +{ + const QString property = mProperty.isEmpty() + ? mValue + : mProperty == "name" + ? repo.name(id) + : repo.property(id, mProperty).toString(); + + if (mConverter) { + data.replace(mLabel, mConverter->convert(property)); + } else { + applyMulti(property, data); + } +} + +void Binding::applyMulti(const QString &property, QString &data) +{ + QString result; + const QStringList parts = mMultiConverter->convert(property); + foreach (const QString &part, parts) { + QString dataCopy = data; + dataCopy.replace(mLabel, part); + result += dataCopy; + } + + data = result; +} diff --git a/pool/shard001/C++/0022843_ingame_menu_state.cpp b/pool/shard001/C++/0022843_ingame_menu_state.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f1a785b786f75ada8ef0e40cedf862993f24e042 --- /dev/null +++ b/pool/shard001/C++/0022843_ingame_menu_state.cpp @@ -0,0 +1,137 @@ +#include "ingame_menu_state.hpp" +#include "../UI/ui_manager.hpp" +#include "../events/state_events.hpp" +#include +#include +#include +IngameMenuState::IngameMenuState(Urho3D::Context *context) : GameState(context) { + + Urho3D::ResourceCache *cache = GetSubsystem(); + ui_factory = + UIManager(context_, cache->GetResource("Fonts/Anonymous Pro.ttf", 20), + Urho3D::Color(), cache->GetResource("UI/DefaultStyle.xml"), + GetSubsystem()->GetRoot()); + create_ui(); +} + +IngameMenuState::~IngameMenuState() { + + for (auto ui_element : ui_elements) { + std::cout << "lol" << std::endl; + ui_element.second->RemoveAllChildren(); + ui_element.second->Remove(); + } + + ui_elements.clear(); +} + +void IngameMenuState::Start() { + + GetSubsystem()->SetMouseVisible(true); + GetSubsystem()->SetMouseGrabbed(false); + + Urho3D::UIElement *root = GetSubsystem()->GetRoot(); + + root->AddChild(ui_elements["Buttons"]); + + subscribe_to_events(); +} + +void IngameMenuState::Stop() { + + for (auto ui_element : ui_elements) { + ui_element.second->RemoveAllChildren(); + ui_element.second->Remove(); + } +} + +void IngameMenuState::subscribe_to_events() { +} + +void IngameMenuState::unsubscribe_events() { + UnsubscribeFromAllEvents(); +} +void IngameMenuState::create_ui() { + + int main_button_width = 600; + int main_button_height = 40; + + ui_elements["Buttons"] = ui_factory.create_collum(75); + ui_elements["Buttons"]->SetAlignment(Urho3D::HA_CENTER, Urho3D::VA_CENTER); + ui_elements["Buttons"]->SetDefaultStyle(ui_factory.m_std_style); + + Urho3D::UIElement *start_buttons_container = ui_factory.create_collum(30); + ui_elements["Buttons"]->AddChild(start_buttons_container); + { + start_buttons_container->AddChild( + ui_factory.create_button("Resume", main_button_width, main_button_height)); + start_buttons_container->AddChild( + ui_factory.create_button("Save", main_button_width, main_button_height)); + start_buttons_container->AddChild( + ui_factory.create_button("Load", main_button_width, main_button_height)); + } + ui_elements["Buttons"]->AddChild( + ui_factory.create_button("Options", main_button_width, main_button_height)); + ui_elements["Buttons"]->AddChild( + ui_factory.create_button("Exit", main_button_width, main_button_height)); + ui_elements["Buttons"]->AddChild( + ui_factory.create_button("Exit to Desktop", main_button_width, main_button_height)); +} + +void IngameMenuState::HandleOnHoverBegin(Urho3D::StringHash eventType, + Urho3D::VariantMap &event_data) { + Urho3D::UIElement *element = static_cast(event_data["Element"].GetPtr()); + std::cout << element->GetName().CString() << std::endl; +} + +void IngameMenuState::HandleKeyDown(Urho3D::StringHash eventType, Urho3D::VariantMap &event_data) { + int key = event_data[Urho3D::KeyDown::P_KEY].GetInt(); + + Urho3D::VariantMap v; + switch (key) { + case Urho3D::KEY_ESC: + sendStateChangeEvent(POP); + break; + default: + std::cout << "key not set" << std::endl; + } +} + +void IngameMenuState::HandleUpdate(Urho3D::StringHash eventType, Urho3D::VariantMap &event_data) { +} + +void IngameMenuState::HandleControlClicked(Urho3D::StringHash eventType, + Urho3D::VariantMap &event_data) { + // Query the clicked UI element. + Urho3D::UIElement *clicked = + static_cast(event_data[Urho3D::UIMouseClick::P_ELEMENT].GetPtr()); + if (clicked) { + Urho3D::String clicked_name = clicked->GetName(); + if (clicked_name == "Resume") { // check if the quit button was clicked + sendStateChangeEvent(POP); + } + if (clicked_name == "Options") { + sendStateChangeEvent(PUSH, OPTIONS); + } + if (clicked_name == "Exit") { + sendStateChangeEvent(EXIT); + } + if (clicked_name == "Exit to Desktop") { + sendStateChangeEvent(EXIT_TO_DESKTOP); + } + if (clicked_name == "Load") { + std::cout << "NOT IMPLEMENTED: Load Button" << std::endl; + } + if (clicked_name == "Save") { + std::cout << "NOT IMPLEMENTED: Load Button" << std::endl; + } + } +} + +const Urho3D::TypeInfo *IngameMenuState::GetTypeInfo() const { + return GetTypeInfoStatic(); +} + +const Urho3D::String &IngameMenuState::GetTypeName() const { + return GetTypeInfo()->GetTypeName(); +} diff --git a/pool/shard001/C++/0022844_CWE401_Memory_Leak__new_array_twointsStruct_14.cpp b/pool/shard001/C++/0022844_CWE401_Memory_Leak__new_array_twointsStruct_14.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fceec6a5b3cdbbb690af44135e53c6ee1c3b282a --- /dev/null +++ b/pool/shard001/C++/0022844_CWE401_Memory_Leak__new_array_twointsStruct_14.cpp @@ -0,0 +1,186 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE401_Memory_Leak__new_array_twointsStruct_14.cpp +Label Definition File: CWE401_Memory_Leak__new_array.label.xml +Template File: sources-sinks-14.tmpl.cpp +*/ +/* + * @description + * CWE: 401 Memory Leak + * BadSource: Allocate data using new[] + * GoodSource: Point data to a stack buffer + * Sinks: + * GoodSink: call delete[] on data + * BadSink : no deallocation of data + * Flow Variant: 14 Control flow: if(globalFive==5) and if(globalFive!=5) + * */ + +#include "std_testcase.h" + +#ifndef _WIN32 +#include +#endif + +namespace CWE401_Memory_Leak__new_array_twointsStruct_14 +{ + +#ifndef OMITBAD + +void bad() +{ + twoIntsStruct * data; + data = NULL; + if(globalFive==5) + { + /* POTENTIAL FLAW: Allocate memory on the heap */ + data = new twoIntsStruct[100]; + /* Initialize and make use of data */ + data[0].intOne = 0; + data[0].intTwo = 0; + printStructLine(&data[0]); + } + if(globalFive==5) + { + /* POTENTIAL FLAW: No deallocation */ + ; /* empty statement needed for some flow variants */ + } +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodB2G1() - use badsource and goodsink by changing the second globalFive==5 to globalFive!=5 */ +static void goodB2G1() +{ + twoIntsStruct * data; + data = NULL; + if(globalFive==5) + { + /* POTENTIAL FLAW: Allocate memory on the heap */ + data = new twoIntsStruct[100]; + /* Initialize and make use of data */ + data[0].intOne = 0; + data[0].intTwo = 0; + printStructLine(&data[0]); + } + if(globalFive!=5) + { + /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ + printLine("Benign, fixed string"); + } + else + { + /* FIX: Deallocate memory */ + delete[] data; + } +} + +/* goodB2G2() - use badsource and goodsink by reversing the blocks in the second if */ +static void goodB2G2() +{ + twoIntsStruct * data; + data = NULL; + if(globalFive==5) + { + /* POTENTIAL FLAW: Allocate memory on the heap */ + data = new twoIntsStruct[100]; + /* Initialize and make use of data */ + data[0].intOne = 0; + data[0].intTwo = 0; + printStructLine(&data[0]); + } + if(globalFive==5) + { + /* FIX: Deallocate memory */ + delete[] data; + } +} + +/* goodG2B1() - use goodsource and badsink by changing the first globalFive==5 to globalFive!=5 */ +static void goodG2B1() +{ + twoIntsStruct * data; + data = NULL; + if(globalFive!=5) + { + /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ + printLine("Benign, fixed string"); + } + else + { + /* FIX: Use memory allocated on the stack */ + twoIntsStruct dataGoodBuffer[100]; + data = dataGoodBuffer; + /* Initialize and make use of data */ + data[0].intOne = 0; + data[0].intTwo = 0; + printStructLine(&data[0]); + } + if(globalFive==5) + { + /* POTENTIAL FLAW: No deallocation */ + ; /* empty statement needed for some flow variants */ + } +} + +/* goodG2B2() - use goodsource and badsink by reversing the blocks in the first if */ +static void goodG2B2() +{ + twoIntsStruct * data; + data = NULL; + if(globalFive==5) + { + /* FIX: Use memory allocated on the stack */ + twoIntsStruct dataGoodBuffer[100]; + data = dataGoodBuffer; + /* Initialize and make use of data */ + data[0].intOne = 0; + data[0].intTwo = 0; + printStructLine(&data[0]); + } + if(globalFive==5) + { + /* POTENTIAL FLAW: No deallocation */ + ; /* empty statement needed for some flow variants */ + } +} + +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 CWE401_Memory_Leak__new_array_twointsStruct_14; /* 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/shard001/C++/0022857_caimagehueselector.cpp b/pool/shard001/C++/0022857_caimagehueselector.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5e0a461839f3d9ca61ab0c86a49e55b3258f9dea --- /dev/null +++ b/pool/shard001/C++/0022857_caimagehueselector.cpp @@ -0,0 +1,134 @@ +#include "caimagehueselector.h" +#include "caimagemanipulation.h" +#include "caresources.h" +#include "catrophy.h" + + +/** Constructor for an empty image hue selector. + \param direction Vertical selector? (Use Up/Down arrows to control) +*/ +CAImageHueSelector::CAImageHueSelector( Direction direction ) + : CAImageView(),hueImage() { + if( CA_APP->debug ) std::cout << "CAImageHueSelector() begin" << std::endl; + + this->direction = direction; + hue = 0; + + if( CA_APP->debug ) std::cout << "CAImageHueSelector() end" << std::endl; +} + + + +/** Constructor for an image hue selector with an image. + \param upperText Text above image + \param lowerText Text under image + \param image The image itself + \param type Selector type (Image, Selector, HueSelector) + \param direction Vertical selector? (Use Up/Down arrows to control) +*/ +CAImageHueSelector::CAImageHueSelector( const std::string upperText, + const std::string lowerText, + CL_Texture image, + bool autoResize, + Direction direction ) + : CAImageView( upperText, + lowerText, + image, + autoResize ) { + if( CA_APP->debug ) std::cout << "CAImageHueSelector() begin 2" << std::endl; + + this->direction = direction; + CL_PixelBuffer result = CAImageManipulation::changeHSV( image.get_pixeldata(), 0, 0, 0 ); + hueImage = CL_Image(*CA_APP->graphicContext,result,CL_Rect(0,0,result.get_width(),result.get_height())); + hue = 0; + setImageSize( image.get_width(), image.get_height() ); + + if( CA_APP->debug ) std::cout << "CAImageHueSelector() end 2" << std::endl; +} + +/** Destructor. +*/ +CAImageHueSelector::~CAImageHueSelector() { +} + +/** Sets the size of the image view (without top/bottom button). + Bigger images get cropped (top left part shown). + \param w Width of image view + \param h Height of image view +*/ +void +CAImageHueSelector::setImageSize( int w, int h ) { + CAImageView::setImageSize( w,h ); + + if( direction==Horizontal ) { + width += 2*CA_RES->gui_arrow_l.get_width(); + } else { + height += 2*CA_RES->gui_arrow_t.get_height(); + } + + right = left + width; + bottom = top + height; +} + +/** Changes the images hue (only for hue selectors with one image). + The old image gets deleted. +*/ +void +CAImageHueSelector::changeImageHue( bool forward ) { + if( !image.image.is_null() ) { + // TODO : clean the constants + int amount = 5 * (forward ? 1 : -1); + hue += amount; + if( hue > 360 ) hue -= 360; + if( hue < 0 ) hue += 360; + + CL_PixelBuffer result = CAImageManipulation::changeHSV( image.image.get_pixeldata(), hue, 0, 0 ); + hueImage = CL_Image(*CA_APP->graphicContext,result,CL_Rect(0,0,result.get_width(),result.get_height())); + } +} + +/** Displays the image view with its current image/ texts. +*/ +void +CAImageHueSelector::display( bool active ) +{ + //CAImageView::display( active ); + + CL_Rect crAll( 0, 0, CA_APP->width, CA_APP->height ); + CL_Rect crImage( left, top, right, bottom ); + CA_APP->graphicContext->set_cliprect( crImage ); + + CL_Draw::fill( *CA_APP->graphicContext, CL_Rect(left, top, right, bottom), CL_Colorf(0, 0, 0, 64) ); + + displayTextButtons( active ); + + if (!hueImage.is_null()) + { + // center the image + const int leftPos = left + (width - hueImage.get_width()) /2; + const int topPos = top + (height - hueImage.get_height())/2; + hueImage.draw( *CA_APP->graphicContext,leftPos, topPos); + } + + displayArrows( active ); + + CA_APP->graphicContext->set_cliprect( crAll ); +} + +/** Handles key events for this view / selector. +*/ +void +CAImageHueSelector::handleKey (const CL_InputEvent &key) +{ + if( (key.id==CL_KEY_LEFT && direction==Horizontal) || (key.id==CL_KEY_DOWN && direction==Vertical) || key.id==CL_KEY_PRIOR) + { + changeImageHue( false ); + } + + if( (key.id==CL_KEY_RIGHT && direction==Horizontal) || (key.id==CL_KEY_UP && direction==Vertical) || key.id==CL_KEY_NEXT) + { + changeImageHue( true ); + } +} + +// EOF diff --git a/pool/shard001/C++/0022869_LPC.cpp b/pool/shard001/C++/0022869_LPC.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8599d3d97d14d218d3634dda7c41740e66fc64a1 --- /dev/null +++ b/pool/shard001/C++/0022869_LPC.cpp @@ -0,0 +1,138 @@ +/* +** Copyright (C) 2000 George Tzanetakis +** +** 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. +*/ + + +/** + \class LPC: + \brief Linear Prediction Coefficients (LPC) + + Linear Prediction Coefficients (LPC). Features commonly used +in Speech Recognition research. +*/ + + +#include "LPC.h" +#include + +LPC::LPC( unsigned int inSize ) +{ + inSize_ = inSize; + outSize_ = DEFAULT_ORDER+1; + order_ = DEFAULT_ORDER; + autocorr_ = NULL; + hopSize_ = inSize_ / 2; + init(); +} + +LPC::LPC(Signal* src,unsigned int order) +{ + inSize_ = src->winSize(); + hopSize_ = src->hopSize(); + outSize_ = order+1; + order_ = order; + autocorr_ = NULL; + init(); +} + +LPC::~LPC() +{ + delete autocorr_; +} + +void +LPC::init() +{ + unsigned int i; + + // Prepare feature names + featSize_ = outSize_; + for (i=0; i < featSize_; i++) + featNames_.push_back("LPC"); + rmat_.create(order_ - 1, order_ - 1); + temp_.create(order_ - 1, order_ - 1); + corr_.create(inSize_); + autocorr_ = new AutoCorrelation(inSize_); + Zs_.create(order_-1); +} + +float +LPC::pitch() +{ + return pitch_; +} + +float +LPC::power() +{ + return power_; +} + + +void +LPC::predict(fvec& data, fvec& coeffs) +{ + unsigned int i,j; + float power = 0.0; + float error, tmp; + for (i=0; i< order_-1; i++) + { + Zs_(i) = data(order_-1-i-1); + } + for (i=order_-1; i<= hopSize_ + order_-1; i++) + { + tmp = 0.0; + for (j=0; j< order_-1; j++) tmp += Zs_(j) * coeffs(j); + for (j=order_-1-1; j>0; j--) Zs_(j) = Zs_(j-1); + Zs_(0) = data(i); + error = data(i) - tmp; + power += error * error; + } + power_ = sqrt(power) / hopSize_; +} + + + +void +LPC::process(fvec& in, fvec& out) +{ +// fprintf( stderr, "%i %i %i %i\n", in.size(), inSize_, out.size(), outSize_ ); + assert((in.size() == inSize_) && (out.size() == outSize_)); + unsigned int i,j; + autocorr_->process(in, corr_); + pitch_ = autocorr_->pitch(); + for (i=1; iint_id_; + // The ext_id_'s delete themselves when the array of + // COLLECTION::ENTRYs goes away. + } +} + +ACE_Token_Manager * +ACE_Token_Manager::instance (void) +{ + ACE_TRACE ("ACE_Token_Manager::instance"); + + // This first check is to avoid acquiring the mutex in the common + // case. Double-Check pattern rules. + if (token_manager_ == 0) + { +#if defined (ACE_MT_SAFE) && (ACE_MT_SAFE != 0) + ACE_TOKEN_CONST::MUTEX *lock = + ACE_Managed_Object::get_preallocated_object + (ACE_Object_Manager::ACE_TOKEN_MANAGER_CREATION_LOCK); + ACE_GUARD_RETURN (ACE_TOKEN_CONST::MUTEX, ace_mon, *lock, 0); +#endif /* ACE_MT_SAFE */ + + if (token_manager_ == 0) + { + ACE_NEW_RETURN (token_manager_, + ACE_Token_Manager, + 0); + // Register for destruction with ACE_Object_Manager. + ACE_Object_Manager::at_exit (token_manager_, 0, typeid (token_manager_).name ()); + } + } + + return token_manager_; +} + +void +ACE_Token_Manager::get_token (ACE_Token_Proxy *proxy, + const ACE_TCHAR *token_name) +{ + ACE_TRACE ("ACE_Token_Manager::get_token"); + // Hmm. I think this makes sense. We perform our own locking here + // (see safe_acquire.) We have to make sure that only one thread + // uses the collection at a time. + + ACE_GUARD (ACE_TOKEN_CONST::MUTEX, ace_mon, this->lock_); + + TOKEN_NAME name (token_name); + + if (collection_.find (name, proxy->token_) == -1) + // We did not find one in the collection. + { + // Make one. + proxy->token_ = proxy->create_token (token_name); + + // Put it in the collection. + if (collection_.bind (name, proxy->token_) == -1) + { + delete proxy->token_; + proxy->token_ = 0; + } + } + + if (proxy->token_ != 0) + proxy->token_->inc_reference (); + + // We may be returning proxy->token_ == 0 if new failed, caller must + // check. +} + +// 0. check_deadlock (TOKEN) +// 1. if TOKEN->visited (), return 0. +// 2. mark TOKEN visited. +// 3. get ALL_OWNERS +// 4. if CLIENT in ALL_OWNERS, return *DEADLOCK*. +// 5. for each OWNER in ALL_OWNERS, +// 6. if OWNER is not waiting for a NEW_TOKEN, continue. +// 7. else, if check_deadlock (NEW_TOKEN) == 1, return *DEADLOCK* +// 8. return 0. + +int +ACE_Token_Manager::check_deadlock (ACE_Token_Proxy *proxy) +{ + ACE_TRACE ("ACE_Token_Manager::check_deadlock"); + + // Start the recursive deadlock detection algorithm. + int result = this->check_deadlock (proxy->token_, proxy); + + // Whether or not we detect deadlock, we have to unmark all tokens + // for the next time. + COLLECTION::ITERATOR iterator (collection_); + for (COLLECTION::ENTRY *temp = 0; + iterator.next (temp) != 0; + iterator.advance ()) + temp->int_id_->visit (0); + + return result; +} + +int +ACE_Token_Manager::check_deadlock (ACE_Tokens *token, ACE_Token_Proxy *proxy) +{ + ACE_TRACE ("ACE_Token_Manager::check_deadlock"); + + if (token->visited ()) + return 0; + + token->visit (1); + + ACE_Tokens::OWNER_STACK owners; + + int is_owner = token->owners (owners, proxy->client_id ()); + + switch (is_owner) + { + case -1: + // Error. + return -1; + case 1: + // The caller is an owner, so we have a deadlock situation. + if (debug_) + { + ACELIB_DEBUG ((LM_DEBUG, ACE_TEXT ("(%t) Deadlock detected.\n"))); + ACELIB_DEBUG ((LM_DEBUG, ACE_TEXT ("%s owns %s and is waiting for %s.\n"), + proxy->client_id (), + token->name (), + proxy->token_->name ())); + } + + return 1; + case 0: + default: + // Recurse on each owner. + while (!owners.is_empty ()) + { + ACE_TPQ_Entry *e; + owners.pop (e); + // If the owner is waiting on another token, recurse. + ACE_Tokens *twf = this->token_waiting_for (e->client_id ()); + if ((twf != 0) && + (this->check_deadlock (twf, proxy) == 1)) + { + if (debug_) + { + ACELIB_DEBUG ((LM_DEBUG, + ACE_TEXT ("%s owns %s and is waiting for %s.\n"), + e->client_id (), + token->name (), + twf->name ())); + } + return 1; + } + // else, check the next owner. + } + + // We've checked all the owners and found no deadlock. + return 0; + } +} + + +ACE_Tokens * +ACE_Token_Manager::token_waiting_for (const ACE_TCHAR *client_id) +{ + COLLECTION::ITERATOR iterator (collection_); + for (COLLECTION::ENTRY *temp = 0; + iterator.next (temp) != 0; + iterator.advance ()) + { + if (temp->int_id_->is_waiting_for (client_id)) + return temp->int_id_; + } + + // nothing was found, return NULL. + return 0; +} + +// Notify the token manager that a token is has been released. If +// as a result, there is no owner of the token, the token is +// deleted. +void +ACE_Token_Manager::release_token (ACE_Tokens *&token) +{ + ACE_TRACE ("ACE_Token_Manager::release_token"); + // again, let's perform our own locking here. + + ACE_GUARD (ACE_TOKEN_CONST::MUTEX, ace_mon, this->lock_); + + if (token->dec_reference () == 0) + { + // No one has the token, so we can delete it and remove it from + // our collection. First, let's get it from the collection. + TOKEN_NAME token_name (token->name ()); + + ACE_Tokens *temp; + + if (collection_.unbind (token_name, temp) == -1) + // we did not find one in the collection + { + errno = ENOENT; + ACELIB_ERROR ((LM_ERROR, ACE_TEXT ("Token Manager could not release %s:%d\n"), + token->name (), token->type ())); + // @@ bad + } + else + // we found it + { + // sanity pointer comparison. The token referenced by the + // proxy better be the one we found in the list. + ACE_ASSERT (token == temp); + delete token; // or delete temp + // we set their token to zero. if the calling proxy is + // still going to be used, it had better check it's token + // value before calling a method on it! + token = 0; + } + } + // else + // someone is still interested in the token, so keep it around. +} + +void +ACE_Token_Manager::dump (void) const +{ +#if defined (ACE_HAS_DUMP) + ACE_TRACE ("ACE_Token_Manager::dump"); + ACELIB_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this)); + ACELIB_DEBUG ((LM_DEBUG, ACE_TEXT ("ACE_Token_Manager::dump:\n"))); + ACELIB_DEBUG ((LM_DEBUG, ACE_TEXT ("lock_\n"))); + lock_.dump (); + ACELIB_DEBUG ((LM_DEBUG, ACE_TEXT ("collection_\n"))); + collection_.dump (); + ACELIB_DEBUG ((LM_DEBUG, ACE_END_DUMP)); +#endif /* ACE_HAS_DUMP */ +} + +ACE_END_VERSIONED_NAMESPACE_DECL + +#endif /* ACE_HAS_TOKENS_LIBRARY */ diff --git a/pool/shard001/C++/0022883_string_serialization.cc b/pool/shard001/C++/0022883_string_serialization.cc new file mode 100644 index 0000000000000000000000000000000000000000..6b9f741457c4bac34f4222ba1cfccf01d3cee755 --- /dev/null +++ b/pool/shard001/C++/0022883_string_serialization.cc @@ -0,0 +1,46 @@ +// 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/public/cpp/bindings/lib/string_serialization.h" + +#include +#include + +namespace mojo { + +size_t GetSerializedSize_(const String& input, + internal::SerializationContext* context) { + if (!input) + return 0; + return internal::Align(sizeof(internal::String_Data) + input.size()); +} + +void Serialize_(const String& input, + internal::Buffer* buf, + internal::String_Data** output, + internal::SerializationContext* context) { + if (input) { + internal::String_Data* result = + internal::String_Data::New(input.size(), buf); + if (result) + memcpy(result->storage(), input.data(), input.size()); + *output = result; + } else { + *output = nullptr; + } +} + +bool Deserialize_(internal::String_Data* input, + String* output, + internal::SerializationContext* context) { + if (input) { + String result(input->storage(), input->size()); + result.Swap(output); + } else { + *output = nullptr; + } + return true; +} + +} // namespace mojo diff --git a/pool/shard001/C++/0022891_infobar_delegate.cc b/pool/shard001/C++/0022891_infobar_delegate.cc new file mode 100644 index 0000000000000000000000000000000000000000..7039c9e7cb5d70b717de3d9e0d81931594671c43 --- /dev/null +++ b/pool/shard001/C++/0022891_infobar_delegate.cc @@ -0,0 +1,127 @@ +// 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/infobars/infobar_delegate.h" + +#include "base/logging.h" +#include "build/build_config.h" +#include "chrome/browser/infobars/infobar.h" +#include "chrome/browser/infobars/infobar_service.h" +#include "content/public/browser/navigation_controller.h" +#include "content/public/browser/navigation_details.h" +#include "content/public/browser/navigation_entry.h" +#include "content/public/browser/web_contents.h" +#include "ui/base/resource/resource_bundle.h" + +using content::NavigationEntry; + +// InfoBarDelegate ------------------------------------------------------------ + +const int InfoBarDelegate::kNoIconID = 0; + +InfoBarDelegate::~InfoBarDelegate() { +} + +InfoBarDelegate::InfoBarAutomationType + InfoBarDelegate::GetInfoBarAutomationType() const { + return UNKNOWN_INFOBAR; +} + +bool InfoBarDelegate::EqualsDelegate(InfoBarDelegate* delegate) const { + return false; +} + +bool InfoBarDelegate::ShouldExpire( + const content::LoadCommittedDetails& details) const { + if (!details.is_navigation_to_different_page()) + return false; + + return ShouldExpireInternal(details); +} + +void InfoBarDelegate::InfoBarDismissed() { +} + +int InfoBarDelegate::GetIconID() const { + return kNoIconID; +} + +InfoBarDelegate::Type InfoBarDelegate::GetInfoBarType() const { + return WARNING_TYPE; +} + +AutoLoginInfoBarDelegate* InfoBarDelegate::AsAutoLoginInfoBarDelegate() { + return NULL; +} + +ConfirmInfoBarDelegate* InfoBarDelegate::AsConfirmInfoBarDelegate() { + return NULL; +} + +ExtensionInfoBarDelegate* InfoBarDelegate::AsExtensionInfoBarDelegate() { + return NULL; +} + +InsecureContentInfoBarDelegate* + InfoBarDelegate::AsInsecureContentInfoBarDelegate() { + return NULL; +} + +MediaStreamInfoBarDelegate* InfoBarDelegate::AsMediaStreamInfoBarDelegate() { + return NULL; +} + +PopupBlockedInfoBarDelegate* InfoBarDelegate::AsPopupBlockedInfoBarDelegate() { + return NULL; +} + +RegisterProtocolHandlerInfoBarDelegate* + InfoBarDelegate::AsRegisterProtocolHandlerInfoBarDelegate() { + return NULL; +} + +ScreenCaptureInfoBarDelegate* + InfoBarDelegate::AsScreenCaptureInfoBarDelegate() { + return NULL; +} + +ThemeInstalledInfoBarDelegate* + InfoBarDelegate::AsThemePreviewInfobarDelegate() { + return NULL; +} + +TranslateInfoBarDelegate* InfoBarDelegate::AsTranslateInfoBarDelegate() { + return NULL; +} + +void InfoBarDelegate::StoreActiveEntryUniqueID() { + DCHECK(web_contents()); + NavigationEntry* active_entry = + web_contents()->GetController().GetActiveEntry(); + contents_unique_id_ = active_entry ? active_entry->GetUniqueID() : 0; +} + +gfx::Image InfoBarDelegate::GetIcon() const { + int icon_id = GetIconID(); + return (icon_id == kNoIconID) ? gfx::Image() : + ResourceBundle::GetSharedInstance().GetNativeImageNamed(icon_id); +} + +content::WebContents* InfoBarDelegate::web_contents() { + return (infobar_ && infobar_->owner()) ? + infobar_->owner()->web_contents() : NULL; +} + +InfoBarDelegate::InfoBarDelegate() : contents_unique_id_(0) { +} + +bool InfoBarDelegate::ShouldExpireInternal( + const content::LoadCommittedDetails& details) const { + // NOTE: If you change this, be sure to check and adjust the behavior of + // anyone who overrides this as necessary! + return (contents_unique_id_ != details.entry->GetUniqueID()) || + (content::PageTransitionStripQualifier( + details.entry->GetTransitionType()) == + content::PAGE_TRANSITION_RELOAD); +} diff --git a/pool/shard001/C++/0022893_VoronoiDelaunay.cc b/pool/shard001/C++/0022893_VoronoiDelaunay.cc new file mode 100644 index 0000000000000000000000000000000000000000..765a0c4169e608d3da699dedf862584953ca4b5c --- /dev/null +++ b/pool/shard001/C++/0022893_VoronoiDelaunay.cc @@ -0,0 +1,138 @@ +#include "Points/VoronoiDelaunay.hh" +#include "external/VoronoiDiagramGenerator.h" +#include +#include + + +namespace +{ + std::pair orientate(sf::Vector2f e1, sf::Vector2f e2, sf::Vector2f p) + { + auto d1 = e2-e1; + auto d2 = p-e1; + if (d1.x*d2.y-d2.x*d1.y > 0) + return {e1, e2}; + return {e2, e1}; + } + + sf::Vector2i grid_align(sf::Vector2f v) + { + return {(int)round(v.x), (int)round(v.y)}; + } + + size_t mul_hash(size_t a, size_t b) + { + return (a*(b+1))%1000000007; + } +} + + +PointsVoronoiDelaunay::PointsVoronoiDelaunay() +: in(this) +, voronoi(this) +, delaunay(this) +{ + name = "PointsVoronoiDelaunay"; +} + +void PointsVoronoiDelaunay::compute() +{ + auto input = in.get_data(); + std::map< + sf::Vector2f, + std::vector>, + Vector2f_cmp + > raw_cells; + + Cells cells; + Triangulation graph; + + VoronoiDiagramGenerator generator; + + float *vx = new float[input.pts.size()]; + float *vy = new float[input.pts.size()]; + + for (size_t i=0; i std::vector + { + for (sf::Vector2f shake : { + sf::Vector2f(0.f,0.f), + sf::Vector2f(0.01234f, 0.06343f), + sf::Vector2f(-0.042352f, 0.08976f) + }) + { + size_t pmul = 1, kmul = 1; + std::vector aligned; + aligned.reserve(e.second.size()); + + for (auto p : e.second) + { + auto + u = grid_align(p.first+shake), + v = grid_align(p.second+shake); + + pmul=mul_hash(pmul, v.x); + pmul=mul_hash(pmul, v.y); + kmul=mul_hash(kmul, u.x); + kmul=mul_hash(kmul, u.y); + aligned.push_back({u, v}); + } + if (pmul == kmul) + return aligned; + } + return std::vector(); + }(); + + auto angle_cmp = [&](const Segment& p1, const Segment& p2) -> bool + { + auto r1 = static_cast(p1.first)-mid; + auto r2 = static_cast(p2.first)-mid; + return atan2(r1.x, r1.y) < atan2(r2.x, r2.y); + }; + + std::sort(cell.begin(), cell.end(), angle_cmp); + } + + data_hook(voronoi) = std::move(cells); +} + + diff --git a/pool/shard001/C++/0022900_blik_asyncfilemanager.cpp b/pool/shard001/C++/0022900_blik_asyncfilemanager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..72a54bc48f167a7fa06ffa39198c3ecadde40501 --- /dev/null +++ b/pool/shard001/C++/0022900_blik_asyncfilemanager.cpp @@ -0,0 +1,195 @@ +#include +#include "blik_asyncfilemanager.hpp" + +#include + +class SaveQuery +{ +public: + SaveQuery() {} + ~SaveQuery() + { + AsyncFileManager::ClearChunks(m_chunks); + } + SaveQuery& operator=(const SaveQuery& rhs) + { + BLIK_ASSERT("해당 객체는 복사할 수 없습니다", false); + return *this; + } + +public: + String m_path; + buffers m_chunks; +}; + +class SaveListing +{ +public: + SaveListing() : m_manager(nullptr) {} + ~SaveListing() {} + SaveListing& operator=(const SaveListing& rhs) + { + BLIK_ASSERT("해당 객체는 복사할 수 없습니다", false); + return *this; + } + +public: + const AsyncFileManager* m_manager; + Map m_queries; +}; + +namespace BLIK +{ + AsyncFileManager::AsyncFileManager() + { + m_tasking = Tasking::Create(OnTask); + BLIK_COMMON(m_tasking, common_buffer) + { + Buffer::Free(common_buffer); + common_buffer = Buffer::Alloc(BLIK_DBG 1); + ((SaveListing*) common_buffer)->m_manager = this; + } + } + + AsyncFileManager::~AsyncFileManager() + { + Tasking::Release(m_tasking, true); + } + + bool AsyncFileManager::Exist(chars path) const + { + bool Result = false; + BLIK_COMMON_IF(m_tasking, common_buffer) + { + SaveListing* List = (SaveListing*) common_buffer; + if(SaveQuery** OldQuery = List->m_queries.Access(path)) + { + Result = true; + BLIK_TRACE("[Exist] 요청목록에 파일이 있음 : %s", path); + } + } + + if(!Result) + { + Result = Platform::File::Exist(path); + BLIK_TRACE("[Exist] 실제폴더에 파일이 %s : %s", (Result)? "있음" : "없음", path); + } + return Result; + } + + void AsyncFileManager::SaveChunks(chars path, buffers chunks) + { + SaveQuery** OldQuery = nullptr; + BLIK_COMMON_IF(m_tasking, common_buffer) + { + SaveListing* List = (SaveListing*) common_buffer; + if(OldQuery = List->m_queries.Access(path)) + { + ClearChunks((*OldQuery)->m_chunks); + (*OldQuery)->m_chunks = chunks; + BLIK_TRACE("[SaveChunks] 요청목록을 재갱신 : %s", path); + } + } + + if(!OldQuery) + { + SaveQuery* NewQuery = (SaveQuery*) Buffer::Alloc(BLIK_DBG 1); + NewQuery->m_path = path; + NewQuery->m_chunks = chunks; + + BLIK_COMMON_IF(m_tasking, common_buffer) + { + SaveListing* List = (SaveListing*) common_buffer; + List->m_queries(path) = NewQuery; + Tasking::SendQuery(m_tasking, (buffer) NewQuery); + BLIK_TRACE("[SaveChunks] 요청목록에 신규요청 : %s", path); + } + } + } + + buffers AsyncFileManager::LoadChunks(chars path, sint32 offset, sint32 length) const + { + BLIK_ASSERT("length값은 0보다 커야 합니다", 0 < length); + buffers Result; + BLIK_COMMON_IF(m_tasking, common_buffer) + { + SaveListing* List = (SaveListing*) common_buffer; + if(SaveQuery** OldQuery = List->m_queries.Access(path)) + { + const buffers& OldChunks = (*OldQuery)->m_chunks; + for(sint32 i = offset, iend = i + length; i < iend; ++i) + Result.AtAdding() = Buffer::Clone(BLIK_DBG OldChunks[i]); + BLIK_TRACE("[LoadChunks] 요청목록에서 파일을 읽음 : %s", path); + } + } + + if(!Result.Count()) + { + id_file_read OldFile = Platform::File::OpenForRead(path); + if(OldFile) + { + Result = OnReadFile(OldFile, offset, length); + Platform::File::Close(OldFile); + } + BLIK_TRACE("[LoadChunks] 실제폴더에서 파일을 %s : %s", (OldFile)? "읽음" : "찾지못함", path); + } + return Result; + } + + void AsyncFileManager::ClearChunks(buffers& chunks) + { + for(sint32 i = 0, iend = chunks.Count(); i < iend; ++i) + Buffer::Free(chunks.At(i)); + chunks.Clear(); + } + + void AsyncFileManager::OnWriteFile(id_file file, const buffers chunks) const + { + for(sint32 i = 0, iend = chunks.Count(); i < iend; ++i) + { + const buffer OldBuffer = chunks[i]; + const sint32 CopyCount = Buffer::CountOf(OldBuffer); + Platform::File::Write(file, (bytes) &CopyCount, sizeof(CopyCount)); + Platform::File::Write(file, (bytes) OldBuffer, Buffer::SizeOf(OldBuffer) * CopyCount); + } + } + + buffers AsyncFileManager::OnReadFile(id_file_read file, sint32 offset, sint32 length) const + { + buffers Result; + for(sint32 i = offset, iend = i + length; i < iend; ++i) + { + sint32 CopyCount = 0; + Platform::File::Read(file, (uint08*) &CopyCount, sizeof(CopyCount)); + buffer& NewBuffer = Result.AtAdding(); + NewBuffer = Buffer::Realloc(BLIK_DBG NewBuffer, CopyCount); + Platform::File::Read(file, (uint08*) NewBuffer, Buffer::SizeOf(NewBuffer) * CopyCount); + } + return Result; + } + + sint32 AsyncFileManager::OnTask(buffer& self, Queue& query, Queue& answer, id_common common) + { + if(SaveQuery* CurQuery = (SaveQuery*) query.Dequeue()) + { + const AsyncFileManager* Manager = nullptr; + BLIK_COMMON_TASK_IF(common, common_buffer) + Manager = ((SaveListing*) common_buffer)->m_manager; + + if(Manager) + { + BLIK_TRACE("[OnTask] 해당 요청을 실제폴더에 저장후 요청목록에서 제거 : %s", (chars) CurQuery->m_path); + id_file NewFile = Platform::File::OpenForWrite(CurQuery->m_path, true); + Manager->OnWriteFile(NewFile, CurQuery->m_chunks); + Platform::File::Close(NewFile); + + BLIK_COMMON_TASK_IF(common, common_buffer) + (((SaveListing*) common_buffer))->m_queries.Remove(CurQuery->m_path); + Buffer::Free((buffer) CurQuery); + return 0; + } + else BLIK_ASSERT("AsyncFileManager의 인스턴스가 없습니다", false); + } + return 100; + } +} diff --git a/pool/shard001/C++/0022901_brtrace.cpp b/pool/shard001/C++/0022901_brtrace.cpp new file mode 100644 index 0000000000000000000000000000000000000000..132f4cffcee009ba3f9a9017ca41c55f5b13fee8 --- /dev/null +++ b/pool/shard001/C++/0022901_brtrace.cpp @@ -0,0 +1,74 @@ +#include +#include "pin.H" + +FILE * trace; + +#define Print2File + +// This function is called before every instruction is executed +// and prints the IP +VOID printip(VOID *ip, VOID *target, BOOL taken) +{ + #ifdef Print2File + fprintf(trace, "%p %p %s\n", ip, target, (taken? "Y": "N")); + #else + printf("%p %p %s\n", ip, target, (taken? "Y": "N")); + #endif +} + +// Pin calls this function every time a new instruction is encountered +VOID Instruction(INS ins, VOID *v) +{ + // Insert a call to printip before every instruction, and pass it the IP + if (INS_IsBranch(ins)) + { + // IARG_INST_PTR, IARG_BRANCH_TARGET_ADDR, and IARG_BRANCH_TAKEN + INS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR)printip, + IARG_INST_PTR, IARG_BRANCH_TARGET_ADDR, IARG_BRANCH_TAKEN, IARG_END); + } +} + +// This function is called when the application exits +VOID Fini(INT32 code, VOID *v) +{ + #ifdef Print2File + fprintf(trace, "#eof\n"); + fclose(trace); + #endif +} + +/* ===================================================================== */ +/* Print Help Message */ +/* ===================================================================== */ + +INT32 Usage() +{ + PIN_ERROR("This Pintool works on branch prediction\n" + + KNOB_BASE::StringKnobSummary() + "\n"); + return -1; +} + +/* ===================================================================== */ +/* Main */ +/* ===================================================================== */ + +int main(int argc, char * argv[]) +{ + #ifdef Print2File + trace = fopen("brtrace.out", "w"); + #endif + + // Initialize pin + if (PIN_Init(argc, argv)) return Usage(); + + // Register Instruction to be called to instrument instructions + INS_AddInstrumentFunction(Instruction, 0); + + // Register Fini to be called when the application exits + PIN_AddFiniFunction(Fini, 0); + + // Start the program, never returns + PIN_StartProgram(); + + return 0; +} diff --git a/pool/shard001/C++/0022916_inspector_media_context_impl.cc b/pool/shard001/C++/0022916_inspector_media_context_impl.cc new file mode 100644 index 0000000000000000000000000000000000000000..a172dc6d69794c01b0da0c9a52423b92eb9780c9 --- /dev/null +++ b/pool/shard001/C++/0022916_inspector_media_context_impl.cc @@ -0,0 +1,122 @@ +// 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 "third_party/blink/renderer/core/inspector/inspector_media_context_impl.h" + +#include +#include + +#include "base/unguessable_token.h" +#include "third_party/blink/renderer/core/frame/local_dom_window.h" +#include "third_party/blink/renderer/core/probe/core_probes.h" + +namespace blink { + +const char MediaInspectorContextImpl::kSupplementName[] = + "MediaInspectorContextImpl"; + + +// static +MediaInspectorContextImpl* MediaInspectorContextImpl::From( + LocalDOMWindow& window) { + auto* context = + Supplement::From(window); + if (!context) { + context = MakeGarbageCollected(window); + Supplement::ProvideTo(window, context); + } + return context; +} + +MediaInspectorContextImpl::MediaInspectorContextImpl(LocalDOMWindow& frame) + : Supplement(frame) {} + +// Local to cc file for converting +template +static Vector Iter2Vector(const Iterable& iterable) { + Vector result; + result.AppendRange(iterable.begin(), iterable.end()); + return result; +} + +// Garbage collection method. +void MediaInspectorContextImpl::Trace(Visitor* visitor) { + Supplement::Trace(visitor); + visitor->Trace(players_); +} + +Vector MediaInspectorContextImpl::AllPlayerIds() { + Vector existing_players; + existing_players.ReserveCapacity(players_.size()); + for (const auto& player_id : players_.Keys()) + existing_players.push_back(player_id); + return existing_players; +} + +const MediaPlayer& MediaInspectorContextImpl::MediaPlayerFromId( + const WebString& player_id) { + const auto& player = players_.find(player_id); + DCHECK_NE(player, players_.end()); + return *player->value; +} + +WebString MediaInspectorContextImpl::CreatePlayer() { + String next_player_id = + String::FromUTF8(base::UnguessableToken::Create().ToString()); + players_.insert(next_player_id, MakeGarbageCollected()); + probe::PlayersCreated(GetSupplementable(), {next_player_id}); + return next_player_id; +} + +// Convert public version of event to protocol version, and send it. +void MediaInspectorContextImpl::NotifyPlayerErrors( + WebString playerId, + const InspectorPlayerErrors& errors) { + const auto& player = players_.find(playerId); + DCHECK_NE(player, players_.end()); + player->value->errors.AppendRange(errors.begin(), errors.end()); + + Vector vector = + Iter2Vector(errors); + probe::PlayerErrorsRaised(GetSupplementable(), playerId, vector); +} + +void MediaInspectorContextImpl::NotifyPlayerEvents( + WebString playerId, + const InspectorPlayerEvents& events) { + const auto& player = players_.find(playerId); + DCHECK_NE(player, players_.end()); + player->value->events.AppendRange(events.begin(), events.end()); + + Vector vector = + Iter2Vector(events); + probe::PlayerEventsAdded(GetSupplementable(), playerId, vector); +} + +void MediaInspectorContextImpl::SetPlayerProperties( + WebString playerId, + const InspectorPlayerProperties& props) { + const auto& player = players_.find(playerId); + DCHECK_NE(player, players_.end()); + for (const auto& property : props) + player->value->properties.insert(property.name, property); + + Vector vector = + Iter2Vector(props); + probe::PlayerPropertiesChanged(GetSupplementable(), playerId, vector); +} + +void MediaInspectorContextImpl::NotifyPlayerMessages( + WebString playerId, + const InspectorPlayerMessages& messages) { + const auto& player = players_.find(playerId); + DCHECK_NE(player, players_.end()); + player->value->messages.AppendRange(messages.begin(), messages.end()); + + Vector vector = + Iter2Vector(messages); + probe::PlayerMessagesLogged(GetSupplementable(), playerId, vector); +} + +} // namespace blink diff --git a/pool/shard001/C++/0022921_eeprom_wired.cpp b/pool/shard001/C++/0022921_eeprom_wired.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cf0468151e5ed33f3d0a4f0a286f328ab1187221 --- /dev/null +++ b/pool/shard001/C++/0022921_eeprom_wired.cpp @@ -0,0 +1,80 @@ +/** + * Marlin 3D Printer Firmware + * + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * Copyright (c) 2016 Bob Cousins bobcousins42@googlemail.com + * Copyright (c) 2015-2016 Nico Tonnhofer wurstnase.reprap@gmail.com + * Copyright (c) 2016 Victor Perez victor_pv@hotmail.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 "../platforms.h" + +#ifdef HAL_STM32 + +#include "../../inc/MarlinConfig.h" + +#if USE_WIRED_EEPROM + +/** + * PersistentStore for Arduino-style EEPROM interface + * with simple implementations supplied by Marlin. + */ + +#include "../shared/eeprom_if.h" +#include "../shared/eeprom_api.h" + +#ifndef MARLIN_EEPROM_SIZE + #define MARLIN_EEPROM_SIZE size_t(E2END + 1) +#endif +size_t PersistentStore::capacity() { return MARLIN_EEPROM_SIZE; } + +bool PersistentStore::access_start() { eeprom_init(); return true; } +bool PersistentStore::access_finish() { return true; } + +bool PersistentStore::write_data(int &pos, const uint8_t *value, size_t size, uint16_t *crc) { + uint16_t written = 0; + while (size--) { + uint8_t v = *value; + uint8_t * const p = (uint8_t * const)pos; + if (v != eeprom_read_byte(p)) { // EEPROM has only ~100,000 write cycles, so only write bytes that have changed! + eeprom_write_byte(p, v); + if (++written & 0x7F) delay(2); else safe_delay(2); // Avoid triggering watchdog during long EEPROM writes + if (eeprom_read_byte(p) != v) { + SERIAL_ECHO_MSG(STR_ERR_EEPROM_WRITE); + return true; + } + } + crc16(crc, &v, 1); + pos++; + value++; + } + return false; +} + +bool PersistentStore::read_data(int &pos, uint8_t *value, size_t size, uint16_t *crc, const bool writing/*=true*/) { + do { + // Read from either external EEPROM, program flash or Backup SRAM + const uint8_t c = eeprom_read_byte((uint8_t*)pos); + if (writing) *value = c; + crc16(crc, &c, 1); + pos++; + value++; + } while (--size); + return false; +} + +#endif // USE_WIRED_EEPROM +#endif // HAL_STM32 diff --git a/pool/shard001/C++/0022929_Filterer.cpp b/pool/shard001/C++/0022929_Filterer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..901061bf6a41b1f0c8d8c833430b7fd0bca3ec47 --- /dev/null +++ b/pool/shard001/C++/0022929_Filterer.cpp @@ -0,0 +1,54 @@ +/* ========================================================================= + * This file is part of logging-c++ + * ========================================================================= + * + * (C) Copyright 2004 - 2014, MDA Information Systems LLC + * + * logging-c++ 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 . + * + */ + +/////////////////////////////////////////////////////////// +// Filterer.cpp +/////////////////////////////////////////////////////////// + +#include "logging/Filterer.h" + + +void logging::Filterer::addFilter(logging::Filter* filter) +{ + if (filters.find(filter->getName()) == filters.end()) + { + filters[filter->getName()] = filter; + } +} + +bool logging::Filterer::filter(const logging::LogRecord* record) const +{ + for (std::map::const_iterator p = filters.begin(); + p != filters.end(); ++p) + { + if (!p->second->filter(record)) + return false; + } + return true; +} + +void logging::Filterer::removeFilter(logging::Filter* filter) +{ + filters.erase(filter->getName()); + +} + diff --git a/pool/shard001/C++/0022931_examples.cc b/pool/shard001/C++/0022931_examples.cc new file mode 100644 index 0000000000000000000000000000000000000000..d11588b439ee9d2b812a7f229b3addaa5d417a49 --- /dev/null +++ b/pool/shard001/C++/0022931_examples.cc @@ -0,0 +1,125 @@ +/* + * wrep - command line tool to work with weather bulletins + * + * Copyright (C) 2011 ARPA-SIM + * + * 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. + * + * 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 + * + * Author: Enrico Zini + */ + +#include +#include +#include +#include +#include +#include "config.h" + +#ifdef HAS_GETOPT_LONG +#include +#endif + +using namespace wreport; +using namespace std; + +// These are split in separate files so they can be loaded as example code by +// the documentation +#include "makebuoy.cc" + +void do_usage(FILE* out) +{ + fputs("Usage: examples [options]\n", out); +} + +void do_help(FILE* out) +{ + do_usage(out); + fputs( + "Run wreport examples\n" + "Options:\n" + " -v,--verbose verbose operation\n" + " -h,--help print this help message\n" + " -B,--makebuoy generate a buoy BUFR message\n" +#ifndef HAS_GETOPT_LONG + "NOTE: long options are not supported on this system\n" +#endif + , out); +} + +int main(int argc, char* argv[]) +{ +#ifdef HAS_GETOPT_LONG + static struct option long_options[] = + { + /* These options set a flag. */ + {"makebuoy", no_argument, NULL, 'B'}, + {"verbose", no_argument, NULL, 'v'}, + {"help", no_argument, NULL, 'h'}, + {0, 0, 0, 0} + }; +#endif + + // Parse command line options + bool verbose = false; + enum { HELP, MAKEBUOY } action = HELP; + while (1) + { + // getopt_long stores the option index here + int option_index = 0; + +#ifdef HAS_GETOPT_LONG + int c = getopt_long(argc, argv, "vh", + long_options, &option_index); +#else + int c = getopt(argc, argv, "vh"); +#endif + + // Detect the end of the options + if (c == -1) + break; + + switch (c) + { + case 'v': verbose = true; break; + case 'h': action = HELP; break; + case 'B': action = MAKEBUOY; break; + default: + fprintf(stderr, "unknown option character %c (%d)\n", c, c); + do_help(stderr); + return 1; + } + } + + // Print out processing remarks if verbose + if (verbose) + notes::set_target(cerr); + + // Run the handler for the action requested by the user + try { + switch (action) + { + case HELP: + do_help(stdout); + return 0; + case MAKEBUOY: + do_makebuoy(); + return 0; + } + } catch (std::exception& e) { + fprintf(stderr, "%s\n", e.what()); + return 1; + } + + return 0; +} diff --git a/pool/shard001/C++/0022937_roundtrip_tcp.cc b/pool/shard001/C++/0022937_roundtrip_tcp.cc new file mode 100644 index 0000000000000000000000000000000000000000..76582bd219c3bcf7420b9977d149bbb445d4396a --- /dev/null +++ b/pool/shard001/C++/0022937_roundtrip_tcp.cc @@ -0,0 +1,152 @@ +#include "InetAddress.h" +#include "TcpStream.h" + +#include +#include +#include +#include +#include +#include + +#include + +int64_t kNanos = 1e9; +int64_t clock_diff(struct timespec x, struct timespec y) +{ + return (x.tv_sec - y.tv_sec) * kNanos + x.tv_nsec - y.tv_nsec; +} + +struct timespec get_time() +{ + struct timespec now; + clock_gettime(CLOCK_MONOTONIC, &now); + return now; +} + +struct Sample +{ + int index; + int64_t start_nano; + int64_t rtt_nano; +}; + +std::vector run(const char* host, int delay_ms, int length_s, int batch, int payload_size, bool silent) +{ + const struct timespec start = get_time(); + std::vector rtts; + + InetAddress addr; + if (!InetAddress::resolve(host, 3007, &addr)) + { + printf("Unable to resolve %s\n", host); + return rtts; + } + + // printf("connecting to %s\n", addr.toIpPort().c_str()); + TcpStreamPtr stream(TcpStream::connect(addr)); + if (!stream) + { + printf("Unable to connect %s\n", addr.toIpPort().c_str()); + perror(""); + return rtts; + } + + std::unique_ptr payload(new char[payload_size]); + int64_t count = 0, sum_rtt = 0; + int64_t min_rtt = std::numeric_limits::max(), max_rtt = 0; + + while (true) { + const struct timespec batch_start = get_time(); + double elapsed_s = (double)clock_diff(batch_start, start) / kNanos; + if (elapsed_s >= length_s) { + if (silent && count > 0) { + printf("count %ld, avg rtt %.2fus, min %.2fus, max %.2fus\n", + count, sum_rtt / 1e3 / count, min_rtt / 1e3, max_rtt / 1e3); + } + break; + } + + for (int i = 0; i < batch; ++i) { + const struct timespec before = get_time(); + int nw = stream->sendAll(payload.get(), payload_size); + if (nw != payload_size) + return rtts; + int nr = stream->receiveAll(payload.get(), payload_size); + if (nr != payload_size) + return rtts; + const struct timespec after = get_time(); + int64_t rtt = clock_diff(after, before); + ++count; + sum_rtt += rtt; + if (rtt > max_rtt) + max_rtt = rtt; + if (rtt < min_rtt) + min_rtt = rtt; + + Sample s = { + .index = i, + .rtt_nano = rtt, + }; + if (i == 0) + s.start_nano = clock_diff(before, start); + else + s.start_nano = clock_diff(before, batch_start); + if (!silent) + rtts.push_back(s); + } + + if (delay_ms > 0) { + ::usleep(delay_ms * 1000); + } + } + return rtts; +} + +int main(int argc, char* argv[]) +{ + int opt; + int delay = 0, length = 3, batch = 4, payload = 1; + bool silent = false; + while ((opt = getopt(argc, argv, "b:d:l:p:s")) != -1) { + switch (opt) { + case 'b': + batch = atoi(optarg); + break; + case 'd': + delay = atoi(optarg); + break; + case 'l': + length = atoi(optarg); + break; + case 'p': + payload = atoi(optarg); + break; + case 's': + silent = true; + break; + default: + ; + } + } + if (optind >= argc) { + fprintf(stderr, "Usage:\nroundtrip_tcp [-b batch_size] [-d delay_ms] [-l length_in_seconds] echo_server_host\n"); + return 1; + } + if (batch < 1) { + batch = 1; + } + if (delay < 0) { + delay = 0; + } + if (payload < 1) { + payload = 1; + } + + std::vector rtts = run(argv[optind], delay, length, batch, payload, silent); + if (!silent) { + printf("index start rtt\n"); + for (Sample s : rtts) { + printf("%d %ld %ld\n", s.index, s.start_nano, s.rtt_nano); + } + } +} diff --git a/pool/shard001/C++/0022940_syntax_tree.cpp b/pool/shard001/C++/0022940_syntax_tree.cpp new file mode 100644 index 0000000000000000000000000000000000000000..53c547d282be322cda2a79c51ad78ac2d076f2d7 --- /dev/null +++ b/pool/shard001/C++/0022940_syntax_tree.cpp @@ -0,0 +1,120 @@ +#include "tinyp_structs.h" +#include "syntax_tree.h" +#include "stdlib.h" + +struct syntax_tree_node_t* new_tree_node(enum NodeType node_type, + struct syntax_tree_node_t* st, + struct syntax_tree_node_t* nd, + struct syntax_tree_node_t* rd) { + struct syntax_tree_node_t* n = + (struct syntax_tree_node_t*)malloc(sizeof(struct syntax_tree_node_t)); + n->node_type = node_type; + n->sibiling = NULL; + n->child[0] = st; + n->child[1] = nd; + n->child[2] = rd; + return n; +} + +void destroyTree(struct syntax_tree_node_t* root) { + if (root) { + for (int i = 0; i != 3; ++i) { + destroyTree(root->child[i]); + } + if (root->sibiling) { + destroyTree(root->sibiling); + } + free(root); + root = NULL; + } +} + +struct syntax_tree_node_t* new_stmt_node(enum NodeType node_type) { + // struct syntax_tree_node_t *n = (struct + // syntax_tree_node_t*)malloc(sizeof(struct syntax_tree_node_t)); + struct syntax_tree_node_t* n = new struct syntax_tree_node_t(); + if (n == NULL) { + printf("Not enough memory.\n"); + } else { + for (int i = 0; i < 3; ++i) { + n->child[i] = NULL; + } + n->sibiling = NULL; + n->node_type = node_type; + n->token.kind = TK_COMMENT; + n->token.value = ""; + } + return n; +} + +struct syntax_tree_node_t* new_exp_node(enum NodeType node_type) { + // struct syntax_tree_node_t *n = (struct + // syntax_tree_node_t*)malloc(sizeof(struct syntax_tree_node_t)); + struct syntax_tree_node_t* n = new struct syntax_tree_node_t(); + if (n == NULL) { + printf("Not enough memory.\n"); + } else { + for (int i = 0; i < 3; ++i) { + n->child[i] = NULL; + } + n->sibiling = NULL; + n->node_type = node_type; + n->token.kind = TK_COMMENT; + n->token.value = ""; + } + return n; +} + +static unsigned int indent = 0; + +static void print_indent() { + for (int i = 0; i != indent; ++i) printf(" "); +} + +void printTree(struct syntax_tree_node_t* root) { + if (root == NULL) return; + indent += 2; + while (root != NULL) { + print_indent(); + switch (root->node_type) { + case STMT_IF: + printf("If\n"); + break; + case STMT_REPEAT: + printf("Repeat\n"); + break; + case STMT_WHILE: + printf("While\n"); + break; + case STMT_ASSIGN: + printf("Assign to : %s\n", root->token.value.c_str()); + break; + case STMT_READ: + printf("Read : %s\n", root->token.value.c_str()); + break; + case STMT_WRITE: + printf("Write : %s\n", root->token.value.c_str()); + break; + + case EXP_OP: + printf("Op: %s\n", root->token.value.c_str()); + break; + case EXP_CONST: + printf("Const: %s\n", root->token.value.c_str()); + break; + case EXP_ID: + printf("ID : %s\n", root->token.value.c_str()); + break; + case EXP_STR: + printf("Str : %s\n", root->token.value.c_str()); + break; + + default: + printf("Unknown NodeType\n"); + break; + } + for (int i = 0; i != 3; ++i) printTree(root->child[i]); + root = root->sibiling; + } + indent -= 2; +} diff --git a/pool/shard001/C++/0022942_cmd_icd.cc b/pool/shard001/C++/0022942_cmd_icd.cc new file mode 100644 index 0000000000000000000000000000000000000000..930fa9bddaf49c992bd8081e665b50436972bd80 --- /dev/null +++ b/pool/shard001/C++/0022942_cmd_icd.cc @@ -0,0 +1,87 @@ +/* + Copyright (C) 1999 T. Scott Dattalo + +This file is part of gpsim. + +gpsim 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. + +gpsim 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 gpsim; see the file COPYING. If not, write to +the Free Software Foundation, 59 Temple Place - Suite 330, +Boston, MA 02111-1307, USA. */ + + +#include +#include +#include + +#include "command.h" +#include "cmd_icd.h" +#include "../src/icd.h" + +cmd_icd c_icd; + +#define ICD_OPEN_CMD 1 + +static cmd_options cmd_icd_options[] = +{ + {"open", ICD_OPEN_CMD, OPT_TT_STRING}, + {0,0,0} +}; + +cmd_icd::cmd_icd() + : command("icd",0) +{ + brief_doc = string("ICD command."); + + long_doc = string ("\nicd [open ]\n\ +\tThe open command is used to enable ICD mode and specify the serial\n\ +\tport where the ICD is. (e.g. \"icd open /dev/ttyS0\").\n\ +\tWithout options (and after the icd is enabled), it will print some\n\ +\tinformation about the ICD.\n\ +"); + + op = cmd_icd_options; +} + +#include + +void cmd_icd::icd() +{ + if(icd_detected()) + { + printf("ICD version \"%s\" was found.\n",icd_version()); + printf("Target controller is %s.\n", icd_target()); + printf("Vdd: %.1f\t",icd_vdd()); + printf("Vpp: %.1f\n",icd_vpp()); + if(icd_has_debug_module()) + puts("Debug module is present"); + else + puts("Debug moudle is NOT present."); + } + else + { + printf("ICD has not been opened (use the \"icd open\" command)\n"); + } +} + +void cmd_icd::icd(cmd_options_str *cos) +{ + switch(cos->co->value) { + case ICD_OPEN_CMD: + cout << "ICD open " << cos->str << endl; + icd_connect(cos->str); + break; + default: + cout << " Invalid set option\n"; + } + +} diff --git a/pool/shard001/C++/0022945_07_2_fibline_80_100.cpp b/pool/shard001/C++/0022945_07_2_fibline_80_100.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1e4f7624f269fa8ca4ef3f648c36043d86d41f68 --- /dev/null +++ b/pool/shard001/C++/0022945_07_2_fibline_80_100.cpp @@ -0,0 +1,58 @@ +#include +#include +using namespace std; +typedef int lng ; +string a0="1", a1="1", num ; +lng k, currentDigit = 2; + +char numToChar (lng n) +{ + return ((char)('0'+n%10)) ; +} + +lng charToNum (char c) +{ + return ((lng)(c-'0')) ; +} + + +string addStrings (string a0, string a1) +{ + string res = ""; + lng i, sum=0 ; + if (a0.length() < a1.length()) + swap(a0, a1) ; + if (a0.length()>a1.length()) + { + // to fill leading zeros to a1 + for (lng k=0; k<(a0.length()-a1.length()); ++k) + a1 = '0' + a1; + } ; + + for (i=a0.length()-1; i>=0; --i) + { + sum = sum + charToNum(a0[i]) + charToNum(a1[i]) ; + // res = numToChar(sum%10) + res ; + res.insert(0, 1, numToChar(sum%10)) ; + sum = sum/10 ; // PRENOS mayBe + } ; + + if (sum>0) // ima prenos + res.insert(0, 1, numToChar(sum)) ; + return res ; +} + +int main () +{ + string fibLine="11" ; + lng cDig = 2 ; + cin >>k ; // 2 + +XnDeviceModuleHolder::XnDeviceModuleHolder(XnDeviceModule* pModule) : + m_pModule(pModule) +{} + +XnDeviceModuleHolder::~XnDeviceModuleHolder() +{ + XnDeviceModuleHolder::Free(); +} + +XnStatus XnDeviceModuleHolder::Init(const XnActualPropertiesHash* pInitialValues) +{ + XnStatus nRetVal = XN_STATUS_OK; + + nRetVal = m_pModule->Init(); + XN_IS_STATUS_OK(nRetVal); + + if (pInitialValues != NULL) + { + nRetVal = m_pModule->BatchConfig(*pInitialValues); + XN_IS_STATUS_OK(nRetVal); + } + + return (XN_STATUS_OK); +} + +XnStatus XnDeviceModuleHolder::Free() +{ + return XN_STATUS_OK; +} diff --git a/pool/shard001/C++/0022952_testmemcli.cpp b/pool/shard001/C++/0022952_testmemcli.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f532a4a70d755c2948c90ef7ee7baf256e295041 --- /dev/null +++ b/pool/shard001/C++/0022952_testmemcli.cpp @@ -0,0 +1,169 @@ +/* + * Copyright 2008 Stephen Liu + * For license terms, see the file COPYING along with this library. + */ + +#include +#include +#include +#include +#include +#include + +#include "spnkmemcli.hpp" +#include "spnkmemobj.hpp" + +#include "spnkini.hpp" +#include "spnklist.hpp" +#include "spnkendpoint.hpp" +#include "spnksocketpool.hpp" +#include "spnkstr.hpp" +#include "spnklog.hpp" +#include "spnksocket.hpp" +#include "spnktime.hpp" +#include "spnkconfig.hpp" + +#include "spnkgetopt.h" + +SP_NKMemClient * InitMemClient( const char * config ) +{ + SP_NKEndPointTable * table = NULL; + SP_NKSocketPool * socketPool = NULL; + + SP_NKIniFile ini; + if( 0 == ini.open( config ) ) { + SP_NKSocketPoolConfig poolConfig; + poolConfig.init( &ini, "SocketPool" ); + + SP_NKTcpSocketFactory * factory = new SP_NKTcpSocketFactory(); + factory->setTimeout( poolConfig.getConnectTimeout(), poolConfig.getSocketTimeout() ); + socketPool = new SP_NKSocketPool( poolConfig.getMaxIdlePerEndPoint(), factory ); + socketPool->setMaxIdleTime( poolConfig.getMaxIdleTime() ); + + table = SP_NKEndPointTableConfig::readTable( &ini ); + } + + SP_NKMemClient * memClient = NULL; + + if( NULL != table ) { + memClient = new SP_NKMemClient( table ); + memClient->setSocketPool( socketPool ); + } + + return memClient; +} + +void showUsage( const char * program ) +{ + printf( "Usage: %s [-f config] [-l ] [-v]\n", program ); +} + +int main( int argc, char * argv[] ) +{ +#ifndef WIN32 + assert ( sigset ( SIGPIPE, SIG_IGN ) != SIG_ERR ) ; +#endif + + const char * config = "testmemcli.ini"; + int loops = 100; + + extern char *optarg ; + int c ; + + while( ( c = getopt ( argc, argv, "c:l:ov" )) != EOF ) { + switch ( c ) { + case 'c': + config = optarg; + break; + case 'l': + loops = atoi( optarg ); + break; + case 'o': + SP_NKLog::init4test( "testmemcli" ); + SP_NKSocket::setLogSocketDefault( 1 ); + break; + case '?' : + case 'v' : + showUsage( argv[0] ); + exit( -1 ); + } + } + + if( 0 != spnk_initsock() ) assert( 0 ); + + SP_NKLog::setLogLevel( LOG_INFO ); + + printf( "Use config %s\n", config ); + + SP_NKMemClient * memClient = InitMemClient( config ); + + char key[ 128 ] = { 0 }; + + SP_NKMemItem item; + + SP_NKClock clock; + + int i = 0; + + for( i = 0; i < loops; i++ ) { + snprintf( key, sizeof( key ), "testkey%d", i ); + + item.setKey( key ); + item.setFlags( 1234 ); + item.setDataBlock( strdup( "This is a test of an object blah blah es, " + "serialization does not seem to slow things down so much. " + "The gzip compression is horrible horrible performance, " + "so we only use it for very large objects. " + "I have not done any heavy benchmarking recently" ) ); + + if( ! memClient->stor( "set", &item ) ) { + printf( "fail on loop#%d\n", i ); + exit( 0 ); + } + } + + printf( "stor %d items ok, use %ld ms\n", loops, clock.getInterval() ); + + for( i = 0; i < loops; i++ ) { + snprintf( key, sizeof( key ), "testkey%d", i ); + + if( ! memClient->retr( key, &item ) ) { + printf( "fail on loop#%d\n", i ); + exit( 0 ); + } + } + + printf( "retr %d/1 items ok, use %ld ms\n", loops, clock.getInterval() ); + + for( i = 0; i < loops; i += 100 ) { + SP_NKStringList keyList; + for( int j = 0; j < 100; j++ ) { + snprintf( key, sizeof( key ), "testkey%d", i + j ); + keyList.append( key ); + } + + SP_NKMemItemList itemList; + if( ! memClient->retr( &keyList, &itemList ) ) { + printf( "fail on loop#%d\n", i ); + exit( 0 ); + } + + assert( keyList.getCount() == itemList.getCount() ); + } + + printf( "retr %d/100 items ok, use %ld ms\n", loops, clock.getInterval() ); + + SP_NKMemStatList statList; + memClient->stat( &statList ); + + for( i = 0; i < statList.getCount(); i++ ) { + const SP_NKMemStat * stat = statList.getItem( i ); + printf( "%s:%d curr_items %s\n", stat->getIP(), stat->getPort(), + stat->getValue( "curr_items" ) ); + } + + delete memClient; + + return 0; +} + diff --git a/pool/shard001/C++/0022967_game_over.cpp b/pool/shard001/C++/0022967_game_over.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e7c79b17d611fc7562989b7fc7a2747572a66ea5 --- /dev/null +++ b/pool/shard001/C++/0022967_game_over.cpp @@ -0,0 +1,53 @@ +#include "globals.h" + +static GAME_TEXTURE winner_texture, inst; +static double x, y; + +void init_game_over_state() +{ + SDL_Color c = { 0, 255, 0, 255 }; + inst = text("Press Esc", mono_oblique_font18, c); + x = 170; y = 200; +} + +int winning_player() +{ + int i; + int max_score = 0, winner; + for(i = 0; i < players; i++) + { + if(scores[i] > max_score) + { + max_score = scores[i]; + winner = i; + } + } + return winner; +} + +void move_to_game_over_state() +{ + game_state = GAME_OVER; + if(winner_texture.sdl_texture) + { + SDL_DestroyTexture(winner_texture.sdl_texture); + } + + + char str[20]; + sprintf(str, "PLAYER%d WINS", winning_player() + 1); + + SDL_Color c = { 0, 255, 0, 255 }; + winner_texture = text(str, mono_font22, c); +} + +void render_game_over_state() +{ + SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_BLEND); + SDL_SetRenderDrawColor(renderer, 0, 0, 0, 150); + SDL_Rect rect = { 0, 0, WIDTH, HEIGHT }; + SDL_RenderFillRect(renderer, &rect); + + render_text(&winner_texture, x, y); + render_text(&inst, x + 50, y + 50); +} \ No newline at end of file diff --git a/pool/shard001/C++/0022971_OutputDev.cc b/pool/shard001/C++/0022971_OutputDev.cc new file mode 100644 index 0000000000000000000000000000000000000000..061b0cd6c081426af0aef435b085ddec50ef092f --- /dev/null +++ b/pool/shard001/C++/0022971_OutputDev.cc @@ -0,0 +1,164 @@ +//======================================================================== +// +// OutputDev.cc +// +// Copyright 1996-2003 Glyph & Cog, LLC +// +//======================================================================== + +#include + +#ifdef USE_GCC_PRAGMAS +#pragma implementation +#endif + +#include +#include "Object.h" +#include "Stream.h" +#include "GfxState.h" +#include "OutputDev.h" +#include "goo/GooHash.h" + +//------------------------------------------------------------------------ +// OutputDev +//------------------------------------------------------------------------ + +void OutputDev::setDefaultCTM(FixedPoint *ctm) { + int i; + FixedPoint det; + + for (i = 0; i < 6; ++i) { + defCTM[i] = ctm[i]; + } + det = (FixedPoint)1 / (defCTM[0] * defCTM[3] - defCTM[1] * defCTM[2]); + defICTM[0] = defCTM[3] * det; + defICTM[1] = -defCTM[1] * det; + defICTM[2] = -defCTM[2] * det; + defICTM[3] = defCTM[0] * det; + defICTM[4] = (defCTM[2] * defCTM[5] - defCTM[3] * defCTM[4]) * det; + defICTM[5] = (defCTM[1] * defCTM[4] - defCTM[0] * defCTM[5]) * det; +} + +void OutputDev::cvtDevToUser(FixedPoint dx, FixedPoint dy, FixedPoint *ux, FixedPoint *uy) { + *ux = defICTM[0] * dx + defICTM[2] * dy + defICTM[4]; + *uy = defICTM[1] * dx + defICTM[3] * dy + defICTM[5]; +} + +void OutputDev::cvtUserToDev(FixedPoint ux, FixedPoint uy, int *dx, int *dy) { + *dx = (int)(defCTM[0] * ux + defCTM[2] * uy + defCTM[4] + 0.5); + *dy = (int)(defCTM[1] * ux + defCTM[3] * uy + defCTM[5] + 0.5); +} + +void OutputDev::updateAll(GfxState *state) { + updateLineDash(state); + updateFlatness(state); + updateLineJoin(state); + updateLineCap(state); + updateMiterLimit(state); + updateLineWidth(state); + updateStrokeAdjust(state); + updateFillColorSpace(state); + updateFillColor(state); + updateStrokeColorSpace(state); + updateStrokeColor(state); + updateBlendMode(state); + updateFillOpacity(state); + updateStrokeOpacity(state); + updateFillOverprint(state); + updateStrokeOverprint(state); + updateTransfer(state); + updateFont(state); +} + +GBool OutputDev::beginType3Char(GfxState *state, FixedPoint x, FixedPoint y, + FixedPoint dx, FixedPoint dy, + CharCode code, Unicode *u, int uLen) { + return gFalse; +} + +void OutputDev::drawImageMask(GfxState *state, Object *ref, Stream *str, + int width, int height, GBool invert, + GBool inlineImg) { + int i, j; + + if (inlineImg) { + str->reset(); + j = height * ((width + 7) / 8); + for (i = 0; i < j; ++i) + str->getChar(); + str->close(); + } +} + +void OutputDev::drawImage(GfxState *state, Object *ref, Stream *str, + int width, int height, GfxImageColorMap *colorMap, + int *maskColors, GBool inlineImg) { + int i, j; + + if (inlineImg) { + str->reset(); + j = height * ((width * colorMap->getNumPixelComps() * + colorMap->getBits() + 7) / 8); + for (i = 0; i < j; ++i) + str->getChar(); + str->close(); + } +} + +void OutputDev::drawMaskedImage(GfxState *state, Object *ref, Stream *str, + int width, int height, + GfxImageColorMap *colorMap, + Stream *maskStr, + int maskWidth, int maskHeight, + GBool maskInvert) { + drawImage(state, ref, str, width, height, colorMap, NULL, gFalse); +} + +void OutputDev::drawSoftMaskedImage(GfxState *state, Object *ref, Stream *str, + int width, int height, + GfxImageColorMap *colorMap, + Stream *maskStr, + int maskWidth, int maskHeight, + GfxImageColorMap *maskColorMap) { + drawImage(state, ref, str, width, height, colorMap, NULL, gFalse); +} + +void OutputDev::endMarkedContent(GfxState *state) { +} + +void OutputDev::beginMarkedContent(char *name) { +} + +void OutputDev::beginMarkedContent(char *name, Dict *properties) { +} + +void OutputDev::markPoint(char *name) { +} + +void OutputDev::markPoint(char *name, Dict *properties) { +} + + +#if OPI_SUPPORT +void OutputDev::opiBegin(GfxState *state, Dict *opiDict) { +} + +void OutputDev::opiEnd(GfxState *state, Dict *opiDict) { +} +#endif + +void OutputDev::startProfile() { + if (profileHash) + delete profileHash; + + profileHash = new GooHash (true); +} + +GooHash *OutputDev::endProfile() { + GooHash *profile = profileHash; + + profileHash = NULL; + + return profile; +} + diff --git a/pool/shard001/C++/0022996_changepassword.cpp b/pool/shard001/C++/0022996_changepassword.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c98e7c69a305bdfcd734588341a8238e47d97120 --- /dev/null +++ b/pool/shard001/C++/0022996_changepassword.cpp @@ -0,0 +1,48 @@ +#include "changepassword.h" +#include "ui_changepassword.h" +#include "client_interfaces.h" +#include "QMessageBox" + +ChangePassword::ChangePassword(QWidget *parent) : + QDialog(parent), + ui(new Ui::ChangePassword) +{ + ui->setupUi(this); +} + +ChangePassword::~ChangePassword() +{ + delete ui; +} + +void ChangePassword::on_pushButton_2_clicked() +{ + close(); +} + +void ChangePassword::on_pushButton_clicked() +{ + auto_iface factory1; + getClassFactory(&factory1); + + auto_iface iUser; + factory1->getAuthManager(&iUser); + + QString passOld= ui->lineEdit->text();//依次读入新老密码 + QString passNew = ui->lineEdit_2->text(); + QString passNew2 = ui->lineEdit_3->text(); + std::string passOld1 = passOld.toStdString(); + std::string passNew1 = passNew.toStdString(); + std::string passNew12 = passNew2.toStdString();//重复输入老密码 + if(passNew1 == passNew12)//两次密码输入比对 + { + if(iUser->changePassword(passOld1.c_str(),passNew1.c_str())) + { + QMessageBox::information(this,"Welcome",u8"密码修改成功"); + close();//成功更改密码之后自动退出 + } + else{QMessageBox::information(this,"Warning",u8"修改密码失败");} + } + else{QMessageBox::information(this,"Warning",u8"两次密码输入不一致");} + +} diff --git a/pool/shard001/C++/0022997_tblWaiting.cc b/pool/shard001/C++/0022997_tblWaiting.cc new file mode 100644 index 0000000000000000000000000000000000000000..32a8c07ca46c9a76f8d3052f2f63ab9a996cf81f --- /dev/null +++ b/pool/shard001/C++/0022997_tblWaiting.cc @@ -0,0 +1,167 @@ +/* + Kvalobs - Free Quality Control Software for Meteorological Observations + + $Id: tblWaiting.cc,v 1.1.6.2 2007/09/27 09:02:23 paule Exp $ + + Copyright (C) 2007 met.no + + Contact information: + Norwegian Meteorological Institute + Box 43 Blindern + 0313 OSLO + NORWAY + email: kvalobs-dev@met.no + + This file is part of KVALOBS + + KVALOBS 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. + + KVALOBS 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 KVALOBS; if not, write to the Free Software Foundation Inc., + 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ +#include +#include +#include +#include +#include +#include "tblWaiting.h" + + +using namespace std; +using namespace miutil; +using namespace dnmi; + +void +TblWaiting:: +createSortIndex() +{ + ostringstream ost; + ost << wmono_ << obstime_.isoTime() << delaytime_.isoTime(); + sortBy_=ost.str(); +} + +void +TblWaiting:: +clean() +{ + wmono_ = 0; + obstime_ = miTime::nowTime(); + delaytime_ = miTime::nowTime(); + + createSortIndex(); +} + + +bool +TblWaiting:: +set(const dnmi::db::DRow &r_) +{ + db::DRow &r=const_cast(r_); + string buf; + list names=r.getFieldNames(); + list::iterator it=names.begin(); + + for(;it!=names.end(); it++){ + try{ + buf=r[*it]; + + if(*it=="wmono"){ + wmono_=atoi(buf.c_str()); + }else if(*it=="obstime"){ + obstime_=miTime(buf); + }else if(*it=="delaytime"){ + delaytime_=miTime(buf); + }else{ + LOGWARN("TblWaiting::set .. unknown entry:" << *it << std::endl); + } + } + catch(...){ + LOGWARN("TblWaiting: unexpected exception ..... \n"); + } + } + + createSortIndex(); + return true; +} + +bool +TblWaiting:: +set(const TblWaiting &s) +{ + wmono_ = s.wmono_; + obstime_ = s.obstime_; + delaytime_ = s.delaytime_; + + createSortIndex(); + + return true; +} + + + +bool +TblWaiting:: +set(int wmono, + const miutil::miTime &obtime, + const miutil::miTime &delaytime) +{ + wmono_ = wmono; + obstime_ = obtime; + delaytime_ = delaytime; + + createSortIndex(); + + return true; +} + +string +TblWaiting:: +toSend() const +{ + ostringstream ost; + + ost << "(" + << wmono_ << "," + << quoted(obstime_.isoTime()) << "," + << quoted(delaytime_.isoTime()) + << ")"; + + return ost.str(); +} + + +string +TblWaiting:: +uniqueKey()const +{ + ostringstream ost; + + ost << " WHERE wmono=" << wmono_ << " AND " + << " obstime=" << quoted(obstime_.isoTime()); + + return ost.str(); +} + + + +string +TblWaiting:: +toUpdate()const +{ + ostringstream ost; + + ost << "SET delaytime=" << quoted(delaytime_.isoTime()) + << " WHERE wmono=" << wmono_ << " AND " + << " obstime=" << quoted(obstime_.isoTime()); + + return ost.str(); +} diff --git a/pool/shard001/C++/0023005_localvariabledock.cpp b/pool/shard001/C++/0023005_localvariabledock.cpp new file mode 100644 index 0000000000000000000000000000000000000000..289c910dc5dee102ee830522a8b459d60b6d0ae3 --- /dev/null +++ b/pool/shard001/C++/0023005_localvariabledock.cpp @@ -0,0 +1,187 @@ +/* + * This file is part of the KDE libraries + * Copyright (C) 2006 Matt Broadstone (mbroadst@gmail.com) + * (C) 2007 Maks Orlovich + * + * 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; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include "localvariabledock.h" +#include "localvariabledock.moc" + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "value2string.h" + +namespace KJSDebugger { + +LocalVariablesDock::LocalVariablesDock(QWidget *parent) + : QDockWidget(i18n("Local Variables"), parent), m_execState(0) +{ + setFeatures(DockWidgetMovable | DockWidgetFloatable); + m_view = new QTreeWidget(this); + + m_view->setColumnCount(2); + + QStringList headers; + headers << i18n("Reference"); + headers << i18n("Value"); + m_view->setHeaderLabels(headers); + + connect(m_view, SIGNAL(itemExpanded(QTreeWidgetItem*)), + this, SLOT (slotItemExpanded(QTreeWidgetItem*))); + + setWidget(m_view); +} + +LocalVariablesDock::~LocalVariablesDock() +{ +} + +void LocalVariablesDock::updateValue(KJS::ExecState* exec, KJS::JSValue* val, + QTreeWidgetItem* item, bool recurse) +{ + // Note: parent is responsible for setting our name.. + item->setText(1, valueToString(val)); + if (recurse) { + if (val->isObject()) + { + updateObjectProperties(exec, val, item); + } + else + { + // It has no kids, so treeview item better not, either + QList kids = item->takeChildren(); + qDeleteAll(kids); + } + } +} + +void LocalVariablesDock::updateObjectProperties(KJS::ExecState* exec, KJS::JSValue* val, + QTreeWidgetItem* item, bool globalObject) +{ + bool root = (item == m_view->invisibleRootItem()); + + // We have to be careful here -- we don't want to recurse if we're not open; + // except for root since we may want the + there + bool recurse = item->isExpanded() || root; + + QStringList props; + KJS::JSObject* obj = 0; + + // Get the list of all relevant properties.. + // Note: val may be null for root case.. + if (val) + { + assert (val->isObject()); + + obj = val->getObject(); + KJS::PropertyNameArray jsProps; + + // We use getOwnPropertyNames and not getPropertyNames here + // to not include things from the prototype + obj->getOwnPropertyNames(exec, jsProps); + + for (int pos = 0; pos < jsProps.size(); ++pos) + { + // For global (window) objects, we only show hash table properties, + // for less cluttered display. + if (globalObject && !obj->getDirect(jsProps[pos])) + continue; + + props.append(jsProps[pos].ustring().qstring()); + } + } + + // If we're not an activation, also list the prototype, as __proto__ + if (val && !val->getObject()->isActivation()) + props << QLatin1String("__proto__"); + + // If we're the root, also pretend 'this' is there. + if (root && exec) + props << QLatin1String("this"); + + // Sort them, to make updates easier. + props.sort(); + + // Do we need more or less nodes? + while (props.size() < item->childCount()) + delete item->takeChild(item->childCount() - 1); + + while (props.size() > item->childCount()) + item->addChild(new QTreeWidgetItem); + + // Update names and values. + for (int pos = 0; pos < props.size(); ++pos) + { + QString propName = props[pos]; + QTreeWidgetItem* kid = item->child(pos); + kid->setText(0, propName); + + if (root && propName == "this") + updateValue(exec, exec->thisValue(), kid, true); + else + updateValue(exec, obj->get(exec, KJS::Identifier(KJS::UString(props[pos]))), kid, recurse); + } +} + +void LocalVariablesDock::slotItemExpanded(QTreeWidgetItem* item) +{ + Q_UNUSED(item); + updateDisplay(m_execState); +} + +void LocalVariablesDock::updateDisplay(KJS::ExecState *exec) +{ + m_execState = exec; + + // Find out out scope object... + KJS::JSObject* scopeObject = 0; + KJS::Context* context =0; + + if (exec) + context = exec->context(); + + // Find the nearest local scope, or + // failing that the topmost scope + if (context) + { + KJS::ScopeChain chain = context->scopeChain(); + for( KJS::ScopeChainIterator iter = chain.begin(); + iter != chain.end(); ++iter) + { + scopeObject = *iter; + if (scopeObject->isActivation()) + break; + } + } + + updateObjectProperties(exec, scopeObject, m_view->invisibleRootItem(), + scopeObject && !scopeObject->isActivation()); +} + +} diff --git a/pool/shard001/C++/0023010_kart_update_protocol.cpp b/pool/shard001/C++/0023010_kart_update_protocol.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6c2f70b6e07109e255e5330923e8c4b8cd9417fb --- /dev/null +++ b/pool/shard001/C++/0023010_kart_update_protocol.cpp @@ -0,0 +1,143 @@ +#include "network/protocols/kart_update_protocol.hpp" + +#include "karts/abstract_kart.hpp" +#include "karts/controller/controller.hpp" +#include "modes/world.hpp" +#include "network/event.hpp" +#include "network/network_config.hpp" +#include "network/protocol_manager.hpp" +#include "utils/time.hpp" + +KartUpdateProtocol::KartUpdateProtocol() : Protocol(PROTOCOL_KART_UPDATE) +{ + // Allocate arrays to store one position and rotation for each kart + // (which is the update information from the server to the client). + m_next_positions.resize(World::getWorld()->getNumKarts()); + m_next_quaternions.resize(World::getWorld()->getNumKarts()); + + // This flag keeps track if valid data for an update is in + // the arrays + m_was_updated = false; +} // KartUpdateProtocol + +// ---------------------------------------------------------------------------- +KartUpdateProtocol::~KartUpdateProtocol() +{ +} // ~KartUpdateProtocol + +// ---------------------------------------------------------------------------- +void KartUpdateProtocol::setup() +{ +} // setup + +// ---------------------------------------------------------------------------- +/** Store the update events in the queue. Since the events are handled in the + * synchronous notify function, there is no lock necessary to + */ +bool KartUpdateProtocol::notifyEvent(Event* event) +{ + if (event->getType() != EVENT_TYPE_MESSAGE) + return true; + NetworkString &ns = event->data(); + if (ns.size() < 33) + { + Log::info("KartUpdateProtocol", "Message too short."); + return true; + } + float time = ns.getFloat(); + while(ns.size() >= 29) + { + uint8_t kart_id = ns.getUInt8(); + Vec3 xyz = ns.getVec3(); + btQuaternion quat = ns.getQuat(); + m_next_positions [kart_id] = xyz; + m_next_quaternions[kart_id] = quat; + } // while ns.size()>29 + + // Set the flag that a new update was received + m_was_updated = true; + return true; +} // notifyEvent + +// ---------------------------------------------------------------------------- +/** Sends regular update events from the server to all clients and from the + * clients to the server (FIXME - is that actually necessary??) + * Then it applies all update events that have been received in notifyEvent. + * This two-part implementation means that if the server should send two + * or more updates before this client handles them, only the last one will + * actually be handled (i.e. outdated kart position updates are discarded). + */ +void KartUpdateProtocol::update(float dt) +{ + if (!World::getWorld()) + return; + static double time = 0; + double current_time = StkTime::getRealTime(); + if (current_time > time + 0.1) // 10 updates per second + { + time = current_time; + if (NetworkConfig::get()->isServer()) + { + World *world = World::getWorld(); + NetworkString *ns = getNetworkString(4+world->getNumKarts()*29); + ns->setSynchronous(true); + ns->addFloat( world->getTime() ); + for (unsigned int i = 0; i < world->getNumKarts(); i++) + { + AbstractKart* kart = world->getKart(i); + Vec3 xyz = kart->getXYZ(); + ns->addUInt8( kart->getWorldKartId()); + ns->add(xyz).add(kart->getRotation()); + Log::verbose("KartUpdateProtocol", + "Sending %d's positions %f %f %f", + kart->getWorldKartId(), xyz[0], xyz[1], xyz[2]); + } + sendMessageToPeersChangingToken(ns, /*reliable*/false); + delete ns; + } + else + { + NetworkString *ns = + getNetworkString(4+29*race_manager->getNumLocalPlayers()); + ns->setSynchronous(true); + ns->addFloat(World::getWorld()->getTime()); + for(unsigned int i=0; igetNumLocalPlayers(); i++) + { + AbstractKart *kart = World::getWorld()->getLocalPlayerKart(i); + const Vec3 &xyz = kart->getXYZ(); + ns->addUInt8(kart->getWorldKartId()); + ns->add(xyz).add(kart->getRotation()); + Log::verbose("KartUpdateProtocol", + "Sending %d's positions %f %f %f", + kart->getWorldKartId(), xyz[0], xyz[1], xyz[2]); + } + sendToServer(ns, /*reliable*/false); + delete ns; + } // if server + } // if (current_time > time + 0.1) + + + // Now handle all update events that have been received. + // There is no lock necessary, since receiving new positions is done in + // notifyEvent, which is called from the same thread that calls this + // function. + if(m_was_updated) + { + for (unsigned id = 0; id < m_next_positions.size(); id++) + { + AbstractKart *kart = World::getWorld()->getKart(id); + if (!kart->getController()->isLocalPlayerController()) + { + btTransform transform = kart->getBody() + ->getInterpolationWorldTransform(); + transform.setOrigin(m_next_positions[id]); + transform.setRotation(m_next_quaternions[id]); + kart->getBody()->setCenterOfMassTransform(transform); + Log::verbose("KartUpdateProtocol", "Update kart %i pos", + id); + } // if not local player + } // for id < num_karts + m_was_updated = false; // mark that all updates were applied + } // if m_was_updated +} // update + diff --git a/pool/shard001/C++/0023011_DatabaseThread.cpp b/pool/shard001/C++/0023011_DatabaseThread.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9ee6e7e0ba7db05d78bdcb76e281a4ef9444f7cc --- /dev/null +++ b/pool/shard001/C++/0023011_DatabaseThread.cpp @@ -0,0 +1,176 @@ +/* + * Copyright (C) 2007, 2008, 2013 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. + * 3. Neither the name of Apple Computer, Inc. ("Apple") 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 APPLE 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 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 "modules/webdatabase/DatabaseThread.h" + +#include "modules/webdatabase/Database.h" +#include "modules/webdatabase/DatabaseTask.h" +#include "modules/webdatabase/SQLTransactionClient.h" +#include "modules/webdatabase/SQLTransactionCoordinator.h" +#include "platform/Logging.h" +#include "platform/ThreadSafeFunctional.h" +#include "platform/WebThreadSupportingGC.h" +#include "public/platform/Platform.h" +#include "wtf/MainThread.h" + +namespace blink { + +DatabaseThread::DatabaseThread() + : m_transactionClient(adoptPtr(new SQLTransactionClient())) + , m_transactionCoordinator(new SQLTransactionCoordinator()) + , m_cleanupSync(nullptr) + , m_terminationRequested(false) +{ +} + +DatabaseThread::~DatabaseThread() +{ + ASSERT(m_openDatabaseSet.isEmpty()); + ASSERT(!m_thread); +} + +DEFINE_TRACE(DatabaseThread) +{ + visitor->trace(m_openDatabaseSet); + visitor->trace(m_transactionCoordinator); +} + +void DatabaseThread::start() +{ + ASSERT(isMainThread()); + if (m_thread) + return; + m_thread = WebThreadSupportingGC::create("WebCore: Database"); + m_thread->postTask(BLINK_FROM_HERE, threadSafeBind(&DatabaseThread::setupDatabaseThread, this)); +} + +void DatabaseThread::setupDatabaseThread() +{ + m_thread->initialize(); +} + +void DatabaseThread::terminate() +{ + ASSERT(isMainThread()); + TaskSynchronizer sync; + { + MutexLocker lock(m_terminationRequestedMutex); + ASSERT(!m_terminationRequested); + m_terminationRequested = true; + m_cleanupSync = &sync; + WTF_LOG(StorageAPI, "DatabaseThread %p was asked to terminate\n", this); + m_thread->postTask(BLINK_FROM_HERE, threadSafeBind(&DatabaseThread::cleanupDatabaseThread, this)); + } + sync.waitForTaskCompletion(); + // The WebThread destructor blocks until all the tasks of the database + // thread are processed. However, it shouldn't block at all because + // the database thread has already finished processing the cleanup task. + m_thread.clear(); +} + +void DatabaseThread::cleanupDatabaseThread() +{ + WTF_LOG(StorageAPI, "Cleaning up DatabaseThread %p", this); + + // Clean up the list of all pending transactions on this database thread + m_transactionCoordinator->shutdown(); + + // Close the databases that we ran transactions on. This ensures that if any transactions are still open, they are rolled back and we don't leave the database in an + // inconsistent or locked state. + if (m_openDatabaseSet.size() > 0) { + // As the call to close will modify the original set, we must take a copy to iterate over. + HeapHashSet> openSetCopy; + openSetCopy.swap(m_openDatabaseSet); + HeapHashSet>::iterator end = openSetCopy.end(); + for (HeapHashSet>::iterator it = openSetCopy.begin(); it != end; ++it) + (*it)->close(); + } + m_openDatabaseSet.clear(); + + m_thread->postTask(BLINK_FROM_HERE, WTF::bind(&DatabaseThread::cleanupDatabaseThreadCompleted, this)); +} + +void DatabaseThread::cleanupDatabaseThreadCompleted() +{ + m_thread->shutdown(); + if (m_cleanupSync) // Someone wanted to know when we were done cleaning up. + m_cleanupSync->taskCompleted(); +} + +void DatabaseThread::recordDatabaseOpen(Database* database) +{ + ASSERT(isDatabaseThread()); + ASSERT(database); + ASSERT(!m_openDatabaseSet.contains(database)); + MutexLocker lock(m_terminationRequestedMutex); + if (!m_terminationRequested) + m_openDatabaseSet.add(database); +} + +void DatabaseThread::recordDatabaseClosed(Database* database) +{ + ASSERT(isDatabaseThread()); + ASSERT(database); +#if ENABLE(ASSERT) + { + MutexLocker lock(m_terminationRequestedMutex); + ASSERT(m_terminationRequested || m_openDatabaseSet.contains(database)); + } +#endif + m_openDatabaseSet.remove(database); +} + +bool DatabaseThread::isDatabaseOpen(Database* database) +{ + ASSERT(isDatabaseThread()); + ASSERT(database); + MutexLocker lock(m_terminationRequestedMutex); + return !m_terminationRequested && m_openDatabaseSet.contains(database); +} + +bool DatabaseThread::isDatabaseThread() const +{ + // This function is called only from the main thread or the database + // thread. If we are not in the main thread, we are in the database thread. + return !isMainThread(); +} + +void DatabaseThread::scheduleTask(PassOwnPtr task) +{ + ASSERT(m_thread); +#if ENABLE(ASSERT) + { + MutexLocker lock(m_terminationRequestedMutex); + ASSERT(!m_terminationRequested); + } +#endif + // WebThread takes ownership of the task. + m_thread->postTask(BLINK_FROM_HERE, threadSafeBind(&DatabaseTask::run, task)); +} + +} // namespace blink diff --git a/pool/shard001/C++/0023018_trace_test.cpp b/pool/shard001/C++/0023018_trace_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f4ef07e02a02da3410bd2266fbf080663ea71e2a --- /dev/null +++ b/pool/shard001/C++/0023018_trace_test.cpp @@ -0,0 +1,42 @@ +#ifdef STAN_OPENCL +#include +#include +#include +#include + +auto trace_functor = [](const auto& a) { return stan::math::trace(a); }; + +TEST(OpenCLTrace, prim_rev_values_small) { + int N = 2; + int M = 3; + + Eigen::MatrixXd a(N, M); + a << 1, 2, 3, 4, 5, 6; + stan::math::test::compare_cpu_opencl_prim_rev(trace_functor, a); +} + +TEST(OpenCLTrace, prim_rev_values_zero_rows) { + int N = 0; + int M = 3; + + Eigen::MatrixXd a(N, M); + stan::math::test::compare_cpu_opencl_prim_rev(trace_functor, a); +} + +TEST(OpenCLTrace, prim_rev_values_zero_cols) { + int N = 2; + int M = 0; + + Eigen::MatrixXd a(N, M); + stan::math::test::compare_cpu_opencl_prim_rev(trace_functor, a); +} + +TEST(OpenCLTrace, prim_rev_values_large) { + int N = 71; + int M = 83; + + Eigen::MatrixXd a = Eigen::MatrixXd::Random(N, M); + stan::math::test::compare_cpu_opencl_prim_rev(trace_functor, a); +} + +#endif diff --git a/pool/shard001/C++/0023025_Func_k80.cpp b/pool/shard001/C++/0023025_Func_k80.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d9521e9d9b374bc1e4ef0e72268cafc30f95627e --- /dev/null +++ b/pool/shard001/C++/0023025_Func_k80.cpp @@ -0,0 +1,115 @@ +#include "Func_k80.h" +#include "K80RateMatrixFunction.h" +#include "RateMatrix_Kimura80.h" +#include "Real.h" +#include "RealPos.h" +#include "RlDeterministicNode.h" +#include "RlRateMatrix.h" +#include "RlSimplex.h" +#include "TypedDagNode.h" + +using namespace RevLanguage; + +/** default constructor */ +Func_k80::Func_k80( void ) : TypedFunction( ) +{ + +} + + +/** + * The clone function is a convenience function to create proper copies of inherited objected. + * E.g. a.clone() will create a clone of the correct type even if 'a' is of derived type 'b'. + * + * \return A new copy of the process. + */ +Func_k80* Func_k80::clone( void ) const +{ + + return new Func_k80( *this ); +} + + +RevBayesCore::TypedFunction< RevBayesCore::RateGenerator >* Func_k80::createFunction( void ) const +{ + + RevBayesCore::TypedDagNode< double >* ka = static_cast( this->args[0].getVariable()->getRevObject() ).getDagNode(); + + RevBayesCore::K80RateMatrixFunction* f = new RevBayesCore::K80RateMatrixFunction( ka ); + + return f; +} + + +/* Get argument rules */ +const ArgumentRules& Func_k80::getArgumentRules( void ) const +{ + + static ArgumentRules argumentRules = ArgumentRules(); + static bool rules_set = false; + + if ( !rules_set ) + { + + argumentRules.push_back( new ArgumentRule( "kappa" , RealPos::getClassTypeSpec(), "The transition/transversion rate.", ArgumentRule::BY_CONSTANT_REFERENCE, ArgumentRule::ANY ) ); + + rules_set = true; + } + + return argumentRules; +} + + +const std::string& Func_k80::getClassType(void) +{ + + static std::string rev_type = "Func_k80"; + + return rev_type; +} + + +/* Get class type spec describing type of object */ +const TypeSpec& Func_k80::getClassTypeSpec(void) +{ + + static TypeSpec rev_type_spec = TypeSpec( getClassType(), new TypeSpec( Function::getClassTypeSpec() ) ); + + return rev_type_spec; +} + + +/** + * Get the alternative Rev names (aliases) for the function. + * + * \return Rev aliases of constructor function. + */ +std::vector Func_k80::getFunctionNameAliases( void ) const +{ + // create alternative constructor function names variable that is the same for all instance of this class + std::vector a_names; + a_names.push_back( "fnKimura80" ); + + return a_names; +} + + +/** + * Get the primary Rev name for this function. + */ +std::string Func_k80::getFunctionName( void ) const +{ + // create a name variable that is the same for all instance of this class + std::string f_name = "fnK80"; + + return f_name; +} + + +const TypeSpec& Func_k80::getTypeSpec( void ) const +{ + + static TypeSpec type_spec = getClassTypeSpec(); + + return type_spec; +} diff --git a/pool/shard001/C++/0023032_Controller.cpp b/pool/shard001/C++/0023032_Controller.cpp new file mode 100644 index 0000000000000000000000000000000000000000..53f9b40349b5f876f015fd7d25c2de491e602dbe --- /dev/null +++ b/pool/shard001/C++/0023032_Controller.cpp @@ -0,0 +1,157 @@ +/* + * PythonBot - A game by a developer for developers. + * Copyright (C) 2015-2021 Jean-Marie BARAN (jeanmarie.baran@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 . + * + * Refer to 'LICENSE.txt' for the full notice. + */ + +#include "Controller.h" + +Controller::Controller(Model &model, View &view, bool startPaused) + : m_startPaused(startPaused), m_model(model), m_view(view) {} + +void Controller::loop() { + bool gameFinished(false), paused(m_startPaused); + + while (!gameFinished) { + // Deal with all events. + switch (m_view.read_events()) { + case View::REQUEST_QUIT: // Request to quit the game. + gameFinished = true; + break; + case View::REQUEST_PAUSE: // Request to pause/unpause the game. + paused = !paused; + break; + default: // No request made. + break; + } + + // Draw the scene. + m_view.draw(m_model.get_circles()); + m_view.draw(m_model.get_dead_bots()); + m_view.draw(m_model.get_alive_bots()); + m_view.draw(m_model.get_bullets()); + m_view.draw(m_model.get_scans()); + if (paused) + m_view.draw_pause(); + m_view.render(); + + if (!paused) { + // Manage bullets. + update_bullets(); + + // Manage bots. + update_bots(); + } + } +} + +void Controller::update_bullets() { + Bullet *bullet(0); + Bot *bot(0); + sf::Vector2f hitPoint; + for (unsigned int i(0); i < m_model.get_bullets().size(); i++) { + // Get a direct pointer for convenience. + bullet = (Bullet *)m_model.get_bullets()[i]; + + if (m_model.collides(bullet, hitPoint)) { + // Collision with circles and world' boundaries. + m_view.add_explosion(hitPoint); + m_model.erase_bullet(i); + } else if (m_model.collides(bullet, &bot, hitPoint)) { + // Collision with bots. + m_view.add_explosion(hitPoint); + m_model.inflict_damages(bot); + if (!bot->is_alive()) { + bullet->get_bot_origin()->add_kill(); + m_view.add_bot_explosion(bot->get_position()); + } + m_model.erase_bullet(i); + } else { + // Update position. + bullet->move(); + } + } +} + +void Controller::update_bots() { + // Loop over all the bots. + Bot *bot(0); + sf::Vector2f hitPoint; + // See bot death below for the cast. + for (int i(0); i < (int)m_model.get_alive_bots().size(); i++) { + // Get a direct pointer for convenience. + bot = (Bot *)m_model.get_alive_bots()[i]; + + // Get and manage the request of each bot. + BotConnector::Request const &request(bot->get_connector().get_request()); + unsigned int circlesCount(0), botsCount(0), + bulletsCount(0); // Results for a scan. + switch (request.type) { + case BotConnector::SKIP: // The bot asked to skip its turn. + bot->get_connector().answer_request( + bot->get_health(), bot->get_bullets_left(), bot->get_num_kills()); + break; + case BotConnector::MOVE: // The bot asked to move forward. + bot->move(); + bot->get_connector().answer_request( + bot->get_health(), bot->get_bullets_left(), bot->get_num_kills()); + break; + case BotConnector::ROTATE: // The bot asked to be rotated. + bot->rotate(request.rotationDegrees); + bot->get_connector().answer_request( + bot->get_health(), bot->get_bullets_left(), bot->get_num_kills()); + break; + case BotConnector::FIRE: // The bot asked to fire a bullet. + if (bot->get_bullets_left() > 0) + m_model.fire_bullet(bot); + bot->get_connector().answer_request( + bot->get_health(), bot->get_bullets_left(), bot->get_num_kills()); + break; + case BotConnector::SCAN: // The bot asked a scan. + bot->set_scan(request.scanDistance, request.scanRadius); + m_model.scan(bot, request.scanCircles, circlesCount, request.scanBots, + botsCount, request.scanBullets, bulletsCount); + bot->get_connector().answer_scan_request( + bot->get_health(), bot->get_bullets_left(), bot->get_num_kills(), + circlesCount, botsCount, bulletsCount); + break; + default: // The bot did not ask for anything. + break; + } + + // Manage collisions. + Bot *botCollision(0); + if (m_model.collides(bot, &botCollision, hitPoint)) { + m_view.add_explosion(hitPoint); + m_model.inflict_damages(bot); + if (!bot->is_alive()) { + if (botCollision != 0) { + /* If the bot collides with another bot and not the world, add a kill + * to this other bot. */ + botCollision->add_kill(); + } + m_view.add_bot_explosion(bot->get_position()); + /* If the bot has been removed from the vector (dead), the next bot will + * be on the current index. */ + i--; + } + } + + // Load new bullets. + bot->load_bullet(); + } +} \ No newline at end of file diff --git a/pool/shard001/C++/0023035_GpioInput.cpp b/pool/shard001/C++/0023035_GpioInput.cpp new file mode 100644 index 0000000000000000000000000000000000000000..91aee6495362501e532abccfb12f837b8cbe8481 --- /dev/null +++ b/pool/shard001/C++/0023035_GpioInput.cpp @@ -0,0 +1,182 @@ +#include +#include +#include +#include + +#include "GpioInput.h" + + +/**************************************************************************** + * + * GpioInputCallbackData Class + * + **************************************************************************** + */ +GpioInputCallbackData::GpioInputCallbackData( InputChangeCallback callback, + void *userData, + unsigned int flags) + : Callback(callback), + UserData(userData), + Flags(flags), + IsDirty(true), + IoValue(0) +{} + + +void +GpioInputCallbackData::Execute(int ioValue) +{ + if (IsDirty){ + IoValue = ioValue; + IsDirty = false; + Callback(ioValue, UserData); + } + else if (IoValue != ioValue){ + IoValue = ioValue; + Callback(ioValue, UserData); + } +} + + + +/**************************************************************************** + * + * GpioInput Class + * + **************************************************************************** + */ +bool +GpioInput::Read() +{ + int fd; + int bytes_read; + char Buffer[3] = {0}; + + fd = open(ValuePath, O_RDONLY); + if (fd < 0){ + LogMessage( "Failed %s Read open(%s) - pin %d", + Name, ValuePath, PinNumber); + return false; + } + + bytes_read = read(fd, Buffer, sizeof(Buffer)); + + close(fd); + + if (bytes_read <= 0){ + LogMessage( "Failed %s Read read(%s) = %d - pin %d", + Name, ValuePath, bytes_read, PinNumber); + return false; + } + + IoValue = atoi(Buffer); + + return true; +} + + + +bool +GpioInput::SetDirection() +{ + //------------------------------ + int fd; + int rc; + const char *InString = "in\n"; + //------------------------------ + + fd = open(DirectionPath, O_WRONLY); + if (fd < 0){ + LogMessage( "Failed %s SetDirection open(%s) - pin %d", + Name, DirectionPath, PinNumber); + return false; + } + + rc = write(fd, InString, 4); + + close(fd); + + if (rc != 4){ + LogMessage( "Failed %s SetDirection write(%s, %s) - pin %d", + Name, DirectionPath, InString, PinNumber); + return false; + } + else{ + return true; + } +} + + + +GpioInput::GpioInput() + : Gpio(), + CallbackCount(0) +{} + + + +void +GpioInput::AddCallback(GpioInputCallbackData *CallbackData) +{ + CallbackList.push_front(CallbackData); + CallbackCount++; +} + + + +void +GpioInput::Execute() +{ + if (CallbackCount){ + + bool Success = Read(); + + if (!Success){ + IoValue = -1; + } + + for (list::iterator it = CallbackList.begin(); + it != CallbackList.end(); + ++it){ + + GpioInputCallbackData *Callback = *it; + Callback->Execute(IoValue); + } + } +} + + + +void +GpioInput::ToString() +{ + printf("%s\n\tPin: %d\n\tActiveLow: %d\n" + "\tValue: %s\n" + "\tDirection: %s\n" + "\tActiveLow: %s\n", + Name, + PinNumber, + ActiveLow, + ValuePath, + DirectionPath, + ActiveLowPath); +} + + + +void +GpioInput::LogString() +{ + LogMessage("%s\n\tPin: %d\n\tActiveLow: %d\n" + "\tValue: %s\n" + "\tDirection: %s\n" + "\tActiveLow: %s\n", + Name, + PinNumber, + ActiveLow, + ValuePath, + DirectionPath, + ActiveLowPath); +} + + diff --git a/pool/shard001/C++/0023037_ModelPackageGroupStatus.cpp b/pool/shard001/C++/0023037_ModelPackageGroupStatus.cpp new file mode 100644 index 0000000000000000000000000000000000000000..500ac090482630381358bbbf2d1eb977a01bdad7 --- /dev/null +++ b/pool/shard001/C++/0023037_ModelPackageGroupStatus.cpp @@ -0,0 +1,98 @@ +/** + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0. + */ + +#include +#include +#include +#include + +using namespace Aws::Utils; + + +namespace Aws +{ + namespace SageMaker + { + namespace Model + { + namespace ModelPackageGroupStatusMapper + { + + static const int Pending_HASH = HashingUtils::HashString("Pending"); + static const int InProgress_HASH = HashingUtils::HashString("InProgress"); + static const int Completed_HASH = HashingUtils::HashString("Completed"); + static const int Failed_HASH = HashingUtils::HashString("Failed"); + static const int Deleting_HASH = HashingUtils::HashString("Deleting"); + static const int DeleteFailed_HASH = HashingUtils::HashString("DeleteFailed"); + + + ModelPackageGroupStatus GetModelPackageGroupStatusForName(const Aws::String& name) + { + int hashCode = HashingUtils::HashString(name.c_str()); + if (hashCode == Pending_HASH) + { + return ModelPackageGroupStatus::Pending; + } + else if (hashCode == InProgress_HASH) + { + return ModelPackageGroupStatus::InProgress; + } + else if (hashCode == Completed_HASH) + { + return ModelPackageGroupStatus::Completed; + } + else if (hashCode == Failed_HASH) + { + return ModelPackageGroupStatus::Failed; + } + else if (hashCode == Deleting_HASH) + { + return ModelPackageGroupStatus::Deleting; + } + else if (hashCode == DeleteFailed_HASH) + { + return ModelPackageGroupStatus::DeleteFailed; + } + EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); + if(overflowContainer) + { + overflowContainer->StoreOverflow(hashCode, name); + return static_cast(hashCode); + } + + return ModelPackageGroupStatus::NOT_SET; + } + + Aws::String GetNameForModelPackageGroupStatus(ModelPackageGroupStatus enumValue) + { + switch(enumValue) + { + case ModelPackageGroupStatus::Pending: + return "Pending"; + case ModelPackageGroupStatus::InProgress: + return "InProgress"; + case ModelPackageGroupStatus::Completed: + return "Completed"; + case ModelPackageGroupStatus::Failed: + return "Failed"; + case ModelPackageGroupStatus::Deleting: + return "Deleting"; + case ModelPackageGroupStatus::DeleteFailed: + return "DeleteFailed"; + default: + EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); + if(overflowContainer) + { + return overflowContainer->RetrieveOverflow(static_cast(enumValue)); + } + + return {}; + } + } + + } // namespace ModelPackageGroupStatusMapper + } // namespace Model + } // namespace SageMaker +} // namespace Aws diff --git a/pool/shard001/C++/0023039_values.cpp b/pool/shard001/C++/0023039_values.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0f2fd48d73837ad6a2c7903be1314d7336198fb3 --- /dev/null +++ b/pool/shard001/C++/0023039_values.cpp @@ -0,0 +1,131 @@ +#include "sass.hpp" +#include "sass.h" +#include "values.hpp" + +#include + +namespace Sass { + + // convert value from C++ side to C-API + union Sass_Value* ast_node_to_sass_value (const Expression_Ptr val) + { + if (val->concrete_type() == Expression::NUMBER) + { + Number_Ptr_Const res = Cast(val); + return sass_make_number(res->value(), res->unit().c_str()); + } + else if (val->concrete_type() == Expression::COLOR) + { + Color_Ptr_Const col = Cast(val); + return sass_make_color(col->r(), col->g(), col->b(), col->a()); + } + else if (val->concrete_type() == Expression::LIST) + { + List_Ptr_Const l = Cast(val); + union Sass_Value* list = sass_make_list(l->size(), l->separator(), l->is_bracketed()); + for (size_t i = 0, L = l->length(); i < L; ++i) { + Expression_Obj obj = l->at(i); + auto val = ast_node_to_sass_value(obj); + sass_list_set_value(list, i, val); + } + return list; + } + else if (val->concrete_type() == Expression::MAP) + { + Map_Ptr_Const m = Cast(val); + union Sass_Value* map = sass_make_map(m->length()); + size_t i = 0; for (Expression_Obj key : m->keys()) { + sass_map_set_key(map, i, ast_node_to_sass_value(key)); + sass_map_set_value(map, i, ast_node_to_sass_value(m->at(key))); + ++ i; + } + return map; + } + else if (val->concrete_type() == Expression::NULL_VAL) + { + return sass_make_null(); + } + else if (val->concrete_type() == Expression::BOOLEAN) + { + Boolean_Ptr_Const res = Cast(val); + return sass_make_boolean(res->value()); + } + else if (val->concrete_type() == Expression::STRING) + { + if (String_Quoted_Ptr_Const qstr = Cast(val)) + { + return sass_make_qstring(qstr->value().c_str()); + } + else if (String_Constant_Ptr_Const cstr = Cast(val)) + { + return sass_make_string(cstr->value().c_str()); + } + } + return sass_make_error("unknown sass value type"); + } + + // convert value from C-API to C++ side + Value_Ptr sass_value_to_ast_node (const union Sass_Value* val) + { + switch (sass_value_get_tag(val)) { + case SASS_NUMBER: + return SASS_MEMORY_NEW(Number, + ParserState("[C-VALUE]"), + sass_number_get_value(val), + sass_number_get_unit(val)); + case SASS_BOOLEAN: + return SASS_MEMORY_NEW(Boolean, + ParserState("[C-VALUE]"), + sass_boolean_get_value(val)); + case SASS_COLOR: + return SASS_MEMORY_NEW(Color, + ParserState("[C-VALUE]"), + sass_color_get_r(val), + sass_color_get_g(val), + sass_color_get_b(val), + sass_color_get_a(val)); + case SASS_STRING: + if (sass_string_is_quoted(val)) { + return SASS_MEMORY_NEW(String_Quoted, + ParserState("[C-VALUE]"), + sass_string_get_value(val)); + } + return SASS_MEMORY_NEW(String_Constant, + ParserState("[C-VALUE]"), + sass_string_get_value(val)); + case SASS_LIST: { + List_Ptr l = SASS_MEMORY_NEW(List, + ParserState("[C-VALUE]"), + sass_list_get_length(val), + sass_list_get_separator(val)); + for (size_t i = 0, L = sass_list_get_length(val); i < L; ++i) { + l->append(sass_value_to_ast_node(sass_list_get_value(val, i))); + } + l->is_bracketed(sass_list_get_is_bracketed(val)); + return l; + } + case SASS_MAP: { + Map_Ptr m = SASS_MEMORY_NEW(Map, ParserState("[C-VALUE]")); + for (size_t i = 0, L = sass_map_get_length(val); i < L; ++i) { + *m << std::make_pair( + sass_value_to_ast_node(sass_map_get_key(val, i)), + sass_value_to_ast_node(sass_map_get_value(val, i))); + } + return m; + } + case SASS_NULL: + return SASS_MEMORY_NEW(Null, ParserState("[C-VALUE]")); + case SASS_ERROR: + return SASS_MEMORY_NEW(Custom_Error, + ParserState("[C-VALUE]"), + sass_error_get_message(val)); + case SASS_WARNING: + return SASS_MEMORY_NEW(Custom_Warning, + ParserState("[C-VALUE]"), + sass_warning_get_message(val)); + default: break; + } + return 0; + } + +} diff --git a/pool/shard001/C++/0023048_vcxypadfixtureeditor.cpp b/pool/shard001/C++/0023048_vcxypadfixtureeditor.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9f559906f66f06d31688e20b8e52b701a030517d --- /dev/null +++ b/pool/shard001/C++/0023048_vcxypadfixtureeditor.cpp @@ -0,0 +1,112 @@ +/* + Q Light Controller + vcxypadfixture.cpp + + Copyright (c) Heikki Junnila + + 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. The license is + in the file "COPYING". + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +*/ + +#include +#include +#include +#include +#include + +#include "vcxypadfixtureeditor.h" +#include "vcxypadfixture.h" + +/***************************************************************************** + * Initialization + *****************************************************************************/ + +VCXYPadFixtureEditor::VCXYPadFixtureEditor(QWidget* parent, + QList fixtures) : QDialog(parent) +{ + setupUi(this); + + m_fixtures = fixtures; + + /* Take initial values from the first fixture */ + if (fixtures.count() > 0) + { + VCXYPadFixture fxi = fixtures.first(); + + m_xMin->setValue(int(floor((fxi.xMin() * qreal(100)) + qreal(0.5)))); + m_xMax->setValue(int(floor((fxi.xMax() * qreal(100)) + qreal(0.5)))); + m_xReverse->setChecked(fxi.xReverse()); + + m_yMin->setValue(int(floor((fxi.yMin() * qreal(100)) + qreal(0.5)))); + m_yMax->setValue(int(floor((fxi.yMax() * qreal(100)) + qreal(0.5)))); + m_yReverse->setChecked(fxi.yReverse()); + } +} + +VCXYPadFixtureEditor::~VCXYPadFixtureEditor() +{ +} + +void VCXYPadFixtureEditor::slotXMinChanged(int value) +{ + if (value >= m_xMax->value()) + m_xMax->setValue(value + 1); +} + +void VCXYPadFixtureEditor::slotXMaxChanged(int value) +{ + if (value <= m_xMin->value()) + m_xMin->setValue(value - 1); +} + +void VCXYPadFixtureEditor::slotYMinChanged(int value) +{ + if (value >= m_yMax->value()) + m_yMax->setValue(value + 1); +} + +void VCXYPadFixtureEditor::slotYMaxChanged(int value) +{ + if (value <= m_yMin->value()) + m_yMin->setValue(value - 1); +} + +void VCXYPadFixtureEditor::accept() +{ + /* Put dialog values to all fixtures */ + QMutableListIterator it(m_fixtures); + while (it.hasNext() == true) + { + VCXYPadFixture fxi(it.next()); + + fxi.setX(qreal(m_xMin->value()) / qreal(100), qreal(m_xMax->value()) / qreal(100), + m_xReverse->isChecked()); + fxi.setY(qreal(m_yMin->value()) / qreal(100), qreal(m_yMax->value()) / qreal(100), + m_yReverse->isChecked()); + + it.setValue(fxi); + } + + QDialog::accept(); +} + +/**************************************************************************** + * Fixtures + ****************************************************************************/ + +QList VCXYPadFixtureEditor::fixtures() const +{ + return m_fixtures; +} + diff --git a/pool/shard001/C++/0023049_listnamedqueriesresponse.cpp b/pool/shard001/C++/0023049_listnamedqueriesresponse.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ae2a41bc4f76aa8bd394d87dc11c55820f9c4bd3 --- /dev/null +++ b/pool/shard001/C++/0023049_listnamedqueriesresponse.cpp @@ -0,0 +1,118 @@ +/* + 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 "listnamedqueriesresponse.h" +#include "listnamedqueriesresponse_p.h" + +#include +#include +#include + +namespace QtAws { +namespace Athena { + +/*! + * \class QtAws::Athena::ListNamedQueriesResponse + * \brief The ListNamedQueriesResponse class provides an interace for Athena ListNamedQueries responses. + * + * \inmodule QtAwsAthena + * + * Amazon Athena is an interactive query service that lets you use standard SQL to analyze data directly in Amazon S3. You + * can point Athena at your data in Amazon S3 and run ad-hoc queries and get results in seconds. Athena is serverless, so + * there is no infrastructure to set up or manage. You pay only for the queries you run. Athena scales + * automatically—executing queries in parallel—so results are fast, even with large datasets and complex queries. For more + * information, see What is Amazon Athena in the + * Amazon Athena User + * + * Guide> + * + * If you connect to Athena using the JDBC driver, use version 1.1.0 of the driver or later with the Amazon Athena API. + * Earlier version drivers do not support the API. For more information and to download the driver, see Accessing Amazon Athena with + * + * JDBC> + * + * For code samples using the AWS SDK for Java, see Examples and Code Samples in the Amazon + * Athena User + * + * \sa AthenaClient::listNamedQueries + */ + +/*! + * Constructs a ListNamedQueriesResponse object for \a reply to \a request, with parent \a parent. + */ +ListNamedQueriesResponse::ListNamedQueriesResponse( + const ListNamedQueriesRequest &request, + QNetworkReply * const reply, + QObject * const parent) + : AthenaResponse(new ListNamedQueriesResponsePrivate(this), parent) +{ + setRequest(new ListNamedQueriesRequest(request)); + setReply(reply); +} + +/*! + * \reimp + */ +const ListNamedQueriesRequest * ListNamedQueriesResponse::request() const +{ + Q_D(const ListNamedQueriesResponse); + return static_cast(d->request); +} + +/*! + * \reimp + * Parses a successful Athena ListNamedQueries \a response. + */ +void ListNamedQueriesResponse::parseSuccess(QIODevice &response) +{ + //Q_D(ListNamedQueriesResponse); + QXmlStreamReader xml(&response); + /// @todo +} + +/*! + * \class QtAws::Athena::ListNamedQueriesResponsePrivate + * \brief The ListNamedQueriesResponsePrivate class provides private implementation for ListNamedQueriesResponse. + * \internal + * + * \inmodule QtAwsAthena + */ + +/*! + * Constructs a ListNamedQueriesResponsePrivate object with public implementation \a q. + */ +ListNamedQueriesResponsePrivate::ListNamedQueriesResponsePrivate( + ListNamedQueriesResponse * const q) : AthenaResponsePrivate(q) +{ + +} + +/*! + * Parses a Athena ListNamedQueries response element from \a xml. + */ +void ListNamedQueriesResponsePrivate::parseListNamedQueriesResponse(QXmlStreamReader &xml) +{ + Q_ASSERT(xml.name() == QLatin1String("ListNamedQueriesResponse")); + Q_UNUSED(xml) ///< @todo +} + +} // namespace Athena +} // namespace QtAws diff --git a/pool/shard001/C++/0023068_scu_bcs_2_307_test.cc b/pool/shard001/C++/0023068_scu_bcs_2_307_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..b8de5b34ef0e8a62f8bbc53169a50fcd4722fd24 --- /dev/null +++ b/pool/shard001/C++/0023068_scu_bcs_2_307_test.cc @@ -0,0 +1,49 @@ +/****************************************************************************** + * Copyright 2019 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/canbus/vehicle/ge3/protocol/scu_bcs_2_307.h" +#include "gtest/gtest.h" + +namespace apollo { +namespace canbus { +namespace ge3 { + +class Scubcs2307Test : public ::testing::Test { + public: + virtual void SetUp() {} +}; + +TEST_F(Scubcs2307Test, reset) { + Scubcs2307 scubcs2307; + int32_t length = 8; + ChassisDetail chassis_detail; + uint8_t bytes[8] = {0x01, 0x02, 0x03, 0x04, 0x11, 0x12, 0x13, 0x14}; + + scubcs2307.Parse(bytes, length, &chassis_detail); + EXPECT_DOUBLE_EQ(chassis_detail.ge3().scu_bcs_2_307().bcs_vehspdvd(), 0); // + EXPECT_DOUBLE_EQ(chassis_detail.ge3().scu_bcs_2_307().bcs_yawrate(), + -1.573735); // + EXPECT_DOUBLE_EQ(chassis_detail.ge3().scu_bcs_2_307().bcs_vehspd(), + 8.53125); // + EXPECT_DOUBLE_EQ(chassis_detail.ge3().scu_bcs_2_307().bcs_vehlongaccel(), + -20.290904); // + EXPECT_DOUBLE_EQ(chassis_detail.ge3().scu_bcs_2_307().bcs_vehlataccel(), + -21.158968); // +} + +} // namespace ge3 +} // namespace canbus +} // namespace apollo diff --git a/pool/shard001/C++/0023074_DominoSampler.cpp b/pool/shard001/C++/0023074_DominoSampler.cpp new file mode 100644 index 0000000000000000000000000000000000000000..56b939b58c4c10397f9e1949436713bc63745286 --- /dev/null +++ b/pool/shard001/C++/0023074_DominoSampler.cpp @@ -0,0 +1,238 @@ +/** + * \file DominoSampler.cpp + * \brief Sample best solutions using Domino. + * + * Copyright 2007-2017 IMP Inventors. All rights reserved. + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +IMPDOMINO_BEGIN_NAMESPACE + +DominoSampler::DominoSampler(Model *m, ParticleStatesTable *pst, + std::string name) + : DiscreteSampler(m, pst, name), has_mt_(false), csf_(false) {} + +DominoSampler::DominoSampler(Model *m, std::string name) + : DiscreteSampler(m, new ParticleStatesTable(), name), csf_(false) {} + +template +void check_graph(const G &jt, Subset known_particles) { + IMP_CHECK_VARIABLE(known_particles); + IMP_CHECK_VARIABLE(jt); + IMP_IF_CHECK(USAGE) { + boost::unordered_set used; + typename boost::property_map::const_type + subset_map = boost::get(boost::vertex_name, jt); + for (unsigned int i = 0; i < boost::num_vertices(jt); ++i) { + Subset s = boost::get(subset_map, i); + used.insert(s.begin(), s.end()); + } + IMP_USAGE_CHECK(used.size() == known_particles.size(), + "Unexpected number of particles found in graph. Expected " + << known_particles.size() << " found " << used.size()); + } +} + +Assignments DominoSampler::do_get_sample_assignments( + const Subset &known_particles) const { + IMP_LOG_TERSE("Sampling with " << known_particles.size() << " particles as " + << known_particles << std::endl); + IMP_USAGE_CHECK(known_particles.size() > 0, "No particles to sample"); + ParticlesTemp pt(known_particles.begin(), known_particles.end()); + + SubsetFilterTables sfts = get_subset_filter_tables_to_use( + get_restraints(), get_particle_states_table()); + IMP_IF_LOG(TERSE) { + IMP_LOG_TERSE("Filtering with "); + for (unsigned int i = 0; i < sfts.size(); ++i) { + IMP_LOG_TERSE(sfts[i]->get_name() << " "); + } + IMP_LOG_TERSE(std::endl); + } + IMP::PointerMember sst = + DiscreteSampler::get_assignments_table_to_use(sfts); + + Assignments final_solutions; + if (true) { + MergeTree mt; + if (has_mt_) { + IMP_LOG_TERSE("DOMINO has merge tree" << std::endl); + mt = mt_; + check_graph(mt_, known_particles); + IMP_USAGE_CHECK(get_is_merge_tree(mt, known_particles, true), + "Not a merge tree"); + IMP_LOG_TERSE("DOMINO END merge tree" << std::endl); + } else { + IMP_LOG_TERSE("DOMINO has junction tree" << std::endl); + SubsetGraph jt = get_junction_tree(get_interaction_graph( + get_restraints(), get_particle_states_table())); + mt = get_merge_tree(jt); + } + ListSubsetFilterTable *lsft = nullptr; + if (csf_) { + lsft = new ListSubsetFilterTable(get_particle_states_table()); + sfts.push_back(lsft); + } + IMP_LOG_TERSE("domino::DominoSampler entering InferenceStatistics\n"); + { + // sillyness for mac os with boost 1.48 bug + internal::InferenceStatistics tmp; + stats_ = tmp; + } + IMP_LOG_TERSE("domino::DominoSampler entering get_best_conformations\n"); + IMP_NEW(PackedAssignmentContainer, as, ()); + as->set_was_used(true); + internal::load_best_conformations(mt, boost::num_vertices(mt) - 1, + known_particles, sfts, sst, lsft, &stats_, + get_maximum_number_of_assignments(), as); + final_solutions = + as->get_assignments(IntRange(0, as->get_number_of_assignments())); + IMP_LOG_TERSE("domino::DominoSampler end get_best_conformations\n"); + if (lsft) { + IMP_LOG_TERSE( + lsft->get_ok_rate() << " were ok with the cross set filtering" + << std::endl); + } + IMP_LOG_TERSE("DOMINO FINISH junction tree" << std::endl); + } + return final_solutions; +} + +void DominoSampler::set_merge_tree(const MergeTree &sg) { + mt_ = sg; + has_mt_ = true; +} + +unsigned int DominoSampler::get_number_of_assignments_for_vertex( + unsigned int tree_vertex) const { + IMP_USAGE_CHECK(has_mt_, "Can only query statistics of the merge tree" + << " if you set one."); + boost::property_map::const_type subset_map = + boost::get(boost::vertex_name, mt_); + return stats_.get_number_of_assignments(subset_map[tree_vertex]); +} + +Assignments DominoSampler::get_sample_assignments_for_vertex( + unsigned int tree_vertex) const { + IMP_USAGE_CHECK(has_mt_, "Can only query statistics of the merge tree" + << " if you set one."); + boost::property_map::const_type subset_map = + boost::get(boost::vertex_name, mt_); + return stats_.get_sample_assignments(subset_map[tree_vertex]); +} + +Assignments DominoSampler::get_vertex_assignments( + unsigned int node_index, unsigned int max_states) const { + IMP_NEW(PackedAssignmentContainer, ret, ()); + ret->set_was_used(true); + load_vertex_assignments(node_index, ret, max_states); + return ret->get_assignments(IntRange(0, ret->get_number_of_assignments())); +} +Assignments DominoSampler::get_vertex_assignments( + unsigned int node_index, const Assignments &first, + const Assignments &second, unsigned int max_states) const { + IMP_NEW(PackedAssignmentContainer, ret, ()); + IMP_NEW(PackedAssignmentContainer, firstc, ()); + firstc->add_assignments(first); + IMP_NEW(PackedAssignmentContainer, secondc, ()); + secondc->add_assignments(second); + ret->set_was_used(true); + load_vertex_assignments(node_index, firstc, secondc, ret, max_states); + return ret->get_assignments(IntRange(0, ret->get_number_of_assignments())); +} + +void DominoSampler::load_vertex_assignments(unsigned int node_index, + AssignmentContainer *ac, + unsigned int max_states) const { + set_was_used(true); + IMP_OBJECT_LOG; + IMP_USAGE_CHECK(has_mt_, + "Must set merge tree before using interactive functions."); + typedef boost::property_map::const_type + SubsetMap; + typedef boost::graph_traits::adjacency_iterator NeighborIterator; + SubsetMap subset_map = boost::get(boost::vertex_name, mt_); + + // ParticlesTemp known_particles= + // get_particle_states_table()->get_particles(); + SubsetFilterTables sfts = get_subset_filter_tables_to_use( + get_restraints(), get_particle_states_table()); + IMP::PointerMember sst = + DiscreteSampler::get_assignments_table_to_use(sfts, max_states); + ListSubsetFilterTable *lsft = nullptr; + if (csf_) { + lsft = new ListSubsetFilterTable(get_particle_states_table()); + sfts.push_back(lsft); + } + std::pair be = + boost::adjacent_vertices(node_index, mt_); + IMP_CHECK_VARIABLE(be); + IMP_USAGE_CHECK(std::distance(be.first, be.second) == 0, + "Not a binary tree leaf"); + Subset curs = boost::get(subset_map, node_index); + internal::load_leaf_assignments(curs, sst, lsft, nullptr, ac); +} + +void DominoSampler::load_vertex_assignments(unsigned int node_index, + AssignmentContainer *first, + AssignmentContainer *second, + AssignmentContainer *ret, + unsigned int max_states) const { + set_was_used(true); + IMP_OBJECT_LOG; + IMP_USAGE_CHECK(has_mt_, + "Must set merge tree before using interactive functions."); + typedef boost::property_map::const_type + SubsetMap; + typedef boost::graph_traits::adjacency_iterator NeighborIterator; + SubsetMap subset_map = boost::get(boost::vertex_name, mt_); + + // ParticlesTemp known_particles= + // get_particle_states_table()->get_particles(); + // ParticlesTemp pt(known_particles.begin(), known_particles.end()) + SubsetFilterTables sfts = get_subset_filter_tables_to_use( + get_restraints(), get_particle_states_table()); + ListSubsetFilterTable *lsft = nullptr; + if (csf_) { + lsft = new ListSubsetFilterTable(get_particle_states_table()); + sfts.push_back(lsft); + } + std::pair be = + boost::adjacent_vertices(node_index, mt_); + IMP_USAGE_CHECK(std::distance(be.first, be.second) == 2, + "Not a binary tree node"); + int firsti = *be.first; + int secondi = *(++be.first); + if (firsti > secondi) { + std::swap(firsti, secondi); + } + Subset firsts = boost::get(subset_map, firsti); + Subset seconds = boost::get(subset_map, secondi); + IMP_IF_CHECK(USAGE) { + if (first->get_number_of_assignments() > 0) { + IMP_USAGE_CHECK(first->get_assignment(0).size() == firsts.size(), + "The size of an assignment from the first set is not " + << "as expected, are you sure the order is right?"); + } + if (second->get_number_of_assignments() > 0) { + IMP_USAGE_CHECK(second->get_assignment(0).size() == seconds.size(), + "The size of an assignment from the first set is not " + << "as expected, are you sure the order is right?"); + } + } + internal::load_merged_assignments(firsts, first, seconds, second, sfts, lsft, + nullptr, max_states, ret); +} + +IMPDOMINO_END_NAMESPACE diff --git a/pool/shard001/C++/0023076_evakeyrequest.cpp b/pool/shard001/C++/0023076_evakeyrequest.cpp new file mode 100644 index 0000000000000000000000000000000000000000..977e1bf46bd65f106e0f1d49305d56853ad7d8c1 --- /dev/null +++ b/pool/shard001/C++/0023076_evakeyrequest.cpp @@ -0,0 +1,100 @@ +/*************************************************************************** + * Copyright (C) 2004 by yunfan * + * yunfan_zg@163.com * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ + +#include "evakeyrequest.h" +#include + +EvaRequestKeyPacket::EvaRequestKeyPacket() + : OutPacket(QQ_CMD_REQUEST_KEY, true) +{ +} + +EvaRequestKeyPacket::EvaRequestKeyPacket(const unsigned char requestType) + : OutPacket(QQ_CMD_REQUEST_KEY, true) +{ + request = requestType; +} + +EvaRequestKeyPacket::EvaRequestKeyPacket( const EvaRequestKeyPacket &rhs ) + : OutPacket(rhs) +{ + *this = rhs; +} + +EvaRequestKeyPacket::~EvaRequestKeyPacket() +{ +} + +EvaRequestKeyPacket &EvaRequestKeyPacket::operator=(const EvaRequestKeyPacket &rhs) +{ + *( (OutPacket *)this) = (OutPacket)rhs; + request = rhs.getRequest(); + return *this; +} + +int EvaRequestKeyPacket::putBody(unsigned char* buf) +{ + buf[0]=request; + return 1; +} + + + +/**********************************************************************************************************************/ + +EvaRequestKeyReplyPacket::EvaRequestKeyReplyPacket(unsigned char* buf, int len) + : InPacket(buf, len) +{ +} + +EvaRequestKeyReplyPacket::EvaRequestKeyReplyPacket(const EvaRequestKeyReplyPacket &rhs) + : InPacket(rhs) +{ + *this = rhs; +} + +EvaRequestKeyReplyPacket &EvaRequestKeyReplyPacket::operator=(const EvaRequestKeyReplyPacket &rhs) +{ + *( (InPacket *)this) = (InPacket)rhs; + keyType = rhs.getKeyType(); + replyCode = rhs.getReplyCode(); + memcpy(key, rhs.getKey(), 16); + tokenLength = rhs.getTokenLength(); + memcpy(token, rhs.getToken(), tokenLength); + return *this; +} + +void EvaRequestKeyReplyPacket::parseBody() +{ + keyType = decryptedBuf[0]; + replyCode = decryptedBuf[1]; + if(replyCode == QQ_REQUEST_KEY_REPLY_OK) { + memcpy(key, decryptedBuf+2, QQ_KEY_LENGTH); + + if(keyType == QQ_REQUEST_FILE_AGENT_KEY) + setFileAgentKey(key); // now we set file agent key + + tokenLength = (int)(decryptedBuf[2+QQ_KEY_LENGTH+12]) & 0xFF; + memcpy(token, decryptedBuf+2+QQ_KEY_LENGTH+12+1, tokenLength); + + if(keyType == QQ_REQUEST_FILE_AGENT_KEY) + setFileAgentToken(token, tokenLength); // now we can set file agent token + } +} diff --git a/pool/shard001/C++/0023087_list.cpp b/pool/shard001/C++/0023087_list.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3f75e81e9cef65771cf6745505ed5617e9509605 --- /dev/null +++ b/pool/shard001/C++/0023087_list.cpp @@ -0,0 +1,37 @@ +#include "wrap.h" + +void rearrange() +{ + list mylist; + + cout << "你想要多少个自然数?"; + int n; + cin >> n; + + // 放入自然数 + for(int i=1; i<=n; i++) + { + mylist.push_back(i); + } + + cout << "自然数原始序列:" << endl; + show< list >(mylist); + + // 从后往前,遍历链表 + for(list::reverse_iterator p = mylist.rbegin(); + p != mylist.rend(); p++) + { + // 如果是偶数,则移动到链表的末尾 + if(*p % 2 == 0) + { + int tmp = *p; + + mylist.remove(tmp); + mylist.push_back(tmp); + } + } + + cout << "奇偶数重新排列之后的序列:" << endl; + show< list >(mylist); + cout << endl; +} diff --git a/pool/shard001/C++/0023091_triangle_mesh3_tests.cpp b/pool/shard001/C++/0023091_triangle_mesh3_tests.cpp new file mode 100644 index 0000000000000000000000000000000000000000..89b2617e11677b560eeb49c07dafdfdd0672ae61 --- /dev/null +++ b/pool/shard001/C++/0023091_triangle_mesh3_tests.cpp @@ -0,0 +1,111 @@ +// Copyright (c) 2018 Doyub Kim +// +// I am making my contributions/submissions to this project solely in my +// personal capacity and am not conveying any rights to any intellectual +// property of any third parties. + +#include + +#include + +using namespace jet; + +JET_TESTS(TriangleMesh3); + +JET_BEGIN_TEST_F(TriangleMesh3, PointsOnlyGeometries) { + TriangleMesh3 triMesh; + + triMesh.addPoint({0, 0, 0}); + triMesh.addPoint({0, 0, 1}); + triMesh.addPoint({0, 1, 0}); + triMesh.addPoint({0, 1, 1}); + triMesh.addPoint({1, 0, 0}); + triMesh.addPoint({1, 0, 1}); + triMesh.addPoint({1, 1, 0}); + triMesh.addPoint({1, 1, 1}); + + // -x + triMesh.addPointTriangle({0, 1, 3}); + triMesh.addPointTriangle({0, 3, 2}); + + // +x + triMesh.addPointTriangle({4, 6, 7}); + triMesh.addPointTriangle({4, 7, 5}); + + // -y + triMesh.addPointTriangle({0, 4, 5}); + triMesh.addPointTriangle({0, 5, 1}); + + // +y + triMesh.addPointTriangle({2, 3, 7}); + triMesh.addPointTriangle({2, 7, 6}); + + // -z + triMesh.addPointTriangle({0, 2, 6}); + triMesh.addPointTriangle({0, 6, 4}); + + // +z + triMesh.addPointTriangle({1, 5, 7}); + triMesh.addPointTriangle({1, 7, 3}); + + saveTriangleMeshData(triMesh, "cube.obj"); +} +JET_END_TEST_F + +JET_BEGIN_TEST_F(TriangleMesh3, PointsAndNormalGeometries) { + TriangleMesh3 triMesh; + + triMesh.addPoint({0, 0, 0}); + triMesh.addPoint({0, 0, 1}); + triMesh.addPoint({0, 1, 0}); + triMesh.addPoint({0, 1, 1}); + triMesh.addPoint({1, 0, 0}); + triMesh.addPoint({1, 0, 1}); + triMesh.addPoint({1, 1, 0}); + triMesh.addPoint({1, 1, 1}); + + triMesh.addNormal({-1, 0, 0}); + triMesh.addNormal({1, 0, 0}); + triMesh.addNormal({0, -1, 0}); + triMesh.addNormal({0, 1, 0}); + triMesh.addNormal({0, 0, -1}); + triMesh.addNormal({0, 0, 1}); + + // -x + triMesh.addPointNormalTriangle({0, 1, 3}, {0, 0, 0}); + triMesh.addPointNormalTriangle({0, 3, 2}, {0, 0, 0}); + + // +x + triMesh.addPointNormalTriangle({4, 6, 7}, {1, 1, 1}); + triMesh.addPointNormalTriangle({4, 7, 5}, {1, 1, 1}); + + // -y + triMesh.addPointNormalTriangle({0, 4, 5}, {2, 2, 2}); + triMesh.addPointNormalTriangle({0, 5, 1}, {2, 2, 2}); + + // +y + triMesh.addPointNormalTriangle({2, 3, 7}, {3, 3, 3}); + triMesh.addPointNormalTriangle({2, 7, 6}, {3, 3, 3}); + + // -z + triMesh.addPointNormalTriangle({0, 2, 6}, {4, 4, 4}); + triMesh.addPointNormalTriangle({0, 6, 4}, {4, 4, 4}); + + // +z + triMesh.addPointNormalTriangle({1, 5, 7}, {5, 5, 5}); + triMesh.addPointNormalTriangle({1, 7, 3}, {5, 5, 5}); + + saveTriangleMeshData(triMesh, "cube_with_normal.obj"); +} +JET_END_TEST_F + +JET_BEGIN_TEST_F(TriangleMesh3, BasicIO) { + TriangleMesh3 triMesh; + + std::ifstream file(RESOURCES_DIR "/bunny.obj"); + if (file) { + triMesh.readObj(&file); + file.close(); + } +} +JET_END_TEST_F diff --git a/pool/shard001/C++/0023095_qgstappsrc.cpp b/pool/shard001/C++/0023095_qgstappsrc.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d7645674f92cd0fb0c010a4139b13eea500b72fc --- /dev/null +++ b/pool/shard001/C++/0023095_qgstappsrc.cpp @@ -0,0 +1,224 @@ +/**************************************************************************** +** +** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/legal +** +** This file is part of the Qt Mobility Components. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and Digia. For licensing terms and +** conditions see http://qt.digia.com/licensing. For further information +** use the contact form at http://qt.digia.com/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Digia gives you certain additional +** rights. These rights are described in the Digia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3.0 as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU General Public License version 3.0 requirements will be +** met: http://www.gnu.org/copyleft/gpl.html. +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include + +#include "qgstappsrc.h" +#include + +QGstAppSrc::QGstAppSrc(QObject *parent) + :QObject(parent) + ,m_stream(0) + ,m_appSrc(0) + ,m_sequential(false) + ,m_maxBytes(0) + ,m_setup(false) + ,m_dataRequestSize(-1) + ,m_dataRequested(false) + ,m_enoughData(false) + ,m_forceData(false) +{ +} + +QGstAppSrc::~QGstAppSrc() +{ + if (m_appSrc) + gst_object_unref(G_OBJECT(m_appSrc)); +} + +bool QGstAppSrc::setup(GstElement* appsrc) +{ + if (m_setup || m_stream == 0 || appsrc == 0) + return false; + + m_appSrc = GST_APP_SRC(appsrc); + m_callbacks.need_data = &QGstAppSrc::on_need_data; + m_callbacks.enough_data = &QGstAppSrc::on_enough_data; + m_callbacks.seek_data = &QGstAppSrc::on_seek_data; + gst_app_src_set_callbacks(m_appSrc, (GstAppSrcCallbacks*)&m_callbacks, this, (GDestroyNotify)&QGstAppSrc::destroy_notify); + + g_object_get(G_OBJECT(m_appSrc), "max-bytes", &m_maxBytes, NULL); + + if (m_sequential) + m_streamType = GST_APP_STREAM_TYPE_STREAM; + else + m_streamType = GST_APP_STREAM_TYPE_RANDOM_ACCESS; + gst_app_src_set_stream_type(m_appSrc, m_streamType); + gst_app_src_set_size(m_appSrc, (m_sequential) ? -1 : m_stream->size()); + + return m_setup = true; +} + +void QGstAppSrc::setStream(QIODevice *stream) +{ + if (stream == 0) + return; + if (m_stream) { + disconnect(m_stream, SIGNAL(readyRead()), this, SLOT(onDataReady())); + disconnect(m_stream, SIGNAL(destroyed()), this, SLOT(streamDestroyed())); + } + if (m_appSrc) + gst_object_unref(G_OBJECT(m_appSrc)); + + m_dataRequestSize = -1; + m_dataRequested = false; + m_enoughData = false; + m_forceData = false; + m_maxBytes = 0; + + m_appSrc = 0; + m_stream = stream; + connect(m_stream, SIGNAL(destroyed()), SLOT(streamDestroyed())); + connect(m_stream, SIGNAL(readyRead()), this, SLOT(onDataReady())); + m_sequential = m_stream->isSequential(); + m_setup = false; +} + +QIODevice *QGstAppSrc::stream() const +{ + return m_stream; +} + +GstAppSrc *QGstAppSrc::element() +{ + return m_appSrc; +} + +void QGstAppSrc::onDataReady() +{ + if (!m_enoughData) { + m_dataRequested = true; + pushDataToAppSrc(); + } +} + +void QGstAppSrc::streamDestroyed() +{ + if (sender() == m_stream) { + m_stream = 0; + sendEOS(); + } +} + +void QGstAppSrc::pushDataToAppSrc() +{ + if (!isStreamValid() || !m_setup) + return; + + if (m_dataRequested && !m_enoughData) { + qint64 size; + if (m_dataRequestSize == (unsigned int)-1) + size = qMin(m_stream->bytesAvailable(), queueSize()); + else + size = qMin(m_stream->bytesAvailable(), (qint64)m_dataRequestSize); + void *data = g_malloc(size); + GstBuffer* buffer = gst_app_buffer_new(data, size, g_free, data); + buffer->offset = m_stream->pos(); + qint64 bytesRead = m_stream->read((char*)GST_BUFFER_DATA(buffer), size); + buffer->offset_end = buffer->offset + bytesRead - 1; + + if (bytesRead > 0) { + m_dataRequested = false; + m_enoughData = false; + GstFlowReturn ret = gst_app_src_push_buffer (GST_APP_SRC (element()), buffer); + if (ret == GST_FLOW_ERROR) { + qWarning()<<"appsrc: push buffer error"; + } else if (ret == GST_FLOW_WRONG_STATE) { + qWarning()<<"appsrc: push buffer wrong state"; + } else if (ret == GST_FLOW_RESEND) { + qWarning()<<"appsrc: push buffer resend"; + } + } + } else if (m_stream->atEnd()) { + sendEOS(); + } +} + +bool QGstAppSrc::doSeek(qint64 value) +{ + if (isStreamValid()) + return stream()->seek(value); + return false; +} + + +gboolean QGstAppSrc::on_seek_data(GstAppSrc *element, guint64 arg0, gpointer userdata) +{ + QGstAppSrc *self = reinterpret_cast(userdata); + if (self && self->isStreamValid()) { + if (!self->stream()->isSequential()) + QMetaObject::invokeMethod(self, "doSeek", Qt::AutoConnection, Q_ARG(qint64, arg0)); + } + else + return false; + + return true; +} + +void QGstAppSrc::on_enough_data(GstAppSrc *element, gpointer userdata) +{ + QGstAppSrc *self = reinterpret_cast(userdata); + if (self) + self->enoughData() = true; +} + +void QGstAppSrc::on_need_data(GstAppSrc *element, guint arg0, gpointer userdata) +{ + QGstAppSrc *self = reinterpret_cast(userdata); + if (self) { + self->dataRequested() = true; + self->enoughData() = false; + self->dataRequestSize()= arg0; + QMetaObject::invokeMethod(self, "pushDataToAppSrc", Qt::AutoConnection); + } +} + +void QGstAppSrc::destroy_notify(gpointer data) +{ + Q_UNUSED(data); +} + +void QGstAppSrc::sendEOS() +{ + gst_app_src_end_of_stream(GST_APP_SRC(m_appSrc)); + if (isStreamValid() && !stream()->isSequential()) + stream()->reset(); +} diff --git a/pool/shard001/C++/0023109_boss_azuregos.cpp b/pool/shard001/C++/0023109_boss_azuregos.cpp new file mode 100644 index 0000000000000000000000000000000000000000..07370390951a58ec265d098a75c72bfdb6abd6bb --- /dev/null +++ b/pool/shard001/C++/0023109_boss_azuregos.cpp @@ -0,0 +1,166 @@ +/* This file is part of the ScriptDev2 Project. See AUTHORS file for Copyright information + * 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 + */ + +/* ScriptData +SDName: Boss_Azuregos +SD%Complete: 99 +SDComment: Enrage is disabled because it is very doubtful that Azuregos had one in Classic +SDCategory: Azshara +EndScriptData */ + +#include "precompiled.h" + +enum +{ + SAY_TELEPORT = -1000100, + + SPELL_ARCANE_VACUUM = 21147, + SPELL_MARK_OF_FROST_PLAYER = 23182, + SPELL_MARK_OF_FROST_AURA = 23184, // Triggers 23186 on players that have 23182; unfortunatelly 23183 is missing from dbc + SPELL_MANA_STORM = 21097, + SPELL_CHILL = 21098, + SPELL_FROST_BREATH = 21099, + SPELL_REFLECT = 22067, + SPELL_CLEAVE = 19983, // Was 8255; this one is from wowhead and seems to be the correct one +// SPELL_ENRAGE = 23537, // Enrage code is disabled. See comment above +}; + +struct boss_azuregosAI : public ScriptedAI +{ + boss_azuregosAI(Creature* pCreature) : ScriptedAI(pCreature) {Reset();} + + uint32 m_uiManaStormTimer; + uint32 m_uiChillTimer; + uint32 m_uiBreathTimer; + uint32 m_uiTeleportTimer; + uint32 m_uiReflectTimer; + uint32 m_uiCleaveTimer; +// bool m_bEnraged; + + void Reset() override + { + m_uiManaStormTimer = urand(5000, 17000); + m_uiChillTimer = urand(10000, 30000); + m_uiBreathTimer = urand(2000, 8000); + m_uiTeleportTimer = 30000; + m_uiReflectTimer = urand(15000, 30000); + m_uiCleaveTimer = 7000; +// m_bEnraged = false; + } + + void KilledUnit(Unit* pVictim) override + { + // Mark killed players with Mark of Frost + if (pVictim->GetTypeId() == TYPEID_PLAYER) + pVictim->CastSpell(pVictim, SPELL_MARK_OF_FROST_PLAYER, TRIGGERED_OLD_TRIGGERED, nullptr, nullptr, m_creature->GetObjectGuid()); + } + + void Aggro(Unit* /*pWho*/) override + { + // Boss aura which triggers the stun effect on dead players who resurrect + DoCastSpellIfCan(m_creature, SPELL_MARK_OF_FROST_AURA); + } + + void UpdateAI(const uint32 uiDiff) override + { + // Return since we have no target + if (!m_creature->SelectHostileTarget() || !m_creature->getVictim()) + return; + + if (m_uiTeleportTimer < uiDiff) + { + if (DoCastSpellIfCan(m_creature, SPELL_ARCANE_VACUUM) == CAST_OK) + { + DoScriptText(SAY_TELEPORT, m_creature); + m_uiTeleportTimer = urand(20000, 30000); + } + } + else + m_uiTeleportTimer -= uiDiff; + + // Chill Timer + if (m_uiChillTimer < uiDiff) + { + if (DoCastSpellIfCan(m_creature, SPELL_CHILL) == CAST_OK) + m_uiChillTimer = urand(13000, 25000); + } + else + m_uiChillTimer -= uiDiff; + + // Breath Timer + if (m_uiBreathTimer < uiDiff) + { + if (DoCastSpellIfCan(m_creature, SPELL_FROST_BREATH) == CAST_OK) + m_uiBreathTimer = urand(10000, 25000); + } + else + m_uiBreathTimer -= uiDiff; + + // Mana Storm Timer + if (m_uiManaStormTimer < uiDiff) + { + if (Unit* pTarget = m_creature->SelectAttackingTarget(ATTACKING_TARGET_NEAREST_BY, 0)) + { + if (DoCastSpellIfCan(pTarget, SPELL_MANA_STORM) == CAST_OK) + m_uiManaStormTimer = urand(18000, 35000); + } + } + else + m_uiManaStormTimer -= uiDiff; + + // Reflect Timer + if (m_uiReflectTimer < uiDiff) + { + if (DoCastSpellIfCan(m_creature, SPELL_REFLECT) == CAST_OK) + m_uiReflectTimer = urand(20000, 35000); + } + else + m_uiReflectTimer -= uiDiff; + + // Cleave Timer + if (m_uiCleaveTimer < uiDiff) + { + if (DoCastSpellIfCan(m_creature->getVictim(), SPELL_CLEAVE) == CAST_OK) + m_uiCleaveTimer = 7000; + } + else + m_uiCleaveTimer -= uiDiff; + + // EnrageTimer +// if (!m_bEnraged && m_creature->GetHealthPercent() < 26.0f) +// { +// if (DoCastSpellIfCan(m_creature, SPELL_ENRAGE) == CAST_OK) +// m_bEnraged = true; +// } + + DoMeleeAttackIfReady(); + } +}; + +CreatureAI* GetAI_boss_azuregos(Creature* pCreature) +{ + return new boss_azuregosAI(pCreature); +} + +void AddSC_boss_azuregos() +{ + Script* pNewScript; + + pNewScript = new Script; + pNewScript->Name = "boss_azuregos"; + pNewScript->GetAI = &GetAI_boss_azuregos; + pNewScript->RegisterSelf(); +} diff --git a/pool/shard001/C++/0023110_units.cpp b/pool/shard001/C++/0023110_units.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6af755985bf3f8ba9a91b713c931a8cb6372b834 --- /dev/null +++ b/pool/shard001/C++/0023110_units.cpp @@ -0,0 +1,55 @@ +#include "../units.h" + +#include "testbench.h" + +TESTBENCH() + +TEST(can_declare_quantity) { + using namespace xp; + using namespace xp::units; + + using m = si::unit<1, 0, 0, 0, 0, 0, 0>; + //using kg = si::unit<0, 1, 0, 0, 0, 0, 0>; + //using s = si::unit<0, 0, 1, 0, 0, 0, 0>; + + quantity q{ 5 }; + VERIFY(q.val == 5); +} + +TEST(can_add_quantities) { + using namespace xp; + using namespace xp::units; + + using m = si::unit<1, 0, 0, 0, 0, 0, 0>; + + quantity x{ 2 }; + quantity y{ 0.5 }; + auto z = x + y; + VERIFY(z.val == 2.5); +} + +TEST(can_divide_quantities) { + using namespace xp; + using namespace xp::units; + + using m = si::unit<1, 0, 0, 0, 0, 0, 0>; + using s = si::unit<0, 0, 1, 0, 0, 0, 0>; + using m_s = si::unit<1, 0, -1, 0, 0, 0, 0>; + + quantity d{ 5 }; + quantity t{ 2 }; + quantity speed = d / t; + VERIFY(speed.val == 2.5); +} + +TEST(can_use literals) { + using namespace xp; + using namespace xp::units; + + auto kg = 1_kg; + auto g = 1_g; + + VERIFY(kg.val == 1000 * g.val); +} + +TESTFIXTURE(units) diff --git a/pool/shard001/C++/0023112_example.cc b/pool/shard001/C++/0023112_example.cc new file mode 100644 index 0000000000000000000000000000000000000000..3174164288d691eb32649c8e4fd5b0aa7c960b13 --- /dev/null +++ b/pool/shard001/C++/0023112_example.cc @@ -0,0 +1,70 @@ +// example.cc +#define EIGEN_USE_THREADS +#include "example.h" +#include "tensorflow/core/framework/op_kernel.h" + +using namespace tensorflow; + +using CPUDevice = Eigen::ThreadPoolDevice; +using GPUDevice = Eigen::GpuDevice; + +// CPU specialization of actual computation. +template +struct ExampleFunctor { + void operator()(const CPUDevice& d, int size, const T* in, T* out) { + for (int i = 0; i < size; ++i) { + out[i] = 2 * in[i]; + } + } +}; + +// OpKernel definition. +// template parameter is the datatype of the tensors. +template +class ExampleOp : public OpKernel { + public: + explicit ExampleOp(OpKernelConstruction* context) : OpKernel(context) {} + + void Compute(OpKernelContext* context) override { + // Grab the input tensor + const Tensor& input_tensor = context->input(0); + + // Create an output tensor + Tensor* output_tensor = NULL; + OP_REQUIRES_OK(context, context->allocate_output(0, input_tensor.shape(), + &output_tensor)); + + // Do the computation. + OP_REQUIRES(context, input_tensor.NumElements() <= tensorflow::kint32max, + errors::InvalidArgument("Too many elements in tensor")); + + /* To do the actual computation, compute function calls a templated functor struct */ + ExampleFunctor()( + context->eigen_device(), + static_cast(input_tensor.NumElements()), + input_tensor.flat().data(), + output_tensor->flat().data()); + } +}; + +// Register the CPU kernels. +#define REGISTER_CPU(T) + REGISTER_KERNEL_BUILDER( + Name("Example") + .Device(DEVICE_CPU) + .TypeConstraint("T"), + ExampleOp); +REGISTER_CPU(float); +REGISTER_CPU(int32); + +// Register the GPU kernels. +#ifdef GOOGLE_CUDA +#define REGISTER_GPU(T) + REGISTER_KERNEL_BUILDER( + Name("Example") + .Device(DEVICE_GPU) + .TypeConstraint("T"), + ExampleOp); +REGISTER_GPU(float); +REGISTER_GPU(int32); +#endif // GOOGLE_CUDA \ No newline at end of file diff --git a/pool/shard001/C++/0023115_player.cpp b/pool/shard001/C++/0023115_player.cpp new file mode 100644 index 0000000000000000000000000000000000000000..06d9a9445285609072962c105ffb6dadbea58a45 --- /dev/null +++ b/pool/shard001/C++/0023115_player.cpp @@ -0,0 +1,197 @@ +/*************************************** +** Tsunagari Tile Engine ** +** player.cpp ** +** Copyright 2011-2013 PariahSoft LLC ** +***************************************/ + +// ********** +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to +// deal in the Software without restriction, including without limitation the +// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +// sell copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +// IN THE SOFTWARE. +// ********** + +#include +#include +#include + +#include "area.h" +#include "client-conf.h" +#include "entity.h" +#include "log.h" +#include "player.h" +#include "world.h" +#include "window.h" + +#define ASSERT(x) if (!(x)) { return false; } + +template +void removeValue(Cont* c, ValueType v) +{ + typename Cont::iterator it; + for (it = c->begin(); it != c->end(); ++it) { + if (*it == v) { + c->erase(it); + return; + } + } +} + + +Player::Player() + : Character(), velocity(0, 0) +{ + nowalkFlags = TILE_NOWALK | TILE_NOWALK_PLAYER; + nowalkExempt = TILE_NOWALK_EXIT; +} + +bool Player::init(const std::string& descriptor, const std::string& initialPhase) +{ + ASSERT(Entity::init(descriptor)); + setPhase(initialPhase); + return true; +} + +void Player::destroy() +{ + // Assuming this is being called from Python code, where this function + // is bound to the name "delete()". + Log::err("Player", "delete(): Player cannot be destroyed"); +} + +void Player::startMovement(ivec2 delta) +{ + switch (conf.moveMode) { + case TURN: + moveByTile(delta); + break; + case TILE: + movements.push_back(delta); + velocity = delta; + moveByTile(velocity); + break; + case NOTILE: + // TODO + break; + } + stillMoving = velocity; +} + +void Player::stopMovement(ivec2 delta) +{ + switch (conf.moveMode) { + case TURN: + break; + case TILE: + removeValue(&movements, delta); + velocity = movements.size() ? + movements.back() : + ivec2(0, 0); + if (velocity) + moveByTile(velocity); + break; + case NOTILE: + // TODO + break; + } + stillMoving = velocity; +} + +void Player::moveByTile(ivec2 delta) +{ + if (frozen) + return; + if (moving) + return; + + setFacing(delta); + + // Left CTRL allows changing facing, but disallows movement. + // + // FIXME: This may not be the best keybinding because on Mac >= 10.7, + // Ctrl-Left and Ctrl-Right are bound by default to switch desktop + // space and do not reach Tsunagari's window. This leaves the hero in + // an awkward position of being able to switch directions to up or + // down but not to left or right. + // --pdm Dec 6, 2014 + const GameWindow& window = GameWindow::instance(); + if (window.input().down(Gosu::kbLeftControl)) { + setPhase(directionStr(facing)); + redraw = true; + return; + } + + Entity::moveByTile(delta); + + World* world = World::instance(); + world->turn(); +} + +void Player::useTile() +{ + Tile* t = area->getTile(moveDest(facing)); + if (t) + t->runUseScript(this); +} + +void Player::setFrozen(bool b) +{ + World* world = World::instance(); + + b ? world->storeKeys() : world->restoreKeys(); + Entity::setFrozen(b); + if (!frozen && velocity) + moveByTile(velocity); +} + +void Player::postMove() +{ + Entity::postMove(); + + // Normal exit. + if (destTile) { + Exit* exit = destTile->exits[EXIT_NORMAL]; + if (exit) + takeExit(exit); + } + + // Side exit. + if (fromTile) { + ivec2 dxy(deltaCoord.x, deltaCoord.y); + Exit* exit = fromTile->exitAt(dxy); + if (exit) + takeExit(exit); + } + + // If we have a velocity, keep moving. + if (conf.moveMode == TILE && velocity) + moveByTile(velocity); +} + +void Player::takeExit(Exit* exit) +{ + World* world = World::instance(); + Area* newArea = world->getArea(exit->area); + if (newArea) { + world->focusArea(newArea, exit->coords); + } + else { + // Roll back movement if exit failed to open. + setTileCoords(fromCoord); + Log::err("Exit", exit->area + ": failed to load properly"); + } +} + diff --git a/pool/shard001/C++/0023118_dlgStartup.cpp b/pool/shard001/C++/0023118_dlgStartup.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6fc985fd056cbbd93d343f1893cca19e038fb867 --- /dev/null +++ b/pool/shard001/C++/0023118_dlgStartup.cpp @@ -0,0 +1,226 @@ +/* +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 "Dialogs/Dialogs.h" +#include "WidgetDialog.hpp" +#include "Widget/TwoWidgets.hpp" +#include "Widget/RowFormWidget.hpp" +#include "UIGlobals.hpp" +#include "Profile/Profile.hpp" +#include "Screen/Canvas.hpp" +#include "Screen/Layout.hpp" +#include "Look/DialogLook.hpp" +#include "Form/Form.hpp" +#include "Form/Button.hpp" +#include "Form/DataField/FileReader.hpp" +#include "Language/Language.hpp" +#include "Gauge/LogoView.hpp" +#include "LogFile.hpp" +#include "Util/StringUtil.hpp" +#include "LocalPath.hpp" +#include "OS/PathName.hpp" +#include "OS/FileUtil.hpp" +#include "Compiler.h" + +#include /* for MAX_PATH */ + +class LogoWindow final : public PaintWindow { + LogoView logo; + +protected: + virtual void OnPaint(Canvas &canvas) override { + canvas.ClearWhite(); + logo.draw(canvas, GetClientRect()); + } +}; + +class LogoQuitWidget final : public NullWidget { + ActionListener &action_listener; + + LogoWindow logo; + WndButton quit; + +public: + LogoQuitWidget(const ButtonLook &look, ActionListener &_action_listener) + :action_listener(_action_listener), quit(look) {} + +private: + PixelRect GetButtonRect(PixelRect rc) { + rc.left = rc.right - Layout::Scale(75); + rc.bottom = rc.top + Layout::GetMaximumControlHeight(); + return rc; + } + +public: + /* virtual methods from class Widget */ + virtual PixelSize GetMinimumSize() const override { + return { 150, 150 }; + } + + virtual PixelSize GetMaximumSize() const override { + /* use as much as possible */ + return { 8192, 8192 }; + } + + virtual void Prepare(ContainerWindow &parent, + const PixelRect &rc) override { + WindowStyle style; + style.Hide(); + + ButtonWindowStyle button_style(style); + button_style.TabStop(); + + quit.Create(parent, _("Quit"), rc, + style, action_listener, mrCancel); + logo.Create(parent, rc, style); + } + + virtual void Unprepare() override { + logo.Destroy(); + quit.Destroy(); + } + + virtual void Show(const PixelRect &rc) override { + quit.MoveAndShow(GetButtonRect(rc)); + logo.MoveAndShow(rc); + } + + virtual void Hide() override { + quit.FastHide(); + logo.FastHide(); + } + + virtual void Move(const PixelRect &rc) override { + quit.Move(GetButtonRect(rc)); + logo.Move(rc); + } +}; + +class StartupWidget final : public RowFormWidget { + enum Controls { + PROFILE, + CONTINUE, + }; + + ActionListener &action_listener; + DataField *const df; + +public: + StartupWidget(const DialogLook &look, ActionListener &_action_listener, + DataField *_df) + :RowFormWidget(look), action_listener(_action_listener), df(_df) {} + + /* virtual methods from class Widget */ + virtual void Prepare(ContainerWindow &parent, + const PixelRect &rc) override; + virtual bool Save(bool &changed) override; + + virtual bool SetFocus() override { + /* focus the "Continue" button by default */ + GetRow(CONTINUE).SetFocus(); + return true; + } +}; + +void +StartupWidget::Prepare(ContainerWindow &parent, + const PixelRect &rc) +{ + Add(_("Profile"), nullptr, df); + AddButton(_("Continue"), action_listener, mrOK); +} + +static void +SelectProfile(const TCHAR *path) +{ + if (StringIsEmpty(path)) + return; + + Profile::SetFiles(path); + + if (RelativePath(path) == nullptr) { + /* When a profile from a secondary data path is used, this path + becomes the primary data path */ + TCHAR temp[MAX_PATH]; + SetPrimaryDataPath(DirName(path, temp)); + } + + File::Touch(path); +} + +bool +StartupWidget::Save(bool &changed) +{ + const DataFieldFileReader &dff = + (const DataFieldFileReader &)GetDataField(PROFILE); + SelectProfile(dff.GetPathFile()); + changed = true; + + return true; +} + +bool +dlgStartupShowModal() +{ + LogFormat("Startup dialog"); + + /* scan all profile files */ + DataFieldFileReader *dfe = new DataFieldFileReader(); + dfe->ScanDirectoryTop(_T("*.top")); + + /* skip this dialog if there is only one (or none) */ + if (dfe->GetNumFiles() <= 1) { + SelectProfile(dfe->GetPathFile()); + delete dfe; + return true; + } + + /* preselect the most recently used profile */ + unsigned best_index = 0; + uint64_t best_timestamp = 0; + unsigned length = dfe->size(); + + for (unsigned i = 0; i < length; ++i) { + const TCHAR *path = dfe->GetItem(i); + uint64_t timestamp = File::GetLastModification(path); + if (timestamp > best_timestamp) { + best_timestamp = timestamp; + best_index = i; + } + } + + dfe->Set(best_index); + + /* show the dialog */ + const DialogLook &look = UIGlobals::GetDialogLook(); + WidgetDialog dialog(look); + TwoWidgets widget(new LogoQuitWidget(look.button, dialog), + new StartupWidget(look, dialog, dfe)); + + dialog.CreateFull(UIGlobals::GetMainWindow(), _T(""), &widget); + + const int result = dialog.ShowModal(); + dialog.StealWidget(); + + return result == mrOK; +} diff --git a/pool/shard001/C++/0023121_thread_queue.cpp b/pool/shard001/C++/0023121_thread_queue.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c804df64ddba3f9633e01e4741843678a961b023 --- /dev/null +++ b/pool/shard001/C++/0023121_thread_queue.cpp @@ -0,0 +1,65 @@ +#include +#include +using namespace sim; +ThreadHandler::~ThreadHandler() +{ + +} + +ThreadQueue::ThreadQueue() + :is_started_(false), max_size_(0), thread_count_(0),size_(0) +{ +} + +void ThreadQueue::start() +{ + if (!is_started_) + { + is_started_ = true; + work_tasks_.reserve(thread_count_); + for (size_t i=0; irun(); + lock.lock(); + } + cond_.wait(lock); + } +} diff --git a/pool/shard001/C++/0023122_ping.cpp b/pool/shard001/C++/0023122_ping.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e3a1b6744fe75710793eea3fee5d92968e6a5361 --- /dev/null +++ b/pool/shard001/C++/0023122_ping.cpp @@ -0,0 +1,161 @@ +// +// ping.cpp +// ~~~~~~~~ +// +// Copyright (c) 2003-2015 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 +#include + +#include "icmp_header.hpp" +#include "ipv4_header.hpp" + +using asio::ip::icmp; +using asio::deadline_timer; +namespace posix_time = boost::posix_time; + +class pinger +{ +public: + pinger(asio::io_context& io_context, const char* destination) + : resolver_(io_context), socket_(io_context, icmp::v4()), + timer_(io_context), sequence_number_(0), num_replies_(0) + { + destination_ = *resolver_.resolve(icmp::v4(), destination, "").begin(); + + start_send(); + start_receive(); + } + +private: + void start_send() + { + std::string body("\"Hello!\" from Asio ping."); + + // Create an ICMP header for an echo request. + icmp_header echo_request; + echo_request.type(icmp_header::echo_request); + echo_request.code(0); + echo_request.identifier(get_identifier()); + echo_request.sequence_number(++sequence_number_); + compute_checksum(echo_request, body.begin(), body.end()); + + // Encode the request packet. + asio::streambuf request_buffer; + std::ostream os(&request_buffer); + os << echo_request << body; + + // Send the request. + time_sent_ = posix_time::microsec_clock::universal_time(); + socket_.send_to(request_buffer.data(), destination_); + + // Wait up to five seconds for a reply. + num_replies_ = 0; + timer_.expires_at(time_sent_ + posix_time::seconds(5)); + timer_.async_wait(boost::bind(&pinger::handle_timeout, this)); + } + + void handle_timeout() + { + if (num_replies_ == 0) + std::cout << "Request timed out" << std::endl; + + // Requests must be sent no less than one second apart. + timer_.expires_at(time_sent_ + posix_time::seconds(1)); + timer_.async_wait(boost::bind(&pinger::start_send, this)); + } + + void start_receive() + { + // Discard any data already in the buffer. + reply_buffer_.consume(reply_buffer_.size()); + + // Wait for a reply. We prepare the buffer to receive up to 64KB. + socket_.async_receive(reply_buffer_.prepare(65536), + boost::bind(&pinger::handle_receive, this, _2)); + } + + void handle_receive(std::size_t length) + { + // The actual number of bytes received is committed to the buffer so that we + // can extract it using a std::istream object. + reply_buffer_.commit(length); + + // Decode the reply packet. + std::istream is(&reply_buffer_); + ipv4_header ipv4_hdr; + icmp_header icmp_hdr; + is >> ipv4_hdr >> icmp_hdr; + + // We can receive all ICMP packets received by the host, so we need to + // filter out only the echo replies that match the our identifier and + // expected sequence number. + if (is && icmp_hdr.type() == icmp_header::echo_reply + && icmp_hdr.identifier() == get_identifier() + && icmp_hdr.sequence_number() == sequence_number_) + { + // If this is the first reply, interrupt the five second timeout. + if (num_replies_++ == 0) + timer_.cancel(); + + // Print out some information about the reply packet. + posix_time::ptime now = posix_time::microsec_clock::universal_time(); + std::cout << length - ipv4_hdr.header_length() + << " bytes from " << ipv4_hdr.source_address() + << ": icmp_seq=" << icmp_hdr.sequence_number() + << ", ttl=" << ipv4_hdr.time_to_live() + << ", time=" << (now - time_sent_).total_milliseconds() << " ms" + << std::endl; + } + + start_receive(); + } + + static unsigned short get_identifier() + { +#if defined(ASIO_WINDOWS) + return static_cast(::GetCurrentProcessId()); +#else + return static_cast(::getpid()); +#endif + } + + icmp::resolver resolver_; + icmp::endpoint destination_; + icmp::socket socket_; + deadline_timer timer_; + unsigned short sequence_number_; + posix_time::ptime time_sent_; + asio::streambuf reply_buffer_; + std::size_t num_replies_; +}; + +int main(int argc, char* argv[]) +{ + try + { + if (argc != 2) + { + std::cerr << "Usage: ping " << std::endl; +#if !defined(ASIO_WINDOWS) + std::cerr << "(You may need to run this program as root.)" << std::endl; +#endif + return 1; + } + + asio::io_context io_context; + pinger p(io_context, argv[1]); + io_context.run(); + } + catch (std::exception& e) + { + std::cerr << "Exception: " << e.what() << std::endl; + } +} diff --git a/pool/shard001/C++/0023131_livescores.cpp b/pool/shard001/C++/0023131_livescores.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e834f485cb599834a7b98cf70b4243e4210ef6d5 --- /dev/null +++ b/pool/shard001/C++/0023131_livescores.cpp @@ -0,0 +1,190 @@ +/* + * Copyright 2014-2017 Roland Hostettler + * + * This file is part of swisshockey. + * + * swisshockey 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. + * + * swisshockey 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 + * swisshockey. If not, see http://www.gnu.org/licenses/. + */ + +#include "livescores.h" + +#include +#include + +#include "logger.h" +#include "config.h" +#include "notifier.h" + +// SailfishApp::main() will display "qml/template.qml", if you need more +// control over initialization, you can use: +// +// - SailfishApp::application(int, char *[]) to get the QGuiApplication * +// - SailfishApp::createView() to get a new QQuickView * instance +// - SailfishApp::pathTo(QString) to get a QUrl to a resource file +// +// To display the view, call "show()" (will show fullscreen on device). +LiveScores::LiveScores(QObject *parent) : QObject(parent) { + //mAppVersion.append(APP_VERSION); + mAppName.append(APP_NAME); + + // Create the data store and setup the data provider + mDataStore = new GamedayData(this); + mDataSource = new SIHFDataSource(this); + connect(mDataSource, SIGNAL(summaryUpdated(QVariantMap)), mDataStore, SLOT(updateData(QVariantMap))); + + // Create a filter for the league, acts as a proxy between the view and the + // data store + mLeagueFilter = new QSortFilterProxyModel(this); + mLeagueFilter->setFilterRole(GamedayData::LeagueRole); + mLeagueFilter->setDynamicSortFilter(true); + mLeagueFilter->setFilterKeyColumn(0); // We only have the 0-column + mLeagueFilter->setFilterRegExp(".*"); + mLeagueFilter->setSourceModel(mDataStore); + + // Create the notifier, disabled by default (enabled automatically when the + // app is brought to the background) + // TODO: Consider having on-screen notification banner when in foreground + mNotifier = new Notifier(mDataStore, this); +// mNotifier->disableNotifications(); + + // Load and show the QML + mQmlViewer = SailfishApp::createView(); + mQmlViewer->setSource(SailfishApp::pathTo("qml/harbour-swisshockey.qml")); + mQmlViewer->show(); + + // Get the leagues + mDataSource->getLeagues(&mLeaguesList); + + // Connect the QML and the C++ bits, and add an event filter to catch + // switches between foreground and background. + mQmlViewer->rootContext()->setContextProperty("listData", this->mLeagueFilter); + mQmlViewer->rootContext()->setContextProperty("leagueList", QVariant::fromValue(mLeaguesList)); + QObject *rootObject = mQmlViewer->rootObject(); + connect(rootObject, SIGNAL(viewChanged(QString)), this, SLOT(updateView(QString))); + connect(rootObject, SIGNAL(leagueChanged(QString)), this, SLOT(updateLeague(QString))); + connect(rootObject, SIGNAL(updateTriggered()), this, SLOT(updateData())); // Manually trigger update + rootObject->installEventFilter(this); + + // Connect the update*()-signals to the update indicator + QObject *overviewPage = rootObject->findChild("overviewPage"); + if(overviewPage == 0) { + Logger& logger = Logger::getInstance(); + logger.log(Logger::DEBUG, QString(Q_FUNC_INFO).append("LiveScores::LiveScores(): Couldn't find the 'overviewPage' QML object, updates in progress will not be shown.")); + } else { + connect(mDataSource, SIGNAL(updateStarted()), overviewPage, SLOT(startUpdateIndicator())); + connect(mDataSource, SIGNAL(updateFinished()), overviewPage, SLOT(stopUpdateIndicator())); + } + + // Trigger an update after all the GUI signals have been connected. + // currentId is "NULL" by default. + mDataSource->update(mSelectedGameId); + + // Create a timer that periodically fires to update the data, defaults to 5 mins + Config& config = Config::getInstance(); + int updateInterval = config.getValue("updateInterval", 0.5).toInt(); + mUpdateTimer = new QTimer(this); + mUpdateTimer->setTimerType(Qt::PreciseTimer); + mUpdateTimer->setSingleShot(false); + connect(mUpdateTimer, SIGNAL(timeout()), this, SLOT(updateData())); + mUpdateTimer->start(updateInterval*60*1000); + +#if 0 + // TODO: Use this code to show the info banner from C++ (Harmattan). + QVariant msg = "Hello from C++"; + QMetaObject::invokeMethod(rootObject, "showInfo", Q_ARG(QVariant, msg)); +#endif +} + +// App name +QString LiveScores::getAppName() const { + return mAppName; +} + +// App version +QString LiveScores::getAppVersion() const { + return mAppVersion; +} + +// Called when the user switches from the summaries to the details view +// TODO: Maybe we should trigger a busy indicator here too? +void LiveScores::updateView(QString id) { + mSelectedGameId = id; + mNotifier->setGameId(id); + + GameData *game = mDataStore->getGame(id); + if(game != NULL) { + // Set the game id in the totomat & force update + connect(mDataSource, SIGNAL(eventsUpdated(QList)), game, SLOT(updateEvents(QList))); + connect(mDataSource, SIGNAL(playersUpdated(QList)), game, SLOT(updateRosters(QList))); + mDataSource->getGameDetails(id); + + // Set the details data models + QQmlContext *context = mQmlViewer->rootContext(); + context->setContextProperty("gameDetailsData", game); + context->setContextProperty("gameEventsData", game); + // TODO: Set home & away team rosters here + } +} + +// Update the filter to the selected league +void LiveScores::updateLeague(QString leagueId) { + Logger& logger = Logger::getInstance(); + logger.log(Logger::DEBUG, "LiveScores::updateLeague(): Changing league filter to " + leagueId); + if(!leagueId.compare("0")) { + mLeagueFilter->setFilterRegExp(".*"); + } else { + mLeagueFilter->setFilterRegExp("^" + leagueId + "$"); + } +} + +// Observe the focus state of the app (foreground / background) and set the +// internal state accordingly +bool LiveScores::eventFilter(QObject* obj, QEvent* event) { + // TODO: Re-implement this +#if 0 + Logger& logger = Logger::getInstance(); + + switch(event->type()) { + case QEvent::WindowActivate: + this->notifier->disableNotifications(); + this->notifier->clearNotifications(); + logger.log(Logger::DEBUG, "LiveScores::eventFilter(): Switched to foreground, notifications disabled."); + break; + + case QEvent::WindowDeactivate: + this->notifier->enableNotifications(); + logger.log(Logger::DEBUG, "LiveScores::eventFilter(): Switched to background, notifications enabled."); + break; + + default: + break; + } +#endif + + // We don't mind other event handlers handling the events, so return false. + return false; +} + +// Updates the data when the timer fires or when triggered by the user +void LiveScores::updateData() { + Logger& logger = Logger::getInstance(); + logger.log(Logger::DEBUG, "LiveScores::updateData(): called for a data update."); + mDataSource->update(mSelectedGameId); +} + +LiveScores::~LiveScores(void) { + // Remove the ones that are not deleted automagically + delete mQmlViewer; + delete mNotifier; +} diff --git a/pool/shard001/C++/0023136_certificate_provider_service_factory.cc b/pool/shard001/C++/0023136_certificate_provider_service_factory.cc new file mode 100644 index 0000000000000000000000000000000000000000..eec8b3bf2483b30e2f303a1158e9857ef021862d --- /dev/null +++ b/pool/shard001/C++/0023136_certificate_provider_service_factory.cc @@ -0,0 +1,204 @@ +// 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 "chrome/browser/chromeos/certificate_provider/certificate_provider_service_factory.h" + +#include +#include +#include +#include + +#include "base/logging.h" +#include "base/macros.h" +#include "base/memory/ptr_util.h" +#include "base/memory/ref_counted.h" +#include "base/memory/singleton.h" +#include "base/values.h" +#include "chrome/browser/chromeos/certificate_provider/certificate_provider_service.h" +#include "chrome/browser/profiles/incognito_helpers.h" +#include "chrome/common/extensions/api/certificate_provider.h" +#include "components/keyed_service/content/browser_context_dependency_manager.h" +#include "extensions/browser/event_listener_map.h" +#include "extensions/browser/event_router.h" +#include "extensions/browser/event_router_factory.h" +#include "extensions/browser/extension_event_histogram_value.h" +#include "extensions/browser/extension_registry.h" +#include "extensions/browser/extension_registry_factory.h" +#include "extensions/browser/extension_registry_observer.h" +#include "extensions/common/extension.h" +#include "net/cert/x509_certificate.h" +#include "net/ssl/ssl_private_key.h" + +namespace chromeos { + +namespace { + +namespace api_cp = extensions::api::certificate_provider; + +class DefaultDelegate : public CertificateProviderService::Delegate, + public extensions::ExtensionRegistryObserver { + public: + DefaultDelegate(CertificateProviderService* service, + extensions::ExtensionRegistry* registry, + extensions::EventRouter* event_router); + ~DefaultDelegate() override; + + // CertificateProviderService::Delegate: + std::vector CertificateProviderExtensions() override; + void BroadcastCertificateRequest(int request_id) override; + bool DispatchSignRequestToExtension( + const std::string& extension_id, + int request_id, + net::SSLPrivateKey::Hash hash, + const scoped_refptr& certificate, + const std::string& digest) override; + + // extensions::ExtensionRegistryObserver: + void OnExtensionUnloaded( + content::BrowserContext* browser_context, + const extensions::Extension* extension, + extensions::UnloadedExtensionInfo::Reason reason) override; + + private: + CertificateProviderService* const service_; + extensions::ExtensionRegistry* const registry_; + extensions::EventRouter* const event_router_; + + DISALLOW_COPY_AND_ASSIGN(DefaultDelegate); +}; + +DefaultDelegate::DefaultDelegate(CertificateProviderService* service, + extensions::ExtensionRegistry* registry, + extensions::EventRouter* event_router) + : service_(service), registry_(registry), event_router_(event_router) { + DCHECK(service_); + DCHECK(event_router_); + registry_->AddObserver(this); +} + +DefaultDelegate::~DefaultDelegate() { + registry_->RemoveObserver(this); +} + +std::vector DefaultDelegate::CertificateProviderExtensions() { + const std::string event_name(api_cp::OnCertificatesRequested::kEventName); + std::vector ids; + for (const auto& listener : + event_router_->listeners().GetEventListenersByName(event_name)) { + ids.push_back(listener->extension_id()); + } + return ids; +} + +void DefaultDelegate::BroadcastCertificateRequest(int request_id) { + const std::string event_name(api_cp::OnCertificatesRequested::kEventName); + std::unique_ptr internal_args(new base::ListValue); + internal_args->AppendInteger(request_id); + std::unique_ptr event(new extensions::Event( + extensions::events::CERTIFICATEPROVIDER_ON_CERTIFICATES_REQUESTED, + event_name, std::move(internal_args))); + event_router_->BroadcastEvent(std::move(event)); +} + +bool DefaultDelegate::DispatchSignRequestToExtension( + const std::string& extension_id, + int request_id, + net::SSLPrivateKey::Hash hash, + const scoped_refptr& certificate, + const std::string& digest) { + const std::string event_name(api_cp::OnSignDigestRequested::kEventName); + if (!event_router_->ExtensionHasEventListener(extension_id, event_name)) + return false; + + api_cp::SignRequest request; + switch (hash) { + case net::SSLPrivateKey::Hash::MD5_SHA1: + request.hash = api_cp::HASH_MD5_SHA1; + break; + case net::SSLPrivateKey::Hash::SHA1: + request.hash = api_cp::HASH_SHA1; + break; + case net::SSLPrivateKey::Hash::SHA256: + request.hash = api_cp::HASH_SHA256; + break; + case net::SSLPrivateKey::Hash::SHA384: + request.hash = api_cp::HASH_SHA384; + break; + case net::SSLPrivateKey::Hash::SHA512: + request.hash = api_cp::HASH_SHA512; + break; + } + request.digest.assign(digest.begin(), digest.end()); + std::string cert_der; + if (!net::X509Certificate::GetDEREncoded(certificate->os_cert_handle(), + &cert_der)) { + LOG(ERROR) << "Could not DER encode the certificate."; + return false; // Behave as if the extension wasn't registered anymore. + } + request.certificate.assign(cert_der.begin(), cert_der.end()); + + std::unique_ptr internal_args(new base::ListValue); + internal_args->AppendInteger(request_id); + internal_args->Append(request.ToValue()); + + event_router_->DispatchEventToExtension( + extension_id, + base::WrapUnique(new extensions::Event( + extensions::events::CERTIFICATEPROVIDER_ON_SIGN_DIGEST_REQUESTED, + event_name, std::move(internal_args)))); + return true; +} + +void DefaultDelegate::OnExtensionUnloaded( + content::BrowserContext* browser_context, + const extensions::Extension* extension, + extensions::UnloadedExtensionInfo::Reason reason) { + service_->OnExtensionUnloaded(extension->id()); +} + +} // namespace + +// static +CertificateProviderService* +CertificateProviderServiceFactory::GetForBrowserContext( + content::BrowserContext* context) { + return static_cast( + GetInstance()->GetServiceForBrowserContext(context, true)); +} + +// static +CertificateProviderServiceFactory* +CertificateProviderServiceFactory::GetInstance() { + return base::Singleton::get(); +} + +CertificateProviderServiceFactory::CertificateProviderServiceFactory() + : BrowserContextKeyedServiceFactory( + "CertificateProviderService", + BrowserContextDependencyManager::GetInstance()) { + DependsOn(extensions::EventRouterFactory::GetInstance()); + DependsOn(extensions::ExtensionRegistryFactory::GetInstance()); +} + +content::BrowserContext* +CertificateProviderServiceFactory::GetBrowserContextToUse( + content::BrowserContext* context) const { + return chrome::GetBrowserContextRedirectedInIncognito(context); +} + +bool CertificateProviderServiceFactory::ServiceIsNULLWhileTesting() const { + return true; +} + +KeyedService* CertificateProviderServiceFactory::BuildServiceInstanceFor( + content::BrowserContext* context) const { + CertificateProviderService* const service = new CertificateProviderService(); + service->SetDelegate(base::WrapUnique(new DefaultDelegate( + service, + extensions::ExtensionRegistryFactory::GetForBrowserContext(context), + extensions::EventRouterFactory::GetForBrowserContext(context)))); + return service; +} + +} // namespace chromeos diff --git a/pool/shard001/C++/0023138_genericchatitemwidget.cpp b/pool/shard001/C++/0023138_genericchatitemwidget.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e58fb28740d72a1c34ac23aacc98a53e53b381c7 --- /dev/null +++ b/pool/shard001/C++/0023138_genericchatitemwidget.cpp @@ -0,0 +1,54 @@ +/* + Copyright © 2015 by The qTox Project Contributors + + This file is part of qTox, a Qt-based graphical interface for Tox. + + qTox is libre 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. + + qTox 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 qTox. If not, see . +*/ + +#include "genericchatitemwidget.h" +#include "src/widget/style.h" +#include "src/persistence/settings.h" +#include "src/widget/tool/croppinglabel.h" +#include + +GenericChatItemWidget::GenericChatItemWidget(QWidget* parent) + : QFrame(parent), compact(false) +{ + setProperty("compact", Settings::getInstance().getCompactLayout()); + + nameLabel = new CroppingLabel(this); + nameLabel->setObjectName("name"); + nameLabel->setTextFormat(Qt::PlainText); +} + +bool GenericChatItemWidget::isCompact() const +{ + return compact; +} + +void GenericChatItemWidget::setCompact(bool compact) +{ + this->compact = compact; +} + +QString GenericChatItemWidget::getName() const +{ + return nameLabel->fullText(); +} + +void GenericChatItemWidget::searchName(const QString &searchString, bool hide) +{ + setVisible(!hide && getName().contains(searchString, Qt::CaseInsensitive)); +} diff --git a/pool/shard001/C++/0023140_main.cpp b/pool/shard001/C++/0023140_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4993005470e39deaa93e4df2adf7272bbd97c2c7 --- /dev/null +++ b/pool/shard001/C++/0023140_main.cpp @@ -0,0 +1,41 @@ +#include "../common/common.h" +#include "bridge_interface.h" +#include "robot_bridge_agent.h" +#include "gui/gui.h" + +class CBridgeInterface *bridge_interface; +class CGUI *gui; + +void application_main_func() +{ + struct sAgentGroupInitStruct agent_group_init_struct; + + agent_group_init_struct.count = 1; + agent_group_init_struct.random_positions = true; + agent_group_init_struct.dt = 500.0; + + class CClient *client; + class CRobotBridgeAgent *agent = new CRobotBridgeAgent(); + + + client = new CClient(agent_group_init_struct, agent); + client->main(); + + delete client; + + exit(EXIT_SUCCESS); +} + +int main() +{ + bridge_interface = new CBridgeInterface(); + + gui = new CGUI(bridge_interface); + gui->run(application_main_func); + + printf("program \'bridge agent\' done\n"); + + delete gui; + delete bridge_interface; + return 0; +} diff --git a/pool/shard001/C++/0023147_main.cpp b/pool/shard001/C++/0023147_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..776b704e75cfcb10870fd329041a99719c0598cc --- /dev/null +++ b/pool/shard001/C++/0023147_main.cpp @@ -0,0 +1,224 @@ +// Standard library headers. +#include +#include + +// Graphics library headers. +#include + +// blackhart headers. +#include "..\..\blackhart\export\cpp\Blackhart.hpp" + +// blackhart.studio headers. +#include "foundation\BkTime.hpp" + +// Globales +static struct BkOrbitalCamera g_camera; +static bool g_full_screen = false; + +// Constantes +static char const* APP_TITLE = "Blackhart Studio"; + +// ~~~~~ Dcl(INTERNAL) ~~~~~ + +static void InputCallback(GLFWwindow* window, int key, int scancode, int action, int mods); +static void MouseCallback(GLFWwindow* window, double posx, double posy); +static void ResizeCallback(GLFWwindow* window, int width, int height); +static void ErrorCallback(int error, const char* msg); +static void ShowFPS(GLFWwindow* window); + +// ~~~~~ Def(ALL) ~~~~~ + +int main() +{ + // ~~~~~ GLFW INITIALIZATION ~~~~~~ + + // Initialize glfw + if (!glfwInit()) + goto EXIT; + + // Set error callback function + glfwSetErrorCallback(ErrorCallback); + + // Initialize glfw windows and set OpenGL context + glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_API); + //glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); + //glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); + //glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_ANY_PROFILE); + + GLFWwindow* window = NULL; + + if (g_full_screen) + { + GLFWmonitor* monitor = glfwGetPrimaryMonitor(); + GLFWvidmode const* vid_mode = glfwGetVideoMode(monitor); + + if (vid_mode != NULL) + window = glfwCreateWindow(vid_mode->width, vid_mode->height, APP_TITLE, monitor, NULL); + } + else + { + uint16 const window_width = 800; + uint16 const window_height = 600; + + window = glfwCreateWindow(window_width, window_height, APP_TITLE, NULL, NULL); + } + + if (window == NULL) + goto GLFW_TERMINATE; + + glfwMakeContextCurrent(window); + + // Set key callback function + glfwSetKeyCallback(window, InputCallback); + + // Set mouse callback + glfwSetCursorPosCallback(window, MouseCallback); + + // Set resize callback function + glfwSetWindowSizeCallback(window, ResizeCallback); + + // Set swap interval of the double buffering + glfwSwapInterval(1); + + + // ~~~~~ BLACKHART INITIALIZATION ~~~~~ + + // Initialize Blackhart + BkInitialize(); + + // Initialize Camera + BkOrbitalCamera_Initialize(&g_camera); + struct BkPoint3 const to = BkPoint3_FromXYZ(BK_REAL(0.0), BK_REAL(0.0), BK_REAL(0.0)); + BkOrbitalCamera_SetTarget(&g_camera, &to); + BkOrbitalCamera_SetRadius(&g_camera, BK_REAL(5)); + + // ~~~~~ RENDER LOOP ~~~~~ + + // Initialize OpenGL viewport + int width = 0; + int height = 0; + + glfwGetWindowSize(window, &width, &height); + ResizeCallback(window, width, height); + + // Main loop + while (!glfwWindowShouldClose(window)) + { + BkTime_Update(); + + BkOrbitalCamera_Rotate(&g_camera, BK_REAL(50) * BK_REAL(BkTime_DeltaTime()), BK_REAL(0)); + + ShowFPS(window); + + glfwPollEvents(); + + BkRender(&(g_camera.base)); + + glfwSwapBuffers(window); + } + + + // ~~~~~ BLACKHART UNINITIALIZATION ~~~~~ + + BkUninitialize(); + + + // ~~~~~ GLFW UNINITIALIZATION ~~~~~ + + glfwDestroyWindow(window); + +GLFW_TERMINATE: + glfwTerminate(); + +EXIT: + return EXIT_SUCCESS; +} + +void InputCallback(GLFWwindow* window, int key, int scancode, int action, int mods) +{ + (void)mods; + (void)scancode; + (void)window; + + // ~~~~~ GLFW EVENTS ~~~~~~ + + if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) + glfwSetWindowShouldClose(window, GLFW_TRUE); +} + +void MouseCallback(GLFWwindow* window, double posx, double posy) +{ + static double last_mouse_pos[2] = { 0.0, 0.0 }; + static double rotation_zpeed = 20.0; + static double zoom_speed = 3.0; + + if (glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT) == 1) + { + double yaw = (posx - last_mouse_pos[0]) * rotation_zpeed * BkTime_DeltaTime(); + double pitch = (posy - last_mouse_pos[1]) * rotation_zpeed * BkTime_DeltaTime(); + BkOrbitalCamera_Rotate(&g_camera, BK_REAL(yaw), BK_REAL(pitch)); + } + + if (glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_RIGHT)) + { + double dx = (posx - last_mouse_pos[0]) * zoom_speed * BkTime_DeltaTime(); + double dy = (posy - last_mouse_pos[1]) * zoom_speed * BkTime_DeltaTime(); + double radius = dx - dy; + BkOrbitalCamera_Zoom(&g_camera, BK_REAL(radius)); + } + + last_mouse_pos[0] = posx; + last_mouse_pos[1] = posy; +} + +void ResizeCallback(GLFWwindow* window, int width, int height) +{ + (void)window; + + glViewport(0, 0, width, height); + g_camera.base.projection = BkProjection_Perspective(BK_REAL(45), BK_REAL(width) / BK_REAL(height), BK_REAL(0.1), BK_REAL(1000)); +} + +void ErrorCallback(int error, const char* msg) +{ + (void)error; + + std::cout << "Fatal: " << msg << std::endl; + exit(EXIT_FAILURE); +} + +void ShowFPS(GLFWwindow* window) +{ + static double previous_seconds = 0; + static int frame_count = 0; + + double elapsed_seconds = 0; + + // Returns number of seconds since GLFW started. + double currend_seconds = glfwGetTime(); + + elapsed_seconds = currend_seconds - previous_seconds; + + // Limit text update 4 times per seconds. + if (elapsed_seconds > 0.25) + { + previous_seconds = currend_seconds; + double fps = (double)frame_count / elapsed_seconds; + double ms_per_frame = 1000.0 / fps; + + std::ostringstream out; + + out.precision(3); + + out << std::fixed + << APP_TITLE << " | " + << "FPS: " << fps << " | " + << "Frame time: " << ms_per_frame << " (ms)"; + + glfwSetWindowTitle(window, out.str().c_str()); + + frame_count = 0; + } + + frame_count++; +} \ No newline at end of file diff --git a/pool/shard001/C++/0023155_PreProcessor.cpp b/pool/shard001/C++/0023155_PreProcessor.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e6c046781d882670ec8e80328778aab221a74872 --- /dev/null +++ b/pool/shard001/C++/0023155_PreProcessor.cpp @@ -0,0 +1,149 @@ +/* +This file is part of BGSLibrary. + +BGSLibrary 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. + +BGSLibrary 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 BGSLibrary. If not, see . +*/ +#include "PreProcessor.h" + +namespace bgslibrary +{ + PreProcessor::PreProcessor() : firstTime(true), equalizeHist(false), gaussianBlur(false) + { + std::cout << "PreProcessor()" << std::endl; + } + + PreProcessor::~PreProcessor() + { + std::cout << "~PreProcessor()" << std::endl; + } + + void PreProcessor::setEqualizeHist(bool value) + { + equalizeHist = value; + } + + void PreProcessor::setGaussianBlur(bool value) + { + gaussianBlur = value; + } + + cv::Mat PreProcessor::getGrayScale() + { + return img_gray.clone(); + } + + void PreProcessor::process(const cv::Mat &img_input, cv::Mat &img_output) + { + if (img_input.empty()) + return; + + loadConfig(); + + if (firstTime) + saveConfig(); + + img_input.copyTo(img_output); + + // Converts image from one color space to another + // http://opencv.willowgarage.com/documentation/cpp/miscellaneous_image_transformations.html#cv-cvtcolor + cv::cvtColor(img_input, img_gray, CV_BGR2GRAY); + //img_gray.copyTo(img_output); + + // Equalizes the histogram of a grayscale image + // http://opencv.willowgarage.com/documentation/cpp/histograms.html#cv-equalizehist + if (equalizeHist) + cv::equalizeHist(img_output, img_output); + + // Smoothes image using a Gaussian filter + // http://opencv.willowgarage.com/documentation/cpp/imgproc_image_filtering.html#GaussianBlur + if (gaussianBlur) + cv::GaussianBlur(img_output, img_output, cv::Size(7, 7), 1.5); + + if (enableShow) + cv::imshow("Pre Processor", img_output); + + firstTime = false; + } + + void PreProcessor::rotate(const cv::Mat &img_input, cv::Mat &img_output, float angle) + { + IplImage* image = new IplImage(img_input); + + //IplImage *rotatedImage = cvCreateImage(cvSize(480,320), IPL_DEPTH_8U, image->nChannels); + //IplImage *rotatedImage = cvCreateImage(cvSize(image->width,image->height), IPL_DEPTH_8U, image->nChannels); + IplImage* rotatedImage = cvCreateImage(cvSize(image->height, image->width), IPL_DEPTH_8U, image->nChannels); + + CvPoint2D32f center; + //center.x = 160; + //center.y = 160; + center.x = (image->height / 2); + center.y = (image->width / 2); + + CvMat* mapMatrix = cvCreateMat(2, 3, CV_32FC1); + + cv2DRotationMatrix(center, angle, 1.0, mapMatrix); + cvWarpAffine(image, rotatedImage, mapMatrix, CV_INTER_LINEAR + CV_WARP_FILL_OUTLIERS, cvScalarAll(0)); + + cv::Mat img_rot(rotatedImage); + img_rot.copyTo(img_output); + + cvReleaseImage(&image); + cvReleaseImage(&rotatedImage); + cvReleaseMat(&mapMatrix); + } + + void PreProcessor::applyCanny(const cv::Mat &img_input, cv::Mat &img_output) + { + if (img_input.empty()) + return; + + //------------------------------------------------------------------ + // Canny + // Finds edges in an image using Canny algorithm. + // http://opencv.willowgarage.com/documentation/cpp/imgproc_feature_detection.html#cv-canny + //------------------------------------------------------------------ + + cv::Mat img_canny; + cv::Canny( + img_input, // image – Single-channel 8-bit input image + img_canny, // edges – The output edge map. It will have the same size and the same type as image + 100, // threshold1 – The first threshold for the hysteresis procedure + 200); // threshold2 – The second threshold for the hysteresis procedure + cv::threshold(img_canny, img_canny, 128, 255, cv::THRESH_BINARY_INV); + + img_canny.copyTo(img_output); + } + + void PreProcessor::saveConfig() + { + CvFileStorage* fs = cvOpenFileStorage("./config/PreProcessor.xml", 0, CV_STORAGE_WRITE); + + cvWriteInt(fs, "equalizeHist", equalizeHist); + cvWriteInt(fs, "gaussianBlur", gaussianBlur); + cvWriteInt(fs, "enableShow", enableShow); + + cvReleaseFileStorage(&fs); + } + + void PreProcessor::loadConfig() + { + CvFileStorage* fs = cvOpenFileStorage("./config/PreProcessor.xml", 0, CV_STORAGE_READ); + + equalizeHist = cvReadIntByName(fs, 0, "equalizeHist", false); + gaussianBlur = cvReadIntByName(fs, 0, "gaussianBlur", false); + enableShow = cvReadIntByName(fs, 0, "enableShow", true); + + cvReleaseFileStorage(&fs); + } +} diff --git a/pool/shard001/C++/0023161_HcSr04.cpp b/pool/shard001/C++/0023161_HcSr04.cpp new file mode 100644 index 0000000000000000000000000000000000000000..308371cafdd9962c69a5512abd83b0cd2c96d78e --- /dev/null +++ b/pool/shard001/C++/0023161_HcSr04.cpp @@ -0,0 +1,47 @@ +/* + Generic Robot with obstacle avoidance capabilities + Copyright (C) 2014 Joao Salavisa (joao.salavisa@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 +#include "HcSr04.h" + +HcSr04::HcSr04(int echoPin, int triggerPin) { + _echoPin = echoPin; + _triggerPin = triggerPin; + + pinMode(_triggerPin, OUTPUT); + pinMode(_echoPin, INPUT); +} + + +long HcSr04::read_distance() { + + long duration, distance; + + digitalWrite(_triggerPin, LOW); + delayMicroseconds(2); + digitalWrite(_triggerPin, HIGH); + delayMicroseconds(10); + digitalWrite(_triggerPin, LOW); + duration = pulseIn(_echoPin, HIGH); + + // Duration in microseconds + distance = duration / 58.2; + + return distance; + +} diff --git a/pool/shard001/C++/0023166_vga_win.cpp b/pool/shard001/C++/0023166_vga_win.cpp new file mode 100644 index 0000000000000000000000000000000000000000..40aaeef5f4942ff455dfb78ada0cfaa5f07fc665 --- /dev/null +++ b/pool/shard001/C++/0023166_vga_win.cpp @@ -0,0 +1,259 @@ +/* + * Seven Kingdoms: Ancient Adversaries + * + * Copyright 1997,1998 Enlight Software Ltd. + * Copyright 2010 Jesse Allen + * + * 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 . + * + */ + +#include +#include +#include +#include +#include + +DBGLOG_DEFAULT_CHANNEL(Vga); + +//------- Define static functions -----------// + +static long FAR PASCAL main_win_proc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam); + +//-------- Begin of function VgaDDraw::create_window --------// +// +int VgaDDraw::create_window() +{ + app_hinstance = (HINSTANCE)GetModuleHandle(NULL); + + //--------- register window class --------// + + WNDCLASS wc; + BOOL rc; + + wc.style = CS_DBLCLKS; + wc.lpfnWndProc = main_win_proc; + wc.cbClsExtra = 0; + wc.cbWndExtra = 0; + wc.hInstance = app_hinstance; + wc.hIcon = LoadIcon( app_hinstance, MAKEINTATOM(IDI_ICON1)); + wc.hCursor = LoadCursor( NULL, IDC_ARROW ); + wc.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH); + wc.lpszMenuName = NULL; + wc.lpszClassName = WIN_CLASS_NAME; + + rc = RegisterClass( &wc ); + + if( !rc ) + return 0; + + //--------- create window -----------// + + main_hwnd = CreateWindowEx( + WS_EX_APPWINDOW | WS_EX_TOPMOST, + WIN_CLASS_NAME, + WIN_TITLE, + WS_VISIBLE | // so we dont have to call ShowWindow + WS_POPUP, + 0, + 0, + GetSystemMetrics(SM_CXSCREEN), + GetSystemMetrics(SM_CYSCREEN), + NULL, + NULL, + app_hinstance, + NULL ); + + if( !main_hwnd ) + return 0; + + UpdateWindow( main_hwnd ); + SetFocus( main_hwnd ); + + ShowCursor(FALSE); + + return 1; +} +//-------- End of function VgaDDraw::create_window --------// + +//-------- Begin of function VgaDDraw::destroy_window --------// +// +void VgaDDraw::destroy_window() +{ +/* + extern char low_video_memory_flag; + + if( low_video_memory_flag ) + { + ShowWindow(sys.main_hwnd, SW_MINIMIZE ); + + unsigned curTime = misc.get_time(); + while( misc.get_time() < curTime + 4000 ); + } +*/ + //---------------------------------------// + + if (main_hwnd) { + PostMessage(main_hwnd, WM_CLOSE, 0, 0); + + MSG msg; + + while( GetMessage(&msg, NULL, 0, 0) ) + { + TranslateMessage(&msg); + DispatchMessage(&msg); + } + + main_hwnd = NULL; + } +} +//-------- End of function VgaDDraw::destroy_window --------// + +//--------- Begin of static function main_win_proc --------// +// +// Callback for all Windows messages +// +static long FAR PASCAL main_win_proc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) +{ + switch( message ) + { + case WM_CREATE: + vga.main_hwnd = hWnd; + break; + + case WM_ACTIVATEAPP: + //--------------------------------------------------------------// + // while we were not-active something bad happened that caused us + // to pause, like a surface restore failing or we got a palette + // changed, now that we are active try to fix things + //--------------------------------------------------------------// + + // check if we are restoring or minimizing + if ((BOOL)wParam && !IsIconic(hWnd)) + { + //-----------------------------------------------------// + // if we are unable to restore, this can happen when + // the screen resolution or bitdepth has changed + // we just reload all the art again and re-create + // the front and back buffers. this is a little + // overkill we could handle a screen res change by + // just recreating the front and back buffers we dont + // need to redo the art, but this is way easier. + //-----------------------------------------------------// + + // attempt to restore window + if (vga.restore() || (vga.init() && vga.restore())) { + sys.need_redraw_flag = 1; // for Sys::disp_frame to redraw the screen + if (!sys.is_mp_game) + sys.unpause(); + + // update ctrl/shift/alt key state + mouse.update_skey_state(); + } else { + // The screen wasn't restored. The game is not usable. + ERR("Lost buffers in main_win_proc!\n"); + } + } + else if (!sys.is_mp_game) + sys.pause(); + break; + + case WM_DESTROY: + vga.main_hwnd = NULL; + // game.deinit(); // end of game + sys.deinit_directx(); + PostQuitMessage( 0 ); + break; + + case WM_ERASEBKGND: + // do not erase the background + return 1; + + case WM_PALETTECHANGED: + // if we changed the palette, do nothing + if ((HWND)wParam == hWnd) break; + + // set the current palette again + vga.refresh_palette(); + break; + + default: + break; + } + + return DefWindowProc(hWnd, message, wParam, lParam); +} +//--------- End of static function main_win_proc --------// + +//-------- Begin of function VgaDDraw::handle_messages --------// +void VgaDDraw::handle_messages() +{ + static int lastTick; + MSG msg; + + int tick = GetTickCount(); + if (lastTick == tick) + return; + lastTick = tick; + + //---- if any of the DirectDraw buffers are lost; restore ----// + if ((vga_front.is_buf_lost() || + vga_back.is_buf_lost() || + (sys.debug_session && vga_true_front.is_buf_lost())) && + !VgaDDraw::restore()) + { + ERR("Lost buffers!\n"); + } + + while (PeekMessage(&msg, main_hwnd, 0, 0, PM_NOREMOVE)) + { + BOOL r; + + r = GetMessage(&msg, main_hwnd, 0, 0); + if (r == -1) + { + // not handled + return; + } + + TranslateMessage(&msg); + DispatchMessage(&msg); + } +} +//-------- End of function VgaDDraw::handle_messages --------// + +//-------- Begin of function VgaDDraw::flag_redraw --------// +void VgaDDraw::flag_redraw() +{ + InvalidateRect(main_hwnd, NULL, TRUE); +} +//-------- End of function VgaDDraw::flag_redraw ----------// + + +//-------- Begin of function VgaDDraw::is_full_screen --------// +// +int VgaDDraw::is_full_screen() +{ + return 0; +} +//-------- End of function VgaDDraw::is_full_screen ----------// + + +//-------- Begin of function VgaDDraw::toggle_full_screen --------// +void VgaDDraw::toggle_full_screen() +{ + // unsupported +} +//-------- End of function VgaDDraw::toggle_full_screen ----------// + diff --git a/pool/shard001/C++/0023177_TileLoaderRunnable.cpp b/pool/shard001/C++/0023177_TileLoaderRunnable.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cb53cc238d13c30839112d867b099e270f8ec3d8 --- /dev/null +++ b/pool/shard001/C++/0023177_TileLoaderRunnable.cpp @@ -0,0 +1,206 @@ +/************************************************************************************************ +* Copyright (C) 2014 by Tristan Dyer * +* * +* This file is part of SMT. * +* * +* SMT 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. * +* * +* SMT 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 SMT. If not, see . * +* * +************************************************************************************************/ + +#include "TileLoaderRunnable.h" + +static int currSatelliteURL = 1; +static QString nextSatelliteURL() +{ + currSatelliteURL = currSatelliteURL == 5 ? 1 : currSatelliteURL; + QString url = "http://otile" + QString::number(currSatelliteURL++) + ".mqcdn.com/tiles/1.0.0/sat/"; + return url; +} + +static int currStreetURL = 1; +static QString nextStreetURL() +{ + currStreetURL = currStreetURL == 4 ? 1 : currStreetURL; + QString url = "http://" + + (currStreetURL == 1 ? QString('a') : + (currStreetURL == 2 ? QString('b') : + QString('c'))) + + ".tile.openstreetmap.org/"; + ++currStreetURL; + return url; +} + +static int currTerrainURL = 1; +static QString nextTerrainURL() +{ + currTerrainURL = currTerrainURL == 5 ? 1 : currTerrainURL; + QString url = "http://" + + (currTerrainURL == 1 ? QString('a') : + (currTerrainURL == 2 ? QString('b') : + currTerrainURL == 3 ? QString('c') : + QString('d'))) + + ".tile.stamen.com/terrain-background/"; + ++currTerrainURL; + return url; +} + +static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) +{ + size_t realsize = size*nmemb; + struct RawImageData *mem = (struct RawImageData *)userp; + + mem->memory = (uchar*)realloc(mem->memory, mem->size + realsize + 1); + if (mem->memory == NULL) + { + return 0; + } + + memcpy(&(mem->memory[mem->size]), contents, realsize); + mem->size += realsize; + mem->memory[mem->size] = 0; + + return realsize; +} + +TileLoaderRunnable::TileLoaderRunnable(TileType tileType, int tileX, int tileY, int zoom) +{ + skip = false; + type = tileType; + x = tileX; + y = tileY; + z = zoom; + + setAutoDelete(false); +} + + +TileLoaderRunnable::~TileLoaderRunnable() +{ +// std::cout << "Deleting Tile Loader Runnable" << std::endl; + if (imageData.memory) + free(imageData.memory); +// std::cout << "Deleted Tile Loader Runnable" << std::endl; +} + + +void TileLoaderRunnable::run() +{ +// std::cout << "Worker thread: " << QThread::currentThread() << std::endl; + if (!skip) + { + + // Load the tile + QString imageURL = BuildURL(); + + if (!imageURL.isEmpty()) + { + + CURL *image = 0; + image = curl_easy_init(); + + if (image) + { + curl_easy_setopt(image, CURLOPT_NOSIGNAL, 1); + curl_easy_setopt(image, CURLOPT_URL, imageURL.toStdString().data()); + curl_easy_setopt(image, CURLOPT_WRITEFUNCTION, WriteMemoryCallback); + curl_easy_setopt(image, CURLOPT_WRITEDATA, (void*)&imageData); + curl_easy_setopt(image, CURLOPT_NOSIGNAL, 1); + curl_easy_setopt(image, CURLOPT_TIMEOUT, 3); + +// std::cout << "Requesting tile: " << imageURL.toStdString().data() << std::endl; + CURLcode fetchResult = curl_easy_perform(image); +// std::cout << "Requesting tile: " << imageURL.toStdString().data() << " - Received" << std::endl; + + QImage qImage; + bool loaded = false; + bool valid = false; + + if (fetchResult != CURLE_OK) + { + std::cout << "Failed to retrieve tile: " + << curl_easy_strerror(fetchResult) << std::endl; + loaded = qImage.load(":/tiles/images/tiles/noload.png"); + } else { + if (type == StreetTile) + loaded = qImage.loadFromData(imageData.memory, (int)imageData.size, "PNG"); + else + loaded = qImage.loadFromData(imageData.memory, (int)imageData.size, "JPG"); + + // If it wasn't loaded, load the error image + if (loaded) + valid = true; + else + loaded = qImage.load(":/tiles/images/tiles/noload.png"); + } + + if (loaded) + { + // Convert format + QImage formattedImage = qImage.convertToFormat(QImage::Format_ARGB32); + + // Create new image on heap that is a shallow copy of the GL version of the image + QImage *finalImage = new QImage(QGLWidget::convertToGLFormat(formattedImage)); + emit finished(finalImage, valid); + + } else { + std::cout << "Unable to load image data: " << imageURL.toStdString().data() << std::endl; + emit finished(0, false); + } + + curl_easy_cleanup(image); + + } else { + emit finished(0, false); + } + + } else { + emit finished(0, false); + } + } else { +// std::cout << "Skipping tile" << std::endl; + emit finished(0, false); + } +} + + +QString TileLoaderRunnable::BuildURL() +{ + QString url; + if (type == SatelliteTile) + { + url = nextSatelliteURL() + + QString::number(z) + "/" + + QString::number(x) + "/" + + QString::number(y) + ".jpg"; + } + else if (type == StreetTile) + { + url = nextStreetURL() + + QString::number(z) + "/" + + QString::number(x) + "/" + + QString::number(y) + ".png"; + } + else if (type == TerrainTile) + { + url = nextTerrainURL() + + QString::number(z) + "/" + + QString::number(x) + "/" + + QString::number(y) + ".jpg"; + } + return url; +} + + +void TileLoaderRunnable::setSkip(bool newSkip) +{ + skip = newSkip; +} diff --git a/pool/shard001/C++/0023178_connectors_internals_ui.cc b/pool/shard001/C++/0023178_connectors_internals_ui.cc new file mode 100644 index 0000000000000000000000000000000000000000..2486c5d217d4dad3fddaf2f06e90709bd4fa8bea --- /dev/null +++ b/pool/shard001/C++/0023178_connectors_internals_ui.cc @@ -0,0 +1,55 @@ +// 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 "chrome/browser/ui/webui/connectors_internals/connectors_internals_ui.h" + +#include "base/bind.h" +#include "base/feature_list.h" +#include "build/build_config.h" +#include "chrome/browser/enterprise/connectors/device_trust/device_trust_features.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/ui/webui/connectors_internals/connectors_internals.mojom.h" +#include "chrome/browser/ui/webui/connectors_internals/connectors_internals_page_handler.h" +#include "chrome/browser/ui/webui/webui_util.h" +#include "chrome/common/url_constants.h" +#include "chrome/grit/browser_resources.h" +#include "chrome/grit/connectors_internals_resources.h" +#include "chrome/grit/connectors_internals_resources_map.h" +#include "content/public/browser/web_ui_data_source.h" +#include "mojo/public/cpp/bindings/pending_receiver.h" + +namespace enterprise_connectors { + +ConnectorsInternalsUI::ConnectorsInternalsUI(content::WebUI* web_ui) + : ui::MojoWebUIController(web_ui) { + content::WebUIDataSource* source = content::WebUIDataSource::Create( + chrome::kChromeUIConnectorsInternalsHost); + + Profile* profile = Profile::FromWebUI(web_ui); + + source->AddBoolean("isOtr", profile->IsOffTheRecord()); + source->AddBoolean( + "zeroTrustConnectorEnabled", + base::FeatureList::IsEnabled(kDeviceTrustConnectorEnabled)); + + webui::SetupWebUIDataSource( + source, + base::make_span(kConnectorsInternalsResources, + kConnectorsInternalsResourcesSize), + IDR_CONNECTORS_INTERNALS_INDEX_HTML); + + content::WebUIDataSource::Add(profile, source); +} + +WEB_UI_CONTROLLER_TYPE_IMPL(ConnectorsInternalsUI) + +ConnectorsInternalsUI::~ConnectorsInternalsUI() = default; + +void ConnectorsInternalsUI::BindInterface( + mojo::PendingReceiver receiver) { + page_handler_ = std::make_unique( + std::move(receiver), Profile::FromWebUI(web_ui())); +} + +} // namespace enterprise_connectors diff --git a/pool/shard001/C++/0023179_mnemonic.cpp b/pool/shard001/C++/0023179_mnemonic.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e4c9e1941ddf959a859ffa4e708eef773d07603c --- /dev/null +++ b/pool/shard001/C++/0023179_mnemonic.cpp @@ -0,0 +1,51 @@ +#include +#include + +using namespace bc; + +bool display_help() +{ + puts("Usage:"); + puts(""); + puts(" mnemonic <<< \"[WORD1] [WORD2] ...\""); + puts(" mnemonic <<< SEED"); + puts(""); + puts("Please email suggestions and questions to ."); + return -1; +} + +int main(int argc, char** argv) +{ + std::istreambuf_iterator it(std::cin); + std::istreambuf_iterator end; + std::string data(it, end); + boost::algorithm::trim(data); + string_list words; + boost::split(words, data, boost::is_any_of("\n\t ")); + if (words.empty()) + return display_help(); + else if (words.size() == 1 && + words[0].size() == deterministic_wallet::seed_size) + { + const std::string seed = words[0]; + string_list words = encode_mnemonic(seed); + bool first = true; + for (const std::string& word: words) + { + if (!first) + std::cout << " "; + std::cout << word; + first = false; + } + std::cout << std::endl; + return 0; + } + else + { + std::cout << decode_mnemonic(words) << std::endl; + return 0; + } + // Should never happen! + return 0; +} + diff --git a/pool/shard001/C++/0023181_pirackeyset.cpp b/pool/shard001/C++/0023181_pirackeyset.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b5263e0798dda8da442a22a555c56b2b774ce2b4 --- /dev/null +++ b/pool/shard001/C++/0023181_pirackeyset.cpp @@ -0,0 +1,84 @@ +// +// pirackeyset.cpp +// + +#include "pirackeyset.h" + +PIRACKeyset::PIRACKeyset( + const char *keysetName, + PIRMakeName make, + unsigned int index) + : PIRKeysetMetaData(keysetName, make, StatefulAC_Panels, index) +{ +} + + +void PIRACKeyset::getTurboModePairs( + PIRStatePairs &turboModePairs) const +{ + resetPairs(turboModePairs); +} + + +void PIRACKeyset::getSwingPairs( + PIRStatePairs &swingPairs) const +{ + resetPairs(swingPairs); +} + + +void PIRACKeyset::getTemperaturePairs( + PIRStatePairs &temperaturePairs) const +{ + resetPairs(temperaturePairs); +} + + +void PIRACKeyset::getFanPairs( + PIRStatePairs &fanPairs) const +{ + resetPairs(fanPairs); +} + + +void PIRACKeyset::getModePairs( + PIRStatePairs &modePairs) const +{ + resetPairs(modePairs); +} + + +void PIRACKeyset::getAirCleanPairs( + PIRStatePairs &aircleanPairs) const +{ + resetPairs(aircleanPairs); +} + + +void PIRACKeyset::getPowerPairs( + PIRStatePairs &powerPairs) const +{ + resetPairs(powerPairs); +} + + +void PIRACKeyset::getTimerOptionPairs( + PIRStatePairs &timerOptionPairs) const +{ + resetPairs(timerOptionPairs); +} + + +void PIRACKeyset::resetPairs( + PIRStatePairs &pairs) const +{ + PIRStatePairs::iterator i = pairs.begin(); + + while (i != pairs.end()) + { + delete (*i); + ++i; + } + + pairs.clear(); +} diff --git a/pool/shard001/C++/0023183_wavefilter.cpp b/pool/shard001/C++/0023183_wavefilter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..61f4f7b5ce66e372c79e4e1d4eaa3b3c0fe12fca --- /dev/null +++ b/pool/shard001/C++/0023183_wavefilter.cpp @@ -0,0 +1,183 @@ +/* + * This file is part of the KDE project + * + * Copyright (c) 2005 Cyrille Berger + * + * 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 "wavefilter.h" +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "kis_wdg_wave.h" +#include "ui_wdgwaveoptions.h" +#include + +K_PLUGIN_FACTORY(KritaWaveFilterFactory, registerPlugin();) +K_EXPORT_PLUGIN(KritaWaveFilterFactory("krita")) + +class KisWaveCurve +{ +public: + virtual ~KisWaveCurve() {} + virtual double valueAt(int x, int y) = 0; +}; + +class KisSinusoidalWaveCurve : public KisWaveCurve +{ +public: + + KisSinusoidalWaveCurve(int amplitude, int wavelength, int shift) : m_amplitude(amplitude), m_wavelength(wavelength), m_shift(shift) { + } + + virtual ~KisSinusoidalWaveCurve() {} + + virtual double valueAt(int x, int y) { + return y + m_amplitude * cos((double)(m_shift + x) / m_wavelength); + } +private: + int m_amplitude, m_wavelength, m_shift; +}; + +class KisTriangleWaveCurve : public KisWaveCurve +{ +public: + + KisTriangleWaveCurve(int amplitude, int wavelength, int shift) : m_amplitude(amplitude), m_wavelength(wavelength), m_shift(shift) { + } + + virtual ~KisTriangleWaveCurve() {} + + virtual double valueAt(int x, int y) { + return y + m_amplitude * pow(-1.0, (m_shift + x) / m_wavelength) *(0.5 - (double)((m_shift + x) % m_wavelength) / m_wavelength); + } +private: + int m_amplitude, m_wavelength, m_shift; +}; KritaWaveFilter::KritaWaveFilter(QObject *parent, const QVariantList &) + : QObject(parent) +{ + KisFilterRegistry::instance()->add(new KisFilterWave()); +} + +KritaWaveFilter::~KritaWaveFilter() +{ +} + +KisFilterWave::KisFilterWave() : KisFilter(id(), categoryOther(), i18n("&Wave...")) +{ + setColorSpaceIndependence(FULLY_INDEPENDENT); + setSupportsPainting(false); + setSupportsIncrementalPainting(false); + setSupportsAdjustmentLayers(false); + +} + +KisFilterConfiguration* KisFilterWave::factoryConfiguration(const KisPaintDeviceSP) const +{ + KisFilterConfiguration* config = new KisFilterConfiguration("wave", 1); + config->setProperty("horizontalwavelength", 50); + config->setProperty("horizontalshift", 50); + config->setProperty("horizontalamplitude", 4); + config->setProperty("horizontalshape", 0); + config->setProperty("verticalwavelength", 50); + config->setProperty("verticalshift", 50); + config->setProperty("verticalamplitude", 4); + config->setProperty("verticalshape", 0); + return config; +} + +KisConfigWidget * KisFilterWave::createConfigurationWidget(QWidget* parent, const KisPaintDeviceSP, const KisImageWSP) const +{ + return new KisWdgWave((KisFilter*)this, (QWidget*)parent); +} + +void KisFilterWave::process(KisPaintDeviceSP device, + const QRect& applyRect, + const KisFilterConfiguration* config, + KoUpdater* progressUpdater + ) const +{ + Q_ASSERT(device.data() != 0); + + int cost = (applyRect.width() * applyRect.height()) / 100; + if (cost == 0) cost = 1; + int count = 0; + + QVariant value; + int horizontalwavelength = (config && config->getProperty("horizontalwavelength", value)) ? value.toInt() : 50; + int horizontalshift = (config && config->getProperty("horizontalshift", value)) ? value.toInt() : 50; + int horizontalamplitude = (config && config->getProperty("horizontalamplitude", value)) ? value.toInt() : 4; + int horizontalshape = (config && config->getProperty("horizontalshape", value)) ? value.toInt() : 0; + int verticalwavelength = (config && config->getProperty("verticalwavelength", value)) ? value.toInt() : 50; + int verticalshift = (config && config->getProperty("verticalshift", value)) ? value.toInt() : 50; + int verticalamplitude = (config && config->getProperty("verticalamplitude", value)) ? value.toInt() : 4; + int verticalshape = (config && config->getProperty("verticalshape", value)) ? value.toInt() : 0; + KisRectIteratorSP dstIt = device->createRectIteratorNG(applyRect); + KisWaveCurve* verticalcurve; + if (verticalshape == 1) + verticalcurve = new KisTriangleWaveCurve(verticalamplitude, verticalwavelength, verticalshift); + else + verticalcurve = new KisSinusoidalWaveCurve(verticalamplitude, verticalwavelength, verticalshift); + KisWaveCurve* horizontalcurve; + if (horizontalshape == 1) + horizontalcurve = new KisTriangleWaveCurve(horizontalamplitude, horizontalwavelength, horizontalshift); + else + horizontalcurve = new KisSinusoidalWaveCurve(horizontalamplitude, horizontalwavelength, horizontalshift); + + KisRandomSubAccessorSP srcRSA = device->createRandomSubAccessor(); + do { + double xv = horizontalcurve->valueAt(dstIt->y(), dstIt->x()); + double yv = verticalcurve->valueAt(dstIt->x(), dstIt->y()); + srcRSA->moveTo(QPointF(xv, yv)); + srcRSA->sampledOldRawData(dstIt->rawData()); + if (progressUpdater) progressUpdater->setProgress((++count) / cost); + }while (dstIt->nextPixel()); + delete horizontalcurve; + delete verticalcurve; +} + +QRect KisFilterWave::neededRect(const QRect& rect, const KisFilterConfiguration* config) const +{ + QVariant value; + int horizontalamplitude = (config && config->getProperty("horizontalamplitude", value)) ? value.toInt() : 4; + int verticalamplitude = (config && config->getProperty("verticalamplitude", value)) ? value.toInt() : 4; + return rect.adjusted(-horizontalamplitude, -verticalamplitude, horizontalamplitude, verticalamplitude); +} diff --git a/pool/shard001/C++/0023185_pfs_time.cc b/pool/shard001/C++/0023185_pfs_time.cc new file mode 100644 index 0000000000000000000000000000000000000000..313d7e8de6e6952b60fd9ff09e3bec8f1e709606 --- /dev/null +++ b/pool/shard001/C++/0023185_pfs_time.cc @@ -0,0 +1,74 @@ +/* +Copyright (C) 2016- The University of Notre Dame +This software is distributed under the GNU General Public License. +See the file COPYING for details. +*/ + +#include "pfs_time.h" + +#include +#include + +pfs_time_mode_t pfs_time_mode = PFS_TIME_MODE_NORMAL; + +/* +For time stop and time warp modes, this is the emulated +time, which begins at midnight, Monday, January 1st, 2001 UTC +In time-warp mode, this is incremented by .01s at every request. +*/ + +static struct timespec emulated_time = { 978307200,0 }; + +time_t pfs_emulate_time( time_t *t ) +{ + struct timespec ts; + pfs_emulate_clock_gettime(CLOCK_REALTIME,&ts); + + if(t) *t = ts.tv_sec; + + return ts.tv_sec; +} + +int pfs_emulate_gettimeofday( struct timeval *tv, struct timezone *tz ) +{ + struct timespec ts; + pfs_emulate_clock_gettime(CLOCK_REALTIME,&ts); + + if(tv) { + tv->tv_sec = ts.tv_sec; + tv->tv_usec = ts.tv_nsec/1000; + } + + if(tz) { + memset(tz,0,sizeof(*tz)); + } + + return 0; +} + +int pfs_emulate_clock_gettime( clockid_t clockid, struct timespec *ts ) +{ + switch(pfs_time_mode) { + case PFS_TIME_MODE_NORMAL: + return clock_gettime(clockid,ts); + break; + case PFS_TIME_MODE_STOP: + *ts = emulated_time; + return 0; + break; + case PFS_TIME_MODE_WARP: + *ts = emulated_time; + emulated_time.tv_nsec += 10000000; + if(emulated_time.tv_nsec >= 1000000000) { + emulated_time.tv_nsec -= 1000000000; + emulated_time.tv_sec++; + } + return 0; + break; + } + + errno = ENOSYS; + return -1; +} + + diff --git a/pool/shard001/C++/0023189_robbyRileyScene.cpp b/pool/shard001/C++/0023189_robbyRileyScene.cpp new file mode 100644 index 0000000000000000000000000000000000000000..091e15f1949a1d0f486f4fd637d53741c093afb2 --- /dev/null +++ b/pool/shard001/C++/0023189_robbyRileyScene.cpp @@ -0,0 +1,40 @@ + +#include "robbyRileyScene.h" + +#define R_RIL_CNT 20 + +void robbyRileyScene::setup(){ + param.set("dent", 15, -10, 30); + parameters.add(param); + loadCode("robbyRileyScene/code.txt"); +} + +void robbyRileyScene::update(){ + +} + +void robbyRileyScene::draw(){ + ofFill(); + + float space = dimensions.height / R_RIL_CNT; + float colPos = 0; + + int i = 0; + while (colPos < dimensions.width){ + float colWidth = (.3+powf(atan((i - param)*.25),2)) * space*.5; + for(int j = 0; j < R_RIL_CNT; j++){ + if((i+j)%2) + ofSetColor(255, 255, 255); + else{ + float dist = powf(sinf(PI*(i+j)/40.0), 6); +// dist += ofNoise(ofGetElapsedTimef()); +// dist *= .5; + ofSetColor(255*dist, 255*dist, 255*dist); + } + ofDrawRectangle(colPos, j * space, colWidth, space); + } + colPos += colWidth; + i++; + } +} + diff --git a/pool/shard001/C++/0023190_WebSpeechSynthesisVoice.cpp b/pool/shard001/C++/0023190_WebSpeechSynthesisVoice.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1fcbd29d87460f1d301ec57ada56a3db954eec0e --- /dev/null +++ b/pool/shard001/C++/0023190_WebSpeechSynthesisVoice.cpp @@ -0,0 +1,81 @@ +/* + * 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. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "public/platform/WebSpeechSynthesisVoice.h" + +#include "modules/speech/SpeechRecognitionAlternative.h" +#include "modules/speech/SpeechSynthesisVoice.h" +#include "wtf/PassRefPtr.h" +#include "wtf/Vector.h" + +namespace WebKit { + +WebSpeechSynthesisVoice::WebSpeechSynthesisVoice() + : m_private(WebCore::PlatformSpeechSynthesisVoice::create()) +{ +} + +void WebSpeechSynthesisVoice::assign(const WebSpeechSynthesisVoice& other) +{ + m_private = other.m_private; +} + +void WebSpeechSynthesisVoice::reset() +{ + m_private.reset(); +} + +void WebSpeechSynthesisVoice::setVoiceURI(const WebString& voiceURI) +{ + m_private->setVoiceURI(voiceURI); +} + +void WebSpeechSynthesisVoice::setName(const WebString& name) +{ + m_private->setName(name); +} + +void WebSpeechSynthesisVoice::setLanguage(const WebString& language) +{ + m_private->setLang(language); +} + +void WebSpeechSynthesisVoice::setIsLocalService(bool isLocalService) +{ + m_private->setLocalService(isLocalService); +} + +void WebSpeechSynthesisVoice::setIsDefault(bool isDefault) +{ + m_private->setIsDefault(isDefault); +} + +WebSpeechSynthesisVoice::operator PassRefPtr() const +{ + return m_private.get(); +} + +} // namespace WebKit diff --git a/pool/shard001/C++/0023191_flatpermissions.cpp b/pool/shard001/C++/0023191_flatpermissions.cpp new file mode 100644 index 0000000000000000000000000000000000000000..00a54fe6b2c77f47c54db6240ebd43b471371978 --- /dev/null +++ b/pool/shard001/C++/0023191_flatpermissions.cpp @@ -0,0 +1,121 @@ +/* + +g++ -c flatpermissions.cpp +g++ -shared flatpermissions.o -o flatpermissions.so + +*/ +/* + Copyright (c) 2013, The Mineserver Project + 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 The Mineserver Project 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 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 + +#define MINESERVER_C_API +#include "plugin_api.h" + +#define PLUGIN_VERSION 1.1 +mineserver_pointer_struct* mineserver; +std::string pluginName = "flatpermissions"; + +std::string dtos(double n) +{ + std::stringstream result; + result << n; + return result.str(); +} + +void loginPost(const char* userIn){ + std::ifstream file; + file.open("permissions.txt", std::ios::in); + std::string line; + if(file.is_open()) + { + while(file.good()) + { + std::string msg; + std::getline(file, msg); + if(msg.size()>1) + { + std::string name, rank; + std::istringstream line(msg); + std::getline(line,name,':'); + std::getline(line,rank); + if(name.compare(std::string(userIn))==0) + { + std::transform(rank.begin(), rank.end(), rank.begin(), ::tolower); + if(rank.compare("admin")==0 || rank.compare("admins")==0) + { + mineserver->permissions.setAdmin(userIn); + } + else if(rank.compare("op")==0 || rank.compare("ops")==0) + { + mineserver->permissions.setOp(userIn); + } + else if(rank.compare("member")==0 || rank.compare("members")==0) + { + mineserver->permissions.setMember(userIn); + } + else + { + mineserver->permissions.setGuest(userIn); + } + break; + } + } + } + file.close(); + } +} + + +PLUGIN_API_EXPORT void CALLCONVENSION flatpermissions_shutdown(void) +{ + if (mineserver->plugin.getPluginVersion(pluginName.c_str()) <= 0) + { + mineserver->logger.log(6, "plugin.flatpermissions", "flatpermission is not loaded!"); + return; + } +} + +PLUGIN_API_EXPORT void CALLCONVENSION flatpermissions_init(mineserver_pointer_struct* mineserver_temp) +{ + mineserver = mineserver_temp; + if(mineserver->plugin.getPluginVersion(pluginName.c_str())>0){ + std::string msg = "flatpermission is already loaded, v. "+dtos(mineserver->plugin.getPluginVersion(pluginName.c_str())); + mineserver->logger.log(6, "plugin.flatpermissions", msg.c_str()); + return; + } + std::string msg = "Loaded "+pluginName+"!"; + mineserver->logger.log(6, "plugin.flatpermissions", msg.c_str()); + + mineserver->plugin.setPluginVersion(pluginName.c_str(), PLUGIN_VERSION); + mineserver->plugin.addCallback("PlayerLoginPost", reinterpret_cast(loginPost)); +} diff --git a/pool/shard001/C++/0023192_qrcodedialog.cpp b/pool/shard001/C++/0023192_qrcodedialog.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1d084b73ab4b07538e7ca29784761a9c8adb5b68 --- /dev/null +++ b/pool/shard001/C++/0023192_qrcodedialog.cpp @@ -0,0 +1,173 @@ +#include "qrcodedialog.h" +#include "ui_qrcodedialog.h" + +#include "bitcoinunits.h" +#include "guiconstants.h" +#include "guiutil.h" +#include "optionsmodel.h" + +#include +#if QT_VERSION < 0x050000 +#include +#endif + +#include + +QRCodeDialog::QRCodeDialog(const QString &addr, const QString &label, bool enableReq, QWidget *parent) : + QDialog(parent), + ui(new Ui::QRCodeDialog), + model(0), + address(addr) +{ + ui->setupUi(this); + + setWindowTitle(QString("%1").arg(address)); + + ui->chkReqPayment->setVisible(enableReq); + ui->lblAmount->setVisible(enableReq); + ui->lnReqAmount->setVisible(enableReq); + + ui->lnLabel->setText(label); + + ui->btnSaveAs->setEnabled(false); + + genCode(); +} + +QRCodeDialog::~QRCodeDialog() +{ + delete ui; +} + +void QRCodeDialog::setModel(OptionsModel *model) +{ + this->model = model; + + if (model) + connect(model, SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); + + // update the display unit, to not use the default ("POC") + updateDisplayUnit(); +} + +void QRCodeDialog::genCode() +{ + QString uri = getURI(); + + if (uri != "") + { + ui->lblQRCode->setText(""); + + QRcode *code = QRcode_encodeString(uri.toUtf8().constData(), 0, QR_ECLEVEL_L, QR_MODE_8, 1); + if (!code) + { + ui->lblQRCode->setText(tr("Error encoding URI into QR Code.")); + return; + } + myImage = QImage(code->width + 8, code->width + 8, QImage::Format_RGB32); + myImage.fill(0xffffff); + unsigned char *p = code->data; + for (int y = 0; y < code->width; y++) + { + for (int x = 0; x < code->width; x++) + { + myImage.setPixel(x + 4, y + 4, ((*p & 1) ? 0x0 : 0xffffff)); + p++; + } + } + QRcode_free(code); + + ui->lblQRCode->setPixmap(QPixmap::fromImage(myImage).scaled(300, 300)); + + ui->outUri->setPlainText(uri); + } +} + +QString QRCodeDialog::getURI() +{ + QString ret = QString("bitcoin:%1").arg(address); + int paramCount = 0; + + ui->outUri->clear(); + + if (ui->chkReqPayment->isChecked()) + { + if (ui->lnReqAmount->validate()) + { + // even if we allow a non POC unit input in lnReqAmount, we generate the URI with POC as unit (as defined in BIP21) + ret += QString("?amount=%1").arg(BitcoinUnits::format(BitcoinUnits::POC, ui->lnReqAmount->value())); + paramCount++; + } + else + { + ui->btnSaveAs->setEnabled(false); + ui->lblQRCode->setText(tr("The entered amount is invalid, please check.")); + return QString(""); + } + } + + if (!ui->lnLabel->text().isEmpty()) + { + QString lbl(QUrl::toPercentEncoding(ui->lnLabel->text())); + ret += QString("%1label=%2").arg(paramCount == 0 ? "?" : "&").arg(lbl); + paramCount++; + } + + if (!ui->lnMessage->text().isEmpty()) + { + QString msg(QUrl::toPercentEncoding(ui->lnMessage->text())); + ret += QString("%1message=%2").arg(paramCount == 0 ? "?" : "&").arg(msg); + paramCount++; + } + + // limit URI length to prevent a DoS against the QR-Code dialog + if (ret.length() > MAX_URI_LENGTH) + { + ui->btnSaveAs->setEnabled(false); + ui->lblQRCode->setText(tr("Resulting URI too long, try to reduce the text for label / message.")); + return QString(""); + } + + ui->btnSaveAs->setEnabled(true); + return ret; +} + +void QRCodeDialog::on_lnReqAmount_textChanged() +{ + genCode(); +} + +void QRCodeDialog::on_lnLabel_textChanged() +{ + genCode(); +} + +void QRCodeDialog::on_lnMessage_textChanged() +{ + genCode(); +} + +void QRCodeDialog::on_btnSaveAs_clicked() +{ + QString fn = GUIUtil::getSaveFileName(this, tr("Save QR Code"), QString(), tr("PNG Images (*.png)")); + if (!fn.isEmpty()) + myImage.scaled(EXPORT_IMAGE_SIZE, EXPORT_IMAGE_SIZE).save(fn); +} + +void QRCodeDialog::on_chkReqPayment_toggled(bool fChecked) +{ + if (!fChecked) + // if chkReqPayment is not active, don't display lnReqAmount as invalid + ui->lnReqAmount->setValid(true); + + genCode(); +} + +void QRCodeDialog::updateDisplayUnit() +{ + if (model) + { + // Update lnReqAmount with the current unit + ui->lnReqAmount->setDisplayUnit(model->getDisplayUnit()); + } +} diff --git a/pool/shard001/C++/0023202_Texture.cpp b/pool/shard001/C++/0023202_Texture.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ed0e2cc5c74553ea2b82acc6aaaea1b356c4d33c --- /dev/null +++ b/pool/shard001/C++/0023202_Texture.cpp @@ -0,0 +1,125 @@ +#include +#include "Texture.h" +#include "Scene.h" + +Texture::Texture() { + active = false; + textureLoaded = false; + filepath = String(); + name = Scene::name(String("Texture")); + type = TEXTURE_TYPE; + image=NULL; +} + +Texture * Texture::addTexture(String filename) { + Texture * tex = NULL; + if (!(tex=T(Scene::getObjectByFile(filename)))) { + tex = new Texture(); + tex->filepath = filename; + Scene::addTexture(tex); + } + return tex; +} + +void Texture::checkers() { + if (!textureLoaded) { + printf("making checkers\n"); + w = h = 100; + texture = new GLubyte[4*w*h]; + printf("h: %d, w: %d\n", h, w); + for (int i = 0 ; i < h*w ; i++) { + texture[i*4 + 0] = (GLubyte) i*4 % 255; + texture[i*4 + 1] = (GLubyte) i*3 % 255; + texture[i*4 + 2] = (GLubyte) i % 255; + texture[i*4 + 3] = 255; + } + textureLoaded = true; + } +} + + +void Texture::readTexture() { + if (!textureLoaded) { + if (!filepath.length()) { + printf("no filepath for texture\n"); + return; + } + printf("Reading texture...%s\n",filepath.c_str()); + FILE *fp ; int i; + if((fp = fopen(filepath.c_str(),"rb"))) { + //fscanf(fp,"%*s %*d %*d %*d%*c") ; + char s[48]; + fgets(s,48, fp); // read P6 + fgets(s,48, fp); // read width and height + sscanf(s,"%d %d", &w, &h); + texture = new GLubyte[4*w*h]; + printf("h: %d, w: %d\n", h, w); + fgets(s,48, fp); + fgets(s,48, fp); + for (i = 0 ; i < h*w ; i++) { + fscanf(fp,"%c",&(texture[i*4 + 2])); + fscanf(fp,"%c",&(texture[i*4 + 1])); + fscanf(fp,"%c",&(texture[i*4 + 0])); + texture[i*4 + 3] = (GLubyte) 255; + } + fclose(fp) ; + } else { + checkers(); + } + } +} + + +void Texture::initializeTexture() { + if (!textureLoaded) { + readTexture(); + + glPixelStorei(GL_UNPACK_ALIGNMENT,1); + + /* Now, set up all the stuff for texturing, per page 399 */ + glGenTextures(1, &texName) ; + glBindTexture(GL_TEXTURE_2D, texName) ; + + bool mipmaps = false; + + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT) ; + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT) ; + //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE) ; + //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE) ; + if (mipmaps) { + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) ; + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR) ; + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) ; + glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 4); + + gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, w, h, GL_RGBA, GL_UNSIGNED_BYTE, texture); + } else { + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) ; + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) ; + glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, texture) ; + } + /* don't this this anymore */ + delete texture; + textureLoaded = true; + printf("texture initialized...\n"); + } +} + +void Texture::EnableBind() { + glEnable(GL_TEXTURE_2D) ; + // GL_REPLACE -> no lighting + //glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE) ; + glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE) ; + glBindTexture(GL_TEXTURE_2D, texName) ; + //glColor3f(0.0,0.0,0.0) ; + //err = glGetError() ; assert(err == GL_NO_ERROR) ; +} + +void Texture::Disable() { + //err = glGetError() ; assert(err == GL_NO_ERROR) ; + glDisable(GL_TEXTURE_2D) ; +} + +Texture::~Texture() { if (textureLoaded) glDeleteTextures(1, &texName); } diff --git a/pool/shard001/C++/0023204_push.cpp b/pool/shard001/C++/0023204_push.cpp new file mode 100644 index 0000000000000000000000000000000000000000..91e686d7e16db61b72b14206dc46dc5f92351d87 --- /dev/null +++ b/pool/shard001/C++/0023204_push.cpp @@ -0,0 +1,29 @@ +#include "push.hpp" + +using namespace VPZ::APKStudio::Helpers; + +namespace VPZ { +namespace APKStudio { +namespace Async { + +Push::Push(const QString &device, const QStringList &files, const QString &destination, QObject *parent) : + Task(parent), destination(destination), device(device), files(files) +{ +} + +void Push::start() +{ + int failed = 0; + int successful = 0; + foreach(const QString &file, files) { + if (ADB::instance()->push(device, file, destination)) + successful++; + else + failed++; + } + emit finished(QVariant::fromValue(QPair(successful, failed))); +} + +} // namespace Async +} // namespace APKStudio +} // namespace VPZ diff --git a/pool/shard001/C++/0023209_moc_optionsmodel.cpp b/pool/shard001/C++/0023209_moc_optionsmodel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..936b7d8320d4dcaa575a17e97bd44bab3e69c306 --- /dev/null +++ b/pool/shard001/C++/0023209_moc_optionsmodel.cpp @@ -0,0 +1,99 @@ +/**************************************************************************** +** Meta object code from reading C++ file 'optionsmodel.h' +** +** Created by: The Qt Meta Object Compiler version 63 (Qt 4.8.5) +** +** WARNING! All changes made in this file will be lost! +*****************************************************************************/ + +#include "../src/qt/optionsmodel.h" +#if !defined(Q_MOC_OUTPUT_REVISION) +#error "The header file 'optionsmodel.h' doesn't include ." +#elif Q_MOC_OUTPUT_REVISION != 63 +#error "This file was generated using the moc from 4.8.5. It" +#error "cannot be used with the include files from this version of Qt." +#error "(The moc has changed too much.)" +#endif + +QT_BEGIN_MOC_NAMESPACE +static const uint qt_meta_data_OptionsModel[] = { + + // content: + 6, // revision + 0, // classname + 0, 0, // classinfo + 1, 14, // methods + 0, 0, // properties + 0, 0, // enums/sets + 0, 0, // constructors + 0, // flags + 1, // signalCount + + // signals: signature, parameters, type, tag, flags + 19, 14, 13, 13, 0x05, + + 0 // eod +}; + +static const char qt_meta_stringdata_OptionsModel[] = { + "OptionsModel\0\0unit\0displayUnitChanged(int)\0" +}; + +void OptionsModel::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) +{ + if (_c == QMetaObject::InvokeMetaMethod) { + Q_ASSERT(staticMetaObject.cast(_o)); + OptionsModel *_t = static_cast(_o); + switch (_id) { + case 0: _t->displayUnitChanged((*reinterpret_cast< int(*)>(_a[1]))); break; + default: ; + } + } +} + +const QMetaObjectExtraData OptionsModel::staticMetaObjectExtraData = { + 0, qt_static_metacall +}; + +const QMetaObject OptionsModel::staticMetaObject = { + { &QAbstractListModel::staticMetaObject, qt_meta_stringdata_OptionsModel, + qt_meta_data_OptionsModel, &staticMetaObjectExtraData } +}; + +#ifdef Q_NO_DATA_RELOCATION +const QMetaObject &OptionsModel::getStaticMetaObject() { return staticMetaObject; } +#endif //Q_NO_DATA_RELOCATION + +const QMetaObject *OptionsModel::metaObject() const +{ + return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject; +} + +void *OptionsModel::qt_metacast(const char *_clname) +{ + if (!_clname) return 0; + if (!strcmp(_clname, qt_meta_stringdata_OptionsModel)) + return static_cast(const_cast< OptionsModel*>(this)); + return QAbstractListModel::qt_metacast(_clname); +} + +int OptionsModel::qt_metacall(QMetaObject::Call _c, int _id, void **_a) +{ + _id = QAbstractListModel::qt_metacall(_c, _id, _a); + if (_id < 0) + return _id; + if (_c == QMetaObject::InvokeMetaMethod) { + if (_id < 1) + qt_static_metacall(this, _c, _id, _a); + _id -= 1; + } + return _id; +} + +// SIGNAL 0 +void OptionsModel::displayUnitChanged(int _t1) +{ + void *_a[] = { 0, const_cast(reinterpret_cast(&_t1)) }; + QMetaObject::activate(this, &staticMetaObject, 0, _a); +} +QT_END_MOC_NAMESPACE diff --git a/pool/shard001/C++/0023217_ArjDecoder2.cpp b/pool/shard001/C++/0023217_ArjDecoder2.cpp new file mode 100644 index 0000000000000000000000000000000000000000..365993bc50746a68044946d39403b59ac5186aba --- /dev/null +++ b/pool/shard001/C++/0023217_ArjDecoder2.cpp @@ -0,0 +1,90 @@ +// ArjDecoder2.cpp + +#include "StdAfx.h" + +#include "ArjDecoder2.h" + +namespace NCompress{ +namespace NArj { +namespace NDecoder2 { + +static const UInt32 kHistorySize = 26624; +static const UInt32 kMatchMinLen = 3; + +HRESULT CCoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream *outStream, + const UInt64 * /* inSize */, const UInt64 *outSize, ICompressProgressInfo * /* progress */) +{ + if (outSize == NULL) + return E_INVALIDARG; + + if (!m_OutWindowStream.Create(kHistorySize)) + return E_OUTOFMEMORY; + if (!m_InBitStream.Create(1 << 20)) + return E_OUTOFMEMORY; + + UInt64 pos = 0; + m_OutWindowStream.SetStream(outStream); + m_OutWindowStream.Init(false); + m_InBitStream.SetStream(inStream); + m_InBitStream.Init(); + CCoderReleaser coderReleaser(this); + + while(pos < *outSize) + { + const UInt32 kStartWidth = 0; + const UInt32 kStopWidth = 7; + UInt32 power = 1 << kStartWidth; + UInt32 width; + UInt32 len = 0; + for (width = kStartWidth; width < kStopWidth; width++) + { + if (m_InBitStream.ReadBits(1) == 0) + break; + len += power; + power <<= 1; + } + if (width != 0) + len += m_InBitStream.ReadBits(width); + if (len == 0) + { + m_OutWindowStream.PutByte((Byte)m_InBitStream.ReadBits(8)); + pos++; + continue; + } + else + { + len = len - 1 + kMatchMinLen; + const UInt32 kStartWidth = 9; + const UInt32 kStopWidth = 13; + UInt32 power = 1 << kStartWidth; + UInt32 width; + UInt32 distance = 0; + for (width = kStartWidth; width < kStopWidth; width++) + { + if (m_InBitStream.ReadBits(1) == 0) + break; + distance += power; + power <<= 1; + } + if (width != 0) + distance += m_InBitStream.ReadBits(width); + if (distance >= pos) + return S_FALSE; + m_OutWindowStream.CopyBlock(distance, len); + pos += len; + } + } + coderReleaser.NeedFlush = false; + return m_OutWindowStream.Flush(); +} + +STDMETHODIMP CCoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, + const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress) +{ + try { return CodeReal(inStream, outStream, inSize, outSize, progress);} + catch(const CInBufferException &e) { return e.ErrorCode; } + catch(const CLzOutWindowException &e) { return e.ErrorCode; } + catch(...) { return S_FALSE; } +} + +}}} diff --git a/pool/shard001/C++/0023218_LiveIntervalUnion.cpp b/pool/shard001/C++/0023218_LiveIntervalUnion.cpp new file mode 100644 index 0000000000000000000000000000000000000000..025d99ce78812c8f42a003a1cda8b9d206b56b97 --- /dev/null +++ b/pool/shard001/C++/0023218_LiveIntervalUnion.cpp @@ -0,0 +1,205 @@ +//===-- LiveIntervalUnion.cpp - Live interval union data structure --------===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +// +// LiveIntervalUnion represents a coalesced set of live intervals. This may be +// used during coalescing to represent a congruence class, or during register +// allocation to model liveness of a physical register. +// +//===----------------------------------------------------------------------===// + +#include "llvm/CodeGen/LiveIntervalUnion.h" +#include "llvm/ADT/SparseBitVector.h" +#include "llvm/Support/Debug.h" +#include "llvm/Support/raw_ostream.h" +#include "llvm/Target/TargetRegisterInfo.h" +#include + +using namespace llvm; + +#define DEBUG_TYPE "regalloc" + + +// Merge a LiveInterval's segments. Guarantee no overlaps. +void LiveIntervalUnion::unify(LiveInterval &VirtReg, const LiveRange &Range) { + if (Range.empty()) + return; + ++Tag; + + // Insert each of the virtual register's live segments into the map. + LiveRange::const_iterator RegPos = Range.begin(); + LiveRange::const_iterator RegEnd = Range.end(); + SegmentIter SegPos = Segments.find(RegPos->start); + + while (SegPos.valid()) { + SegPos.insert(RegPos->start, RegPos->end, &VirtReg); + if (++RegPos == RegEnd) + return; + SegPos.advanceTo(RegPos->start); + } + + // We have reached the end of Segments, so it is no longer necessary to search + // for the insertion position. + // It is faster to insert the end first. + --RegEnd; + SegPos.insert(RegEnd->start, RegEnd->end, &VirtReg); + for (; RegPos != RegEnd; ++RegPos, ++SegPos) + SegPos.insert(RegPos->start, RegPos->end, &VirtReg); +} + +// Remove a live virtual register's segments from this union. +void LiveIntervalUnion::extract(LiveInterval &VirtReg, const LiveRange &Range) { + if (Range.empty()) + return; + ++Tag; + + // Remove each of the virtual register's live segments from the map. + LiveRange::const_iterator RegPos = Range.begin(); + LiveRange::const_iterator RegEnd = Range.end(); + SegmentIter SegPos = Segments.find(RegPos->start); + + for (;;) { + assert(SegPos.value() == &VirtReg && "Inconsistent LiveInterval"); + SegPos.erase(); + if (!SegPos.valid()) + return; + + // Skip all segments that may have been coalesced. + RegPos = Range.advanceTo(RegPos, SegPos.start()); + if (RegPos == RegEnd) + return; + + SegPos.advanceTo(RegPos->start); + } +} + +void +LiveIntervalUnion::print(raw_ostream &OS, const TargetRegisterInfo *TRI) const { + if (empty()) { + OS << " empty\n"; + return; + } + for (LiveSegments::const_iterator SI = Segments.begin(); SI.valid(); ++SI) { + OS << " [" << SI.start() << ' ' << SI.stop() << "):" + << PrintReg(SI.value()->reg, TRI); + } + OS << '\n'; +} + +#ifndef NDEBUG +// Verify the live intervals in this union and add them to the visited set. +void LiveIntervalUnion::verify(LiveVirtRegBitSet& VisitedVRegs) { + for (SegmentIter SI = Segments.begin(); SI.valid(); ++SI) + VisitedVRegs.set(SI.value()->reg); +} +#endif //!NDEBUG + +// Scan the vector of interfering virtual registers in this union. Assume it's +// quite small. +bool LiveIntervalUnion::Query::isSeenInterference(LiveInterval *VirtReg) const { + SmallVectorImpl::const_iterator I = + std::find(InterferingVRegs.begin(), InterferingVRegs.end(), VirtReg); + return I != InterferingVRegs.end(); +} + +// Collect virtual registers in this union that interfere with this +// query's live virtual register. +// +// The query state is one of: +// +// 1. CheckedFirstInterference == false: Iterators are uninitialized. +// 2. SeenAllInterferences == true: InterferingVRegs complete, iterators unused. +// 3. Iterators left at the last seen intersection. +// +unsigned LiveIntervalUnion::Query:: +collectInterferingVRegs(unsigned MaxInterferingRegs) { + // Fast path return if we already have the desired information. + if (SeenAllInterferences || InterferingVRegs.size() >= MaxInterferingRegs) + return InterferingVRegs.size(); + + // Set up iterators on the first call. + if (!CheckedFirstInterference) { + CheckedFirstInterference = true; + + // Quickly skip interference check for empty sets. + if (VirtReg->empty() || LiveUnion->empty()) { + SeenAllInterferences = true; + return 0; + } + + // In most cases, the union will start before VirtReg. + VirtRegI = VirtReg->begin(); + LiveUnionI.setMap(LiveUnion->getMap()); + LiveUnionI.find(VirtRegI->start); + } + + LiveInterval::iterator VirtRegEnd = VirtReg->end(); + LiveInterval *RecentReg = nullptr; + while (LiveUnionI.valid()) { + assert(VirtRegI != VirtRegEnd && "Reached end of VirtReg"); + + // Check for overlapping interference. + while (VirtRegI->start < LiveUnionI.stop() && + VirtRegI->end > LiveUnionI.start()) { + // This is an overlap, record the interfering register. + LiveInterval *VReg = LiveUnionI.value(); + if (VReg != RecentReg && !isSeenInterference(VReg)) { + RecentReg = VReg; + InterferingVRegs.push_back(VReg); + if (InterferingVRegs.size() >= MaxInterferingRegs) + return InterferingVRegs.size(); + } + // This LiveUnion segment is no longer interesting. + if (!(++LiveUnionI).valid()) { + SeenAllInterferences = true; + return InterferingVRegs.size(); + } + } + + // The iterators are now not overlapping, LiveUnionI has been advanced + // beyond VirtRegI. + assert(VirtRegI->end <= LiveUnionI.start() && "Expected non-overlap"); + + // Advance the iterator that ends first. + VirtRegI = VirtReg->advanceTo(VirtRegI, LiveUnionI.start()); + if (VirtRegI == VirtRegEnd) + break; + + // Detect overlap, handle above. + if (VirtRegI->start < LiveUnionI.stop()) + continue; + + // Still not overlapping. Catch up LiveUnionI. + LiveUnionI.advanceTo(VirtRegI->start); + } + SeenAllInterferences = true; + return InterferingVRegs.size(); +} + +void LiveIntervalUnion::Array::init(LiveIntervalUnion::Allocator &Alloc, + unsigned NSize) { + // Reuse existing allocation. + if (NSize == Size) + return; + clear(); + Size = NSize; + LIUs = static_cast( + malloc(sizeof(LiveIntervalUnion)*NSize)); + for (unsigned i = 0; i != Size; ++i) + new(LIUs + i) LiveIntervalUnion(Alloc); +} + +void LiveIntervalUnion::Array::clear() { + if (!LIUs) + return; + for (unsigned i = 0; i != Size; ++i) + LIUs[i].~LiveIntervalUnion(); + free(LIUs); + Size = 0; + LIUs = nullptr; +} diff --git a/pool/shard001/C++/0023224_debug.cpp b/pool/shard001/C++/0023224_debug.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e8198a7e65e3095669b0c5389b90c7b3ec6dbf0f --- /dev/null +++ b/pool/shard001/C++/0023224_debug.cpp @@ -0,0 +1,109 @@ +// +// debug.cpp +// +// Circle - A C++ bare metal environment for Raspberry Pi +// Copyright (C) 2016 R. Stange +// +// 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 "../../pi-OS/include/circle/debug.h" + +#include "../../pi-OS/include/circle/gpiopin.h" +#include "../../pi-OS/include/circle/logger.h" +#include "../../Pi-OS/include/circle/gpiopin.h" +#include "../../Pi-OS/include/circle/string.h" +#include "../../Pi-OS/include/circle/sysconfig.h" + +#ifndef NDEBUG + +static const char FromDebug[] = "debug"; + +#ifdef DEBUG_CLICK + +static CGPIOPin AudioLeft (GPIOPinAudioLeft, GPIOModeOutput); +static CGPIOPin AudioRight (GPIOPinAudioRight, GPIOModeOutput); + +#endif + +void debug_hexdump (const void *pStart, unsigned nBytes, const char *pSource) +{ + u8 *pOffset = (u8 *) pStart; + + if (pSource == 0) + { + pSource = FromDebug; + } + + CLogger::Get ()->Write (pSource, LogDebug, "Dumping 0x%X bytes starting at 0x%X", nBytes, (unsigned) pOffset); + + while (nBytes > 0) + { + CLogger::Get ()->Write (pSource, LogDebug, + "%04X: %02X %02X %02X %02X %02X %02X %02X %02X-%02X %02X %02X %02X %02X %02X %02X %02X", + (unsigned) pOffset & 0xFFFF, + (unsigned) pOffset[0], (unsigned) pOffset[1], (unsigned) pOffset[2], (unsigned) pOffset[3], + (unsigned) pOffset[4], (unsigned) pOffset[5], (unsigned) pOffset[6], (unsigned) pOffset[7], + (unsigned) pOffset[8], (unsigned) pOffset[9], (unsigned) pOffset[10], (unsigned) pOffset[11], + (unsigned) pOffset[12], (unsigned) pOffset[13], (unsigned) pOffset[14], (unsigned) pOffset[15]); + + pOffset += 16; + + if (nBytes >= 16) + { + nBytes -= 16; + } + else + { + nBytes = 0; + } + } +} + +void debug_stacktrace (const u32 *pStackPtr, const char *pSource) +{ + if (pSource == 0) + { + pSource = FromDebug; + } + + for (unsigned i = 0; i < 64; i++, pStackPtr++) + { + extern unsigned char _etext; + + if ( *pStackPtr >= MEM_KERNEL_START + && *pStackPtr < (u32) &_etext) + { + CLogger::Get ()->Write (pSource, LogDebug, "stack[%u] is 0x%X", i, (unsigned) *pStackPtr); + } + } +} + +#ifdef DEBUG_CLICK + +void debug_click (unsigned nMask) +{ + if (nMask & DEBUG_CLICK_LEFT) + { + AudioLeft.Invert (); + } + + if (nMask & DEBUG_CLICK_RIGHT) + { + AudioRight.Invert (); + } +} + +#endif + +#endif diff --git a/pool/shard001/C++/0023230_NntpConnection.cpp b/pool/shard001/C++/0023230_NntpConnection.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5a6d43363878e075ca1af88a36ae091bb7adc126 --- /dev/null +++ b/pool/shard001/C++/0023230_NntpConnection.cpp @@ -0,0 +1,240 @@ +/* + * This file is part of nzbget. See . + * + * Copyright (C) 2004 Sven Henkel + * Copyright (C) 2007-2016 Andrey Prygunkov + * + * 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 . + */ + + +#include "nzbget.h" +#include "Log.h" +#include "NntpConnection.h" +#include "Connection.h" +#include "NewsServer.h" + +static const int CONNECTION_LINEBUFFER_SIZE = 1024*10; + +NntpConnection::NntpConnection(NewsServer* newsServer) : + Connection(newsServer->GetHost(), newsServer->GetPort(), newsServer->GetTls()), m_newsServer(newsServer) +{ + m_lineBuf.Reserve(CONNECTION_LINEBUFFER_SIZE); + SetCipher(newsServer->GetCipher()); + SetIPVersion(newsServer->GetIpVersion() == 4 ? Connection::ipV4 : + newsServer->GetIpVersion() == 6 ? Connection::ipV6 : Connection::ipAuto); +} + +const char* NntpConnection::Request(const char* req) +{ + if (!req) + { + return nullptr; + } + + m_authError = false; + + WriteLine(req); + + char* answer = ReadLine(m_lineBuf, m_lineBuf.Size(), nullptr); + + if (!answer) + { + return nullptr; + } + + if (!strncmp(answer, "480", 3)) + { + debug("%s requested authorization", GetHost()); + + if (!Authenticate()) + { + return nullptr; + } + + //try again + WriteLine(req); + answer = ReadLine(m_lineBuf, m_lineBuf.Size(), nullptr); + } + + return answer; +} + +bool NntpConnection::Authenticate() +{ + if (strlen(m_newsServer->GetUser()) == 0 || strlen(m_newsServer->GetPassword()) == 0) + { + ReportError("Could not connect to %s: server requested authorization but username/password are not set in settings", + m_newsServer->GetHost(), false, 0); + m_authError = true; + return false; + } + + m_authError = !AuthInfoUser(0); + return !m_authError; +} + +bool NntpConnection::AuthInfoUser(int recur) +{ + if (recur > 10) + { + return false; + } + + WriteLine(BString<1024>("AUTHINFO USER %s\r\n", m_newsServer->GetUser())); + + char* answer = ReadLine(m_lineBuf, m_lineBuf.Size(), nullptr); + if (!answer) + { + ReportErrorAnswer("Authorization for %s (%s) failed: Connection closed by remote host", nullptr); + return false; + } + + if (!strncmp(answer, "281", 3)) + { + debug("Authorization for %s successful", GetHost()); + return true; + } + else if (!strncmp(answer, "381", 3)) + { + return AuthInfoPass(++recur); + } + else if (!strncmp(answer, "480", 3)) + { + return AuthInfoUser(++recur); + } + + if (char* p = strrchr(answer, '\r')) *p = '\0'; // remove last CRLF from error message + + if (GetStatus() != csCancelled) + { + ReportErrorAnswer("Authorization for %s (%s) failed: %s", answer); + } + return false; +} + +bool NntpConnection::AuthInfoPass(int recur) +{ + if (recur > 10) + { + return false; + } + + WriteLine(BString<1024>("AUTHINFO PASS %s\r\n", m_newsServer->GetPassword())); + + char* answer = ReadLine(m_lineBuf, m_lineBuf.Size(), nullptr); + if (!answer) + { + ReportErrorAnswer("Authorization failed for %s (%s): Connection closed by remote host", nullptr); + return false; + } + else if (!strncmp(answer, "2", 1)) + { + debug("Authorization for %s successful", GetHost()); + return true; + } + else if (!strncmp(answer, "381", 3)) + { + return AuthInfoPass(++recur); + } + + if (char* p = strrchr(answer, '\r')) *p = '\0'; // remove last CRLF from error message + + if (GetStatus() != csCancelled) + { + ReportErrorAnswer("Authorization for %s (%s) failed: %s", answer); + } + return false; +} + +const char* NntpConnection::JoinGroup(const char* grp) +{ + if (!m_activeGroup.Empty() && !strcmp(m_activeGroup, grp)) + { + // already in group + strcpy(m_lineBuf, "211 "); + return m_lineBuf; + } + + const char* answer = Request(BString<1024>("GROUP %s\r\n", grp)); + + if (answer && !strncmp(answer, "2", 1)) + { + debug("Changed group to %s on %s", grp, GetHost()); + m_activeGroup = grp; + } + else + { + debug("Error changing group on %s to %s: %s.", GetHost(), grp, answer); + } + + return answer; +} + +bool NntpConnection::Connect() +{ + debug("Opening connection to %s", GetHost()); + + if (m_status == csConnected) + { + return true; + } + + if (!Connection::Connect()) + { + return false; + } + + char* answer = ReadLine(m_lineBuf, m_lineBuf.Size(), nullptr); + + if (!answer) + { + ReportErrorAnswer("Connection to %s (%s) failed: Connection closed by remote host", nullptr); + Disconnect(); + return false; + } + + if (strncmp(answer, "2", 1)) + { + ReportErrorAnswer("Connection to %s (%s) failed: %s", answer); + Disconnect(); + return false; + } + + if ((strlen(m_newsServer->GetUser()) > 0 && strlen(m_newsServer->GetPassword()) > 0) && + !Authenticate()) + { + return false; + } + + debug("Connection to %s established", GetHost()); + + return true; +} + +bool NntpConnection::Disconnect() +{ + if (m_status == csConnected) + { + Request("quit\r\n"); + m_activeGroup = nullptr; + } + return Connection::Disconnect(); +} + +void NntpConnection::ReportErrorAnswer(const char* msgPrefix, const char* answer) +{ + BString<1024> errStr(msgPrefix, m_newsServer->GetName(), m_newsServer->GetHost(), answer); + ReportError(errStr, nullptr, false, 0); +} diff --git a/pool/shard001/C++/0023237_cpu_timer_test.cc b/pool/shard001/C++/0023237_cpu_timer_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..b6a912e9c895fb1bd3a43825449b2063848d3239 --- /dev/null +++ b/pool/shard001/C++/0023237_cpu_timer_test.cc @@ -0,0 +1,166 @@ +#define _GLIBCXX_USE_NANOSLEEP 1 +#define BOOST_TEST_MODULE ( cpu_timer_test 2 ) +#include "cetlib/quiet_unit_test.hpp" + +#include "cetlib/cpu_timer.h" + +#include +#include +#include +#include +#include + +#include + +struct CPUTimerTtestFixture { + cet::cpu_timer &timer() { + static cet::cpu_timer t_s; + return t_s; + } +}; + +//---------------------------------------------------------------------- +// Constants used for controlling the tests of the CPUTimer. +// + +// The smallest amount of CPU time we can reliably measure, from two +// consecutive calls to the timer. Time in seconds. +double const small_cputime = 1.5e-3; + +// The smallest amount of real (wallclock) time we can reliably measure, +// from two consecutive calls to the timer. Time in seconds. +double const small_realtime = 1.5e-3; + + +// Return the difference between the total time (user+system) in the two +// rusage structs. +inline double +time_diff(rusage const& a, rusage const& b) +{ + double const sec = (a.ru_utime.tv_sec - b.ru_utime.tv_sec) + + (a.ru_stime.tv_sec - b.ru_stime.tv_sec); + double const microsec = (a.ru_utime.tv_usec - b.ru_utime.tv_usec) + + (a.ru_stime.tv_usec - b.ru_stime.tv_usec); + return sec + 1e-6 * microsec; +} + +// Make a busy-loop for 'dur' seconds. +double busy_loop(double dur) +{ + double x = 3.14; + rusage start_time, ru; + getrusage(RUSAGE_SELF, &start_time) ; + do { + for (int i = 0; i < 1000; ++i) x = sin(x); + getrusage(RUSAGE_SELF, &ru); + } + while (time_diff(ru, start_time) < dur); + return x; +} + +//---------------------------------------------------------------------- + +BOOST_FIXTURE_TEST_SUITE(CPUTimer_t,CPUTimerTtestFixture) + +BOOST_AUTO_TEST_CASE(init) +{ + // A newly-constructed timer should have both realTime and cpuTime of + // zero. + BOOST_CHECK_EQUAL(timer().realTime(), 0.0); + BOOST_CHECK_EQUAL(timer().cpuTime(), 0.0); +} + +BOOST_AUTO_TEST_CASE(timer1) +{ + // Run the timer while we sleep, then stop. This should use clock + // time, but little CPU time. + timer().stop(); + timer().reset(); + timer().start(); + std::this_thread::sleep_for(std::chrono::milliseconds(50)); + timer().stop(); + + BOOST_CHECK_CLOSE(timer().realTime(), 0.050, 5.0); // difference in percentage + std::cout << "timer1 cpu: " << timer().cpuTime() << " real: " << timer().realTime() << std::endl; + BOOST_CHECK_SMALL(timer().cpuTime(), small_cputime); +} + +BOOST_AUTO_TEST_CASE(timer2) +{ + // Run the time while we sleep. Capture the time without stopping the + // timer. This should use clock time but little CPU time. + timer().stop(); + timer().reset(); + timer().start(); + std::this_thread::sleep_for(std::chrono::milliseconds(50)); + // We have to capture the times before we do comparisons, or else + // we'll have used too much CPU time. + double const cpu = timer().cpuTime(); + double const real = timer().realTime(); + + BOOST_CHECK_CLOSE(real, 0.050, 5.0); // difference in percentage + BOOST_CHECK_SMALL(cpu, small_cputime); +} + +BOOST_AUTO_TEST_CASE(nullStart) +{ + // Get the time immediately after starting. This should give close to + // zero for both clock and CPU time. + timer().stop(); + timer().reset(); + timer().start(); + + // Test + BOOST_CHECK_SMALL(timer().realTime(), small_realtime); + BOOST_CHECK_SMALL(timer().cpuTime(), small_cputime); +} + +BOOST_AUTO_TEST_CASE(doubleStop) +{ + // Make sure the time between two stop() calls without an intervening + // start() or reset() does not change. + timer().stop(); + timer().reset(); + timer().start(); + double const dur = 0.150; // seconds + std::cout << busy_loop(dur) << "\n"; + timer().stop(); + double real = timer().realTime(); + double cpu = timer().cpuTime(); + timer().stop(); + + BOOST_CHECK_EQUAL(timer().realTime(), real); + BOOST_CHECK_EQUAL(timer().cpuTime(), cpu); +} + +BOOST_AUTO_TEST_CASE(reset) +{ + // Make sure reset() zeros both real and CPU time. + timer().start(); + double const dur = 0.150; + std::cout << busy_loop(dur) << "\n"; + timer().stop(); + BOOST_CHECK_GT(timer().realTime(), 0.0); + BOOST_CHECK_GT(timer().cpuTime(), 0.0); + + timer().reset(); + BOOST_CHECK_EQUAL(timer().realTime(), 0.0); + BOOST_CHECK_EQUAL(timer().cpuTime(), 0.0); +} + + +BOOST_AUTO_TEST_CASE(checkUsage) +{ + timer().stop(); + timer().reset(); + timer().start(); + + double const dur = 0.135; + std::cout << busy_loop(dur) << "\n"; + timer().stop(); + + BOOST_CHECK_CLOSE(timer().realTime(), dur, 5.0); + BOOST_CHECK_CLOSE(timer().cpuTime(), dur, 5.0); +} + +BOOST_AUTO_TEST_SUITE_END() diff --git a/pool/shard001/C++/0023250_omnibox_popup_model.cc b/pool/shard001/C++/0023250_omnibox_popup_model.cc new file mode 100644 index 0000000000000000000000000000000000000000..2284acc259a70bbd4b9218dbbc493f18b71c1d4f --- /dev/null +++ b/pool/shard001/C++/0023250_omnibox_popup_model.cc @@ -0,0 +1,303 @@ +// 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/ui/omnibox/omnibox_popup_model.h" + +#include + +#include "base/strings/string_util.h" +#include "base/strings/utf_string_conversions.h" +#include "chrome/browser/bookmarks/bookmark_model_factory.h" +#include "chrome/browser/extensions/api/omnibox/omnibox_api.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/search_engines/template_url_service_factory.h" +#include "chrome/browser/ui/omnibox/omnibox_popup_model_observer.h" +#include "chrome/browser/ui/omnibox/omnibox_popup_view.h" +#include "components/bookmarks/browser/bookmark_model.h" +#include "components/omnibox/autocomplete_match.h" +#include "components/search_engines/template_url.h" +#include "components/search_engines/template_url_service.h" +#include "third_party/icu/source/common/unicode/ubidi.h" +#include "ui/gfx/geometry/rect.h" +#include "ui/gfx/image/image.h" + +using bookmarks::BookmarkModel; + +/////////////////////////////////////////////////////////////////////////////// +// OmniboxPopupModel + +const size_t OmniboxPopupModel::kNoMatch = static_cast(-1); + +OmniboxPopupModel::OmniboxPopupModel( + OmniboxPopupView* popup_view, + OmniboxEditModel* edit_model) + : view_(popup_view), + edit_model_(edit_model), + hovered_line_(kNoMatch), + selected_line_(kNoMatch), + selected_line_state_(NORMAL) { + edit_model->set_popup_model(this); +} + +OmniboxPopupModel::~OmniboxPopupModel() { +} + +// static +void OmniboxPopupModel::ComputeMatchMaxWidths(int contents_width, + int separator_width, + int description_width, + int available_width, + bool allow_shrinking_contents, + int* contents_max_width, + int* description_max_width) { + available_width = std::max(available_width, 0); + *contents_max_width = std::min(contents_width, available_width); + *description_max_width = description_width; + + // If the description is empty, the contents can get the full width. + if (!description_width) + return; + + // If we want to display the description, we need to reserve enough space for + // the separator. + available_width -= separator_width; + if (available_width < 0) { + *description_max_width = 0; + return; + } + + if (contents_width + description_width > available_width) { + if (allow_shrinking_contents) { + // Try to split the available space fairly between contents and + // description (if one wants less than half, give it all it wants and + // give the other the remaining space; otherwise, give each half). + // However, if this makes the contents too narrow to show a significant + // amount of information, give the contents more space. + *contents_max_width = std::max( + (available_width + 1) / 2, available_width - description_width); + + const int kMinimumContentsWidth = 300; + *contents_max_width = std::min(std::min( + std::max(*contents_max_width, kMinimumContentsWidth), contents_width), + available_width); + } + + // Give the description the remaining space, unless this makes it too small + // to display anything meaningful, in which case just hide the description + // and let the contents take up the whole width. + *description_max_width = + std::min(description_width, available_width - *contents_max_width); + const int kMinimumDescriptionWidth = 75; + if (*description_max_width < + std::min(description_width, kMinimumDescriptionWidth)) { + *description_max_width = 0; + // Since we're not going to display the description, the contents can have + // the space we reserved for the separator. + available_width += separator_width; + *contents_max_width = std::min(contents_width, available_width); + } + } +} + +bool OmniboxPopupModel::IsOpen() const { + return view_->IsOpen(); +} + +void OmniboxPopupModel::SetHoveredLine(size_t line) { + const bool is_disabling = (line == kNoMatch); + DCHECK(is_disabling || (line < result().size())); + + if (line == hovered_line_) + return; // Nothing to do + + // Make sure the old hovered line is redrawn. No need to redraw the selected + // line since selection overrides hover so the appearance won't change. + if ((hovered_line_ != kNoMatch) && (hovered_line_ != selected_line_)) + view_->InvalidateLine(hovered_line_); + + // Change the hover to the new line. + hovered_line_ = line; + if (!is_disabling && (hovered_line_ != selected_line_)) + view_->InvalidateLine(hovered_line_); +} + +void OmniboxPopupModel::SetSelectedLine(size_t line, + bool reset_to_default, + bool force) { + const AutocompleteResult& result = this->result(); + if (result.empty()) + return; + + // Cancel the query so the matches don't change on the user. + autocomplete_controller()->Stop(false); + + line = std::min(line, result.size() - 1); + const AutocompleteMatch& match = result.match_at(line); + if (reset_to_default) { + manually_selected_match_.Clear(); + } else { + // Track the user's selection until they cancel it. + manually_selected_match_.destination_url = match.destination_url; + manually_selected_match_.provider_affinity = match.provider; + manually_selected_match_.is_history_what_you_typed_match = + match.is_history_what_you_typed_match; + } + + if (line == selected_line_ && !force) + return; // Nothing else to do. + + // We need to update |selected_line_state_| and |selected_line_| before + // calling InvalidateLine(), since it will check them to determine how to + // draw. We also need to update |selected_line_| before calling + // OnPopupDataChanged(), so that when the edit notifies its controller that + // something has changed, the controller can get the correct updated data. + // + // NOTE: We should never reach here with no selected line; the same code that + // opened the popup and made it possible to get here should have also set a + // selected line. + CHECK(selected_line_ != kNoMatch); + GURL current_destination(result.match_at(selected_line_).destination_url); + const size_t prev_selected_line = selected_line_; + selected_line_state_ = NORMAL; + selected_line_ = line; + view_->InvalidateLine(prev_selected_line); + view_->InvalidateLine(selected_line_); + + // Update the edit with the new data for this match. + // TODO(pkasting): If |selected_line_| moves to the controller, this can be + // eliminated and just become a call to the observer on the edit. + base::string16 keyword; + bool is_keyword_hint; + TemplateURLService* service = + TemplateURLServiceFactory::GetForProfile(edit_model_->profile()); + match.GetKeywordUIState(service, &keyword, &is_keyword_hint); + + if (reset_to_default) { + edit_model_->OnPopupDataChanged(match.inline_autocompletion, NULL, + keyword, is_keyword_hint); + } else { + edit_model_->OnPopupDataChanged(match.fill_into_edit, ¤t_destination, + keyword, is_keyword_hint); + } + + // Repaint old and new selected lines immediately, so that the edit doesn't + // appear to update [much] faster than the popup. + view_->PaintUpdatesNow(); +} + +void OmniboxPopupModel::ResetToDefaultMatch() { + const AutocompleteResult& result = this->result(); + CHECK(!result.empty()); + SetSelectedLine(result.default_match() - result.begin(), true, false); + view_->OnDragCanceled(); +} + +void OmniboxPopupModel::Move(int count) { + const AutocompleteResult& result = this->result(); + if (result.empty()) + return; + + // The user is using the keyboard to change the selection, so stop tracking + // hover. + SetHoveredLine(kNoMatch); + + // Clamp the new line to [0, result_.count() - 1]. + const size_t new_line = selected_line_ + count; + SetSelectedLine(((count < 0) && (new_line >= selected_line_)) ? 0 : new_line, + false, false); +} + +void OmniboxPopupModel::SetSelectedLineState(LineState state) { + DCHECK(!result().empty()); + DCHECK_NE(kNoMatch, selected_line_); + + const AutocompleteMatch& match = result().match_at(selected_line_); + DCHECK(match.associated_keyword.get()); + + selected_line_state_ = state; + view_->InvalidateLine(selected_line_); +} + +void OmniboxPopupModel::TryDeletingCurrentItem() { + // We could use GetInfoForCurrentText() here, but it seems better to try + // and shift-delete the actual selection, rather than any "in progress, not + // yet visible" one. + if (selected_line_ == kNoMatch) + return; + + // Cancel the query so the matches don't change on the user. + autocomplete_controller()->Stop(false); + + const AutocompleteMatch& match = result().match_at(selected_line_); + if (match.SupportsDeletion()) { + const size_t selected_line = selected_line_; + const bool was_temporary_text = !manually_selected_match_.empty(); + + // This will synchronously notify both the edit and us that the results + // have changed, causing both to revert to the default match. + autocomplete_controller()->DeleteMatch(match); + const AutocompleteResult& result = this->result(); + if (!result.empty() && + (was_temporary_text || selected_line != selected_line_)) { + // Move the selection to the next choice after the deleted one. + // SetSelectedLine() will clamp to take care of the case where we deleted + // the last item. + // TODO(pkasting): Eventually the controller should take care of this + // before notifying us, reducing flicker. At that point the check for + // deletability can move there too. + SetSelectedLine(selected_line, false, true); + } + } +} + +gfx::Image OmniboxPopupModel::GetIconIfExtensionMatch( + const AutocompleteMatch& match) const { + Profile* profile = edit_model_->profile(); + TemplateURLService* service = + TemplateURLServiceFactory::GetForProfile(profile); + const TemplateURL* template_url = match.GetTemplateURL(service, false); + if (template_url && + (template_url->GetType() == TemplateURL::OMNIBOX_API_EXTENSION)) { + return extensions::OmniboxAPI::Get(profile)->GetOmniboxPopupIcon( + template_url->GetExtensionId()); + } + return gfx::Image(); +} + +bool OmniboxPopupModel::IsStarredMatch(const AutocompleteMatch& match) const { + Profile* profile = edit_model_->profile(); + BookmarkModel* bookmark_model = BookmarkModelFactory::GetForProfile(profile); + return bookmark_model && bookmark_model->IsBookmarked(match.destination_url); +} + +void OmniboxPopupModel::OnResultChanged() { + const AutocompleteResult& result = this->result(); + selected_line_ = result.default_match() == result.end() ? + kNoMatch : static_cast(result.default_match() - result.begin()); + // There had better not be a nonempty result set with no default match. + CHECK((selected_line_ != kNoMatch) || result.empty()); + manually_selected_match_.Clear(); + selected_line_state_ = NORMAL; + // If we're going to trim the window size to no longer include the hovered + // line, turn hover off. Practically, this shouldn't happen, but it + // doesn't hurt to be defensive. + if ((hovered_line_ != kNoMatch) && (result.size() <= hovered_line_)) + SetHoveredLine(kNoMatch); + + bool popup_was_open = view_->IsOpen(); + view_->UpdatePopupAppearance(); + // If popup has just been shown or hidden, notify observers. + if (view_->IsOpen() != popup_was_open) { + FOR_EACH_OBSERVER(OmniboxPopupModelObserver, observers_, + OnOmniboxPopupShownOrHidden()); + } +} + +void OmniboxPopupModel::AddObserver(OmniboxPopupModelObserver* observer) { + observers_.AddObserver(observer); +} + +void OmniboxPopupModel::RemoveObserver(OmniboxPopupModelObserver* observer) { + observers_.RemoveObserver(observer); +} diff --git a/pool/shard001/C++/0023251_call_frame.cpp b/pool/shard001/C++/0023251_call_frame.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9b0692ef2347d8b7973dbadbff8837bcc4bda209 --- /dev/null +++ b/pool/shard001/C++/0023251_call_frame.cpp @@ -0,0 +1,171 @@ +#include + +#include "call_frame.hpp" +#include "builtin/variable_scope.hpp" +#include "builtin/class.hpp" +#include "builtin/module.hpp" +#include "builtin/symbol.hpp" +#include "builtin/compiledmethod.hpp" +#include "builtin/tuple.hpp" +#include "builtin/staticscope.hpp" +#include "builtin/lookuptable.hpp" + +#include "object_utils.hpp" + +namespace rubinius { + VariableScope* CallFrame::promote_scope_full(STATE) { + return scope->create_heap_alias(state, this, !has_closed_scope_p()); + } + + VariableScope* CallFrame::method_scope(STATE) { + VariableScope* current = promote_scope(state); + if(!multiple_scopes_p()) return current; + + for(;;) { + if(current->block_as_method_p()) return current; + VariableScope* parent = current->parent(); + if(!parent->nil_p()) { + current = parent; + } else { + return current; + } + } + + // Shouldn't ever get here. + return 0; + } + + void CallFrame::print_backtrace(STATE) { + print_backtrace(state, std::cout); + } + + void CallFrame::print_backtrace(STATE, std::ostream& stream) { + CallFrame* cf = this; + + while(cf) { + if(!cf->cm) { + cf = static_cast(cf->previous); + continue; + } + + stream << static_cast(cf) << ": "; + + if(cf->is_block_p(state)) { + stream << "__block__"; + } else { + if(MetaClass* meta = try_as(cf->module())) { + if(Module* mod = try_as(meta->attached_instance())) { + stream << mod->name()->c_str(state) << "."; + } else { + if(meta->attached_instance() == G(main)) { + stream << "MAIN."; + } else { + stream << "#<" << + meta->attached_instance()->class_object(state)->name()->c_str(state) << + ":" << (void*)meta->attached_instance()->id(state)->to_native() << ">."; + } + } + } else if(IncludedModule* im = try_as(cf->module())) { + if(im->module()->name()->nil_p()) { + stream << "#"; + } else { + stream << im->module()->name()->c_str(state) << "#"; + } + } else { + const char* mod_name; + if(cf->module()->nil_p()) { + mod_name = cf->cm->scope()->module()->name()->c_str(state); + } else if(cf->module()->name()->nil_p()) { + mod_name = cf->cm->scope()->module()->name()->c_str(state); + } else { + mod_name = cf->module()->name()->c_str(state); + } + stream << mod_name << "#"; + } + + Symbol* name = try_as(cf->name()); + if(name) { + stream << name->c_str(state); + } else { + stream << cf->cm->name()->c_str(state); + } + } + + stream << " in "; + if(Symbol* file_sym = try_as(cf->cm->file())) { + stream << file_sym->c_str(state) << ":" << cf->line(state); + } else { + stream << ""; + } + + stream << " (+" << cf->ip(); + if(cf->is_inline_frame()) { + stream << " inline"; + } else if(cf->jitted_p()) { + stream << " jit"; + } + stream << ")"; + + stream << std::endl; + cf = static_cast(cf->previous); + } + + } + + int CallFrame::line(STATE) { + if(!cm) return -2; // trampoline context + return cm->line(state, ip()); + } + + // Walks the CallFrame list to see if +scope+ is still running + bool CallFrame::scope_still_valid(VariableScope* scope) { + CallFrame* cur = this; + while(cur) { + if(cur->scope->on_heap() == scope) return true; + cur = static_cast(cur->previous); + } + + return false; + } + + void CallFrame::dump() { + VM* state = VM::current_state(); + std::cout << "\n"; + } + + Object* CallFrame::find_breakpoint(STATE) { + LookupTable* tbl = cm->breakpoints(); + if(tbl->nil_p()) return 0; + + bool found = false; + + Object* obj = tbl->fetch(state, Fixnum::from(ip()), &found); + if(found) return obj; + + return 0; + } + + /* For debugging. */ + extern "C" { + void __printbt__(CallFrame* call_frame) { + call_frame->print_backtrace(VM::current_state()); + } + } +} diff --git a/pool/shard001/C++/0023267_Client.cpp b/pool/shard001/C++/0023267_Client.cpp new file mode 100644 index 0000000000000000000000000000000000000000..73910949b57ef4ebd19692492b53b3be2ddab6a7 --- /dev/null +++ b/pool/shard001/C++/0023267_Client.cpp @@ -0,0 +1,93 @@ +// ********************************************************************** +// +// Copyright (c) 2003-2015 ZeroC, Inc. All rights reserved. +// +// This copy of Ice is licensed to you under the terms described in the +// ICE_LICENSE file included in this distribution. +// +// ********************************************************************** + +#include +#include +#include +#include + +DEFINE_TEST("client") + +using namespace std; +using namespace Test; + +int +run(int, char**, const Ice::CommunicatorPtr& communicator, const Ice::CommunicatorPtr& communicator2) +{ + RetryPrx allTests(const Ice::CommunicatorPtr&, const Ice::CommunicatorPtr&, const string&); + RetryPrx retry = allTests(communicator, communicator2, "retry:default -p 12010"); + retry->shutdown(); + return EXIT_SUCCESS; +} + +int +main(int argc, char* argv[]) +{ + int status; + Ice::CommunicatorPtr communicator; + Ice::CommunicatorPtr communicator2; + + try + { + Ice::InitializationData initData; + initData.properties = Ice::createProperties(argc, argv); + initData.observer = getObserver(); + // + // This test kills connections, so we don't want warnings. + // + initData.properties->setProperty("Ice.Warn.Connections", "0"); + + initData.properties->setProperty("Ice.RetryIntervals", "0 1 10 1"); + communicator = Ice::initialize(argc, argv, initData); + + // + // Configure a second communicator for the invocation timeout + // + retry test, we need to configure a large retry interval + // to avoid time-sensitive failures. + // + Ice::InitializationData initData2; + initData2.properties = initData.properties->clone(); + initData2.properties->setProperty("Ice.RetryIntervals", "0 1 10000"); + initData2.observer = getObserver(); + communicator2 = Ice::initialize(initData2); + status = run(argc, argv, communicator, communicator2); + } + catch(const Ice::Exception& ex) + { + cerr << ex << endl; + status = EXIT_FAILURE; + } + + if(communicator) + { + try + { + communicator->destroy(); + } + catch(const Ice::Exception& ex) + { + cerr << ex << endl; + status = EXIT_FAILURE; + } + } + if(communicator2) + { + try + { + communicator2->destroy(); + } + catch(const Ice::Exception& ex) + { + cerr << ex << endl; + status = EXIT_FAILURE; + } + } + + return status; +} diff --git a/pool/shard001/C++/0023271_gdal_multipolygon.cpp b/pool/shard001/C++/0023271_gdal_multipolygon.cpp new file mode 100644 index 0000000000000000000000000000000000000000..56648492bd6743c921cddf7213a2a7f4401882fd --- /dev/null +++ b/pool/shard001/C++/0023271_gdal_multipolygon.cpp @@ -0,0 +1,160 @@ +#include "gdal_common.hpp" +#include "gdal_geometry.hpp" +#include "gdal_geometrycollection.hpp" +#include "gdal_multipolygon.hpp" +#include "gdal_polygon.hpp" +#include "collections/geometry_collection_children.hpp" + +#include + +namespace node_gdal { + +Nan::Persistent MultiPolygon::constructor; + +void MultiPolygon::Initialize(Local target) +{ + Nan::HandleScope scope; + + Local lcons = Nan::New(MultiPolygon::New); + lcons->Inherit(Nan::New(GeometryCollection::constructor)); + lcons->InstanceTemplate()->SetInternalFieldCount(1); + lcons->SetClassName(Nan::New("MultiPolygon").ToLocalChecked()); + + Nan::SetPrototypeMethod(lcons, "toString", toString); + Nan::SetPrototypeMethod(lcons, "unionCascaded", unionCascaded); + Nan::SetPrototypeMethod(lcons, "getArea", getArea); + + target->Set(Nan::New("MultiPolygon").ToLocalChecked(), lcons->GetFunction()); + + constructor.Reset(lcons); +} + +MultiPolygon::MultiPolygon(OGRMultiPolygon *geom) + : Nan::ObjectWrap(), + this_(geom), + owned_(true), + size_(0) +{ + LOG("Created MultiPolygon [%p]", geom); +} + +MultiPolygon::MultiPolygon() + : Nan::ObjectWrap(), + this_(NULL), + owned_(true), + size_(0) +{ +} + +MultiPolygon::~MultiPolygon() +{ + if(this_) { + LOG("Disposing MultiPolygon [%p] (%s)", this_, owned_ ? "owned" : "unowned"); + if (owned_) { + OGRGeometryFactory::destroyGeometry(this_); + Nan::AdjustExternalMemory(-size_); + } + LOG("Disposed MultiPolygon [%p]", this_); + this_ = NULL; + } +} + +/** + * @constructor + * @class gdal.MultiPolygon + * @extends gdal.GeometryCollection + */ +NAN_METHOD(MultiPolygon::New) +{ + Nan::HandleScope scope; + MultiPolygon *f; + + if (!info.IsConstructCall()) { + Nan::ThrowError("Cannot call constructor as function, you need to use 'new' keyword"); + return; + } + + if (info[0]->IsExternal()) { + Local ext = info[0].As(); + void* ptr = ext->Value(); + f = static_cast(ptr); + + } else { + if (info.Length() != 0) { + Nan::ThrowError("MultiPolygon constructor doesn't take any arguments"); + return; + } + f = new MultiPolygon(new OGRMultiPolygon()); + } + + Local children = GeometryCollectionChildren::New(info.This()); + info.This()->SetHiddenValue(Nan::New("children_").ToLocalChecked(), children); + + f->Wrap(info.This()); + info.GetReturnValue().Set(info.This()); +} + +Local MultiPolygon::New(OGRMultiPolygon *geom) +{ + Nan::EscapableHandleScope scope; + return scope.Escape(MultiPolygon::New(geom, true)); +} + +Local MultiPolygon::New(OGRMultiPolygon *geom, bool owned) +{ + Nan::EscapableHandleScope scope; + + if (!geom) { + return scope.Escape(Nan::Null()); + } + + //make a copy of geometry owned by a feature + // + no need to track when a feature is destroyed + // + no need to throw errors when a method trys to modify an owned read-only geometry + // - is slower + + if (!owned) { + geom = static_cast(geom->clone()); + }; + + MultiPolygon *wrapped = new MultiPolygon(geom); + wrapped->owned_ = true; + + UPDATE_AMOUNT_OF_GEOMETRY_MEMORY(wrapped); + + Local ext = Nan::New(wrapped); + Local obj = Nan::New(MultiPolygon::constructor)->GetFunction()->NewInstance(1, &ext); + + return scope.Escape(obj); +} + +NAN_METHOD(MultiPolygon::toString) +{ + Nan::HandleScope scope; + info.GetReturnValue().Set(Nan::New("MultiPolygon").ToLocalChecked()); +} + +/** + * Unions all the geometries and returns the result. + * + * @method unionCascaded + * @return {gdal.Geometry} + */ +NAN_METHOD(MultiPolygon::unionCascaded) +{ + Nan::HandleScope scope; + + MultiPolygon *geom = Nan::ObjectWrap::Unwrap(info.This()); + + info.GetReturnValue().Set(Geometry::New(geom->this_->UnionCascaded())); +} + +/** + * Computes the combined area of the collection. + * + * @method getArea + * @return {Number} + */ +NODE_WRAPPED_METHOD_WITH_RESULT(MultiPolygon, getArea, Number, get_Area); + +} // namespace node_gdal \ No newline at end of file diff --git a/pool/shard001/C++/0023279_archive.cpp b/pool/shard001/C++/0023279_archive.cpp new file mode 100644 index 0000000000000000000000000000000000000000..360f22936c43c857a9f4b3d9e3a66edd3e20461c --- /dev/null +++ b/pool/shard001/C++/0023279_archive.cpp @@ -0,0 +1,97 @@ +///////////////////////////////////////////////////////////////////////////// +// Name: src/common/archive.cpp +// Purpose: Streams for archive formats +// Author: Mike Wetherell +// Copyright: (c) Mike Wetherell +// Licence: wxWindows licence +///////////////////////////////////////////////////////////////////////////// + +// For compilers that support precompilation, includes "wx.h". +#include "wx/wxprec.h" + +#ifdef __BORLANDC__ + #pragma hdrstop +#endif + +#if wxUSE_STREAMS && wxUSE_ARCHIVE_STREAMS + +#include "wx/archive.h" + +IMPLEMENT_ABSTRACT_CLASS(wxArchiveEntry, wxObject) +IMPLEMENT_ABSTRACT_CLASS(wxArchiveClassFactory, wxFilterClassFactoryBase) + + +///////////////////////////////////////////////////////////////////////////// +// wxArchiveInputStream + +wxArchiveInputStream::wxArchiveInputStream(wxInputStream& stream, + wxMBConv& conv) + : wxFilterInputStream(stream), + m_conv(conv) +{ +} + +wxArchiveInputStream::wxArchiveInputStream(wxInputStream *stream, + wxMBConv& conv) + : wxFilterInputStream(stream), + m_conv(conv) +{ +} + + +///////////////////////////////////////////////////////////////////////////// +// wxArchiveOutputStream + +wxArchiveOutputStream::wxArchiveOutputStream(wxOutputStream& stream, + wxMBConv& conv) + : wxFilterOutputStream(stream), + m_conv(conv) +{ +} + +wxArchiveOutputStream::wxArchiveOutputStream(wxOutputStream *stream, + wxMBConv& conv) + : wxFilterOutputStream(stream), + m_conv(conv) +{ +} + + +///////////////////////////////////////////////////////////////////////////// +// wxArchiveEntry + +void wxArchiveEntry::SetNotifier(wxArchiveNotifier& notifier) +{ + UnsetNotifier(); + m_notifier = ¬ifier; + m_notifier->OnEntryUpdated(*this); +} + +wxArchiveEntry& wxArchiveEntry::operator=(const wxArchiveEntry& WXUNUSED(e)) +{ + m_notifier = NULL; + return *this; +} + + +///////////////////////////////////////////////////////////////////////////// +// wxArchiveClassFactory + +wxArchiveClassFactory *wxArchiveClassFactory::sm_first = NULL; + +void wxArchiveClassFactory::Remove() +{ + if (m_next != this) + { + wxArchiveClassFactory **pp = &sm_first; + + while (*pp != this) + pp = &(*pp)->m_next; + + *pp = m_next; + + m_next = this; + } +} + +#endif // wxUSE_STREAMS && wxUSE_ARCHIVE_STREAMS diff --git a/pool/shard001/C++/0023280_main.cpp b/pool/shard001/C++/0023280_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b1ee5d141454aafbb6d60b5dd921f611ccdd8278 --- /dev/null +++ b/pool/shard001/C++/0023280_main.cpp @@ -0,0 +1,40 @@ +#include +#include +#include +#include +#include +#include +#include "requestmapper.h" + +#include "server.h" + +QString getConfigFileName() { + QString binDir = QCoreApplication::applicationDirPath(); + QString appName = QCoreApplication::applicationName(); + QString fileName(appName+".ini"); + QFile file(binDir+"/"+fileName); + + return (file.exists()) ? fileName : NULL; +} + +int main(int argc, char *argv[]) +{ + QCoreApplication app(argc,argv); + + app.setApplicationName("Port-Server"); + app.setOrganizationName("port-42"); + + QString configFileName = getConfigFileName(); + + // Configure and start the TCP listener + QSettings* listenerSettings=new QSettings(configFileName,QSettings::IniFormat,&app); + listenerSettings->beginGroup("listener"); + + new HttpListener(listenerSettings, new RequestMapper(&app),&app); + + qWarning("Server has started"); + + app.exec(); + + qWarning("Server has stopped"); +} diff --git a/pool/shard001/C++/0023281_GoToDlg.cpp b/pool/shard001/C++/0023281_GoToDlg.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ecf670d660025aa533e525c6bb49df413cef1e59 --- /dev/null +++ b/pool/shard001/C++/0023281_GoToDlg.cpp @@ -0,0 +1,196 @@ +/* + * (C) 2003-2006 Gabest + * (C) 2006-2014 see Authors.txt + * + * This file is part of MPC-HC. + * + * MPC-HC 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. + * + * MPC-HC 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 "mplayerc.h" +#include "GoToDlg.h" +#include "SettingsDefines.h" +#include + +// CGoToDlg dialog + +IMPLEMENT_DYNAMIC(CGoToDlg, CDialog) +CGoToDlg::CGoToDlg(REFERENCE_TIME time, REFERENCE_TIME maxTime, double fps, CWnd* pParent /*=nullptr*/) + : CDialog(CGoToDlg::IDD, pParent) + , m_time(time) + , m_maxTime(maxTime) + , m_fps(fps) +{ + if (m_fps == 0) { + CString str = AfxGetApp()->GetProfileString(IDS_R_SETTINGS, IDS_RS_GOTO_FPS, _T("0")); + float fps2; + if (_stscanf_s(str, _T("%f"), &fps2) == 1) { + m_fps = fps2; + } + } +} + +CGoToDlg::~CGoToDlg() +{ +} + +void CGoToDlg::DoDataExchange(CDataExchange* pDX) +{ + CDialog::DoDataExchange(pDX); + DDX_Text(pDX, IDC_EDIT1, m_timestr); + DDX_Text(pDX, IDC_EDIT2, m_framestr); + DDX_Control(pDX, IDC_EDIT1, m_timeedit); + DDX_Control(pDX, IDC_EDIT2, m_frameedit); +} + +BOOL CGoToDlg::OnInitDialog() +{ + CDialog::OnInitDialog(); + + bool showHours = (m_maxTime >= 3600 * 1000 * 10000i64); + + if (showHours) { + m_timeedit.EnableMask(_T("DD DD DD DDD"), _T("__:__:__.___"), L'0', _T("0123456789")); + } else { + m_timeedit.EnableMask(_T("DD DD DDD"), _T("__:__.___"), L'0', _T("0123456789")); + } + m_timeedit.EnableGetMaskedCharsOnly(false); + m_timeedit.EnableSelectByGroup(false); + + int time = (int)(m_time / 10000); + if (time >= 0) { + if (showHours) { + m_timestr.Format(_T("%02d:%02d:%02d.%03d"), + (time / (1000 * 60 * 60)) % 60, + (time / (1000 * 60)) % 60, + (time / 1000) % 60, time % 1000); + } else { + m_timestr.Format(_T("%02d:%02d.%03d"), + (time / (1000 * 60)) % 60, + (time / 1000) % 60, + time % 1000); + } + + if (m_fps > 0) { + m_framestr.Format(_T("%d, %.3f"), (int)(m_fps * m_time / 10000000 + 0.5), m_fps); + } + + UpdateData(FALSE); + + switch (AfxGetApp()->GetProfileInt(IDS_R_SETTINGS, IDS_RS_GOTO_LAST_USED, TYPE_TIME)) { + default: + case TYPE_TIME: + m_timeedit.SetFocus(); + m_timeedit.SetSel(0, 0); + break; + case TYPE_FRAME: + m_frameedit.SetFocus(); + m_frameedit.SetSel(0, m_framestr.Find(',')); + break; + } + + } + + return FALSE; + + // return TRUE; // return TRUE unless you set the focus to a control + // EXCEPTION: OCX Property Pages should return FALSE +} + + +BEGIN_MESSAGE_MAP(CGoToDlg, CDialog) + ON_BN_CLICKED(IDC_OK1, OnParseTimeCode) + ON_BN_CLICKED(IDC_OK2, OnParseFrameCode) +END_MESSAGE_MAP() + + +// CGoToDlg message handlers + +void CGoToDlg::OnParseTimeCode() +{ + UpdateData(); + + AfxGetApp()->WriteProfileInt(IDS_R_SETTINGS, IDS_RS_GOTO_LAST_USED, TYPE_TIME); + + // The hh and mm are declared volatile to work around a compiler bug with ICL 13. + // It prevents the compiler to optimize out those variables from the computation. + volatile unsigned int hh = 0; + volatile unsigned int mm = 0; + float ss = 0.0f; + wchar_t c[2]; // unnecessary character + + if (((swscanf_s(m_timestr, L"%f%1s", &ss, c, _countof(c)) == 1) // ss[.ms] + || (swscanf_s(m_timestr, L"%u:%f%1s", &mm, &ss, c, _countof(c)) == 2 && ss < 60.0f) // mm:ss[.ms] + || (swscanf_s(m_timestr, L"%u:%u:%f%1s", &hh, &mm, &ss, c, _countof(c)) == 3 && mm < 60 && ss < 60.0f)) // hh:mm:ss[.ms] + && ss >= 0.0f) { + + int time = (int)(1000.0f * ((hh * 60 + mm) * 60 + ss) + 0.5f); + m_time = time * 10000i64; + + OnOK(); + } else { + AfxMessageBox(IDS_GOTO_ERROR_PARSING_TIME, MB_ICONEXCLAMATION | MB_OK, 0); + } +} + +void CGoToDlg::OnParseFrameCode() +{ + UpdateData(); + + AfxGetApp()->WriteProfileInt(IDS_R_SETTINGS, IDS_RS_GOTO_LAST_USED, TYPE_FRAME); + + unsigned int frame; + float fps; + wchar_t c1[2]; // delimiter character + wchar_t c2[2]; // unnecessary character + + int result = swscanf_s(m_framestr, L"%u%1s%f%1s", &frame, c1, _countof(c1), &fps, c2, _countof(c2)); + if (result == 1) { + m_time = (REFERENCE_TIME)ceil(10000000.0 * frame / m_fps); + OnOK(); + } else if (result == 3 && c1[0] == L',') { + m_time = (REFERENCE_TIME)ceil(10000000.0 * frame / fps); + OnOK(); + } else if (result == 0 || c1[0] != L',') { + AfxMessageBox(IDS_GOTO_ERROR_PARSING_TEXT, MB_ICONEXCLAMATION | MB_OK, 0); + } else { + AfxMessageBox(IDS_GOTO_ERROR_PARSING_FPS, MB_ICONEXCLAMATION | MB_OK, 0); + } +} + +void CGoToDlg::OnOK() +{ + if (m_time > m_maxTime) { + AfxMessageBox(IDS_GOTO_ERROR_INVALID_TIME, MB_ICONEXCLAMATION | MB_OK, 0); + } else { + __super::OnOK(); + } +} + +BOOL CGoToDlg::PreTranslateMessage(MSG* pMsg) +{ + if (pMsg->message == WM_KEYDOWN && pMsg->wParam == VK_RETURN) { + if (*GetFocus() == m_timeedit) { + OnParseTimeCode(); + } else if (*GetFocus() == m_frameedit) { + OnParseFrameCode(); + } + + return TRUE; + } + + return __super::PreTranslateMessage(pMsg); +} diff --git a/pool/shard001/C++/0023285_secret_manager_impl.cc b/pool/shard001/C++/0023285_secret_manager_impl.cc new file mode 100644 index 0000000000000000000000000000000000000000..aed0c374255c4c37d3e82dfe968a3f050abc5513 --- /dev/null +++ b/pool/shard001/C++/0023285_secret_manager_impl.cc @@ -0,0 +1,83 @@ +#include "common/secret/secret_manager_impl.h" + +#include "envoy/common/exception.h" + +#include "common/common/assert.h" +#include "common/secret/sds_api.h" +#include "common/secret/secret_provider_impl.h" +#include "common/ssl/certificate_validation_context_config_impl.h" +#include "common/ssl/tls_certificate_config_impl.h" + +namespace Envoy { +namespace Secret { + +void SecretManagerImpl::addStaticSecret(const envoy::api::v2::auth::Secret& secret) { + switch (secret.type_case()) { + case envoy::api::v2::auth::Secret::TypeCase::kTlsCertificate: { + auto secret_provider = + std::make_shared(secret.tls_certificate()); + if (!static_tls_certificate_providers_.insert(std::make_pair(secret.name(), secret_provider)) + .second) { + throw EnvoyException( + fmt::format("Duplicate static TlsCertificate secret name {}", secret.name())); + } + break; + } + case envoy::api::v2::auth::Secret::TypeCase::kValidationContext: { + auto secret_provider = std::make_shared( + secret.validation_context()); + if (!static_certificate_validation_context_providers_ + .insert(std::make_pair(secret.name(), secret_provider)) + .second) { + throw EnvoyException(fmt::format( + "Duplicate static CertificateValidationContext secret name {}", secret.name())); + } + break; + } + default: + throw EnvoyException("Secret type not implemented"); + } +} + +TlsCertificateConfigProviderSharedPtr +SecretManagerImpl::findStaticTlsCertificateProvider(const std::string& name) const { + auto secret = static_tls_certificate_providers_.find(name); + return (secret != static_tls_certificate_providers_.end()) ? secret->second : nullptr; +} + +CertificateValidationContextConfigProviderSharedPtr +SecretManagerImpl::findStaticCertificateValidationContextProvider(const std::string& name) const { + auto secret = static_certificate_validation_context_providers_.find(name); + return (secret != static_certificate_validation_context_providers_.end()) ? secret->second + : nullptr; +} + +TlsCertificateConfigProviderSharedPtr SecretManagerImpl::createInlineTlsCertificateProvider( + const envoy::api::v2::auth::TlsCertificate& tls_certificate) { + return std::make_shared(tls_certificate); +} + +CertificateValidationContextConfigProviderSharedPtr +SecretManagerImpl::createInlineCertificateValidationContextProvider( + const envoy::api::v2::auth::CertificateValidationContext& certificate_validation_context) { + return std::make_shared( + certificate_validation_context); +} + +TlsCertificateConfigProviderSharedPtr SecretManagerImpl::findOrCreateTlsCertificateProvider( + const envoy::api::v2::core::ConfigSource& sds_config_source, const std::string& config_name, + Server::Configuration::TransportSocketFactoryContext& secret_provider_context) { + return certificate_providers_.findOrCreate(sds_config_source, config_name, + secret_provider_context); +} + +CertificateValidationContextConfigProviderSharedPtr +SecretManagerImpl::findOrCreateCertificateValidationContextProvider( + const envoy::api::v2::core::ConfigSource& sds_config_source, const std::string& config_name, + Server::Configuration::TransportSocketFactoryContext& secret_provider_context) { + return validation_context_providers_.findOrCreate(sds_config_source, config_name, + secret_provider_context); +} + +} // namespace Secret +} // namespace Envoy diff --git a/pool/shard001/C++/0023287_randomgenerator.cpp b/pool/shard001/C++/0023287_randomgenerator.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0825ee3468296fbb0a0b10802a70f8f42d0756ce --- /dev/null +++ b/pool/shard001/C++/0023287_randomgenerator.cpp @@ -0,0 +1,110 @@ +#include "randomgenerator.h" + +using namespace std; +//Use a portable implementation of random_device to seed the generator + +RandomGenerator::RandomGenerator() +{ + gen= new std::minstd_rand0; + this->seed=chrono::high_resolution_clock::now().time_since_epoch().count(); + this->gen->seed(seed); +} + +void RandomGenerator::Reseed() +{ + gen= new std::minstd_rand0; + this->seed=chrono::high_resolution_clock::now().time_since_epoch().count(); + this->gen->seed(seed); +} + +RandomGenerator::RandomGenerator(unsigned int userSeed) +{ + this->seed=userSeed; + this->gen->seed(seed); +} + +unsigned int RandomGenerator::getRandomInt(){ + unsigned int generatedNumber=gen->operator ()(); + //std::cout<operator ()()%(max+1); +} +float RandomGenerator::getRandomFloat(){ + return ( (getRandomInt()*1.0f) /gen->max()); +} + +void RandomGenerator::randomListUI(void){ + RandomGenerator rg; + unsigned int consoleInput; + cout<<"Combien de nombres pseudo-aleatoires veux tu ?"<>consoleInput; + + std::list l=rg.getListOfRandomInt(consoleInput); + + rg.printListOfRandomInt(l); + } + return; +} +void RandomGenerator::compareSeedsUI(void){ + RandomGenerator* rg; + + for(int i=0;i<20;++i ){ + + rg = new RandomGenerator; + + cout<<" seed : "<getSeed()<getRandomInt() % (41)]++; + } + for(int i=0;i<43;++i){ + cout<seed; +} + +std::list RandomGenerator::getListOfRandomInt(unsigned int n){ + std::list listeRandom; + for(unsigned int i=0; i RandomGenerator::printListOfRandomInt(std::list listeRandom){ + + std::list::const_iterator lit (listeRandom.begin()), lend(listeRandom.end()); + for(;lit!=lend;++lit) { + std::cout << *lit << ' '; + } + std::cout << std::endl; + + return listeRandom; +} diff --git a/pool/shard001/C++/0023298_KeypadTest.cpp b/pool/shard001/C++/0023298_KeypadTest.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c5d0cea32e04a351c10d3eea90fe7a257666a4c7 --- /dev/null +++ b/pool/shard001/C++/0023298_KeypadTest.cpp @@ -0,0 +1,42 @@ +#include "KeypadTest.h" + +KeypadTest::KeypadTest() +{ + CCSize s = CCDirector::sharedDirector()->getWinSize(); + CCLabelTTF* label = CCLabelTTF::create("Keypad Test", "Arial", 28); + addChild(label, 0); + label->setPosition( ccp(s.width/2, s.height-50) ); + + setKeypadEnabled(true); + + // create a label to display the tip string + m_pLabel = CCLabelTTF::create("Please press any key...", "Arial", 22); + m_pLabel->setPosition(ccp(s.width / 2, s.height / 2)); + addChild(m_pLabel, 0); + + m_pLabel->retain(); +} + +KeypadTest::~KeypadTest() +{ + m_pLabel->release(); +} + +void KeypadTest::keyBackClicked() +{ + m_pLabel->setString("BACK clicked!"); +} + +void KeypadTest::keyMenuClicked() +{ + m_pLabel->setString("MENU clicked!"); +} + +void KeypadTestScene::runThisTest() +{ + CCLayer* pLayer = new KeypadTest(); + addChild(pLayer); + + CCDirector::sharedDirector()->replaceScene(this); + pLayer->release(); +} diff --git a/pool/shard001/C++/0023305_status.cc b/pool/shard001/C++/0023305_status.cc new file mode 100644 index 0000000000000000000000000000000000000000..0f02cb57a23b5844a48b7969bdf2def5f9ce9ea4 --- /dev/null +++ b/pool/shard001/C++/0023305_status.cc @@ -0,0 +1,143 @@ +// 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. +// +// A Status encapsulates the result of an operation. It may indicate success, +// or it may indicate an error with an associated error message. +// +// Multiple threads can invoke const methods on a Status without +// external synchronization, but if any of the threads may call a +// non-const method, all threads accessing the same Status must use +// external synchronization. + +#include "arrow/status.h" + +#include +#include +#include +#include + +#include "arrow/util/logging.h" + +namespace arrow { + +Status::Status(StatusCode code, const std::string& msg) + : Status::Status(code, msg, nullptr) {} + +Status::Status(StatusCode code, std::string msg, std::shared_ptr detail) { + ARROW_CHECK_NE(code, StatusCode::OK) << "Cannot construct ok status with message"; + state_ = new State; + state_->code = code; + state_->msg = std::move(msg); + if (detail != nullptr) { + state_->detail = std::move(detail); + } +} + +void Status::CopyFrom(const Status& s) { + delete state_; + if (s.state_ == nullptr) { + state_ = nullptr; + } else { + state_ = new State(*s.state_); + } +} + +std::string Status::CodeAsString() const { + if (state_ == nullptr) { + return "OK"; + } + return CodeAsString(code()); +} + +std::string Status::CodeAsString(StatusCode code) { + const char* type; + switch (code) { + case StatusCode::OK: + type = "OK"; + break; + case StatusCode::OutOfMemory: + type = "Out of memory"; + break; + case StatusCode::KeyError: + type = "Key error"; + break; + case StatusCode::TypeError: + type = "Type error"; + break; + case StatusCode::Invalid: + type = "Invalid"; + break; + case StatusCode::Cancelled: + type = "Cancelled"; + break; + case StatusCode::IOError: + type = "IOError"; + break; + case StatusCode::CapacityError: + type = "Capacity error"; + break; + case StatusCode::IndexError: + type = "Index error"; + break; + case StatusCode::UnknownError: + type = "Unknown error"; + break; + case StatusCode::NotImplemented: + type = "NotImplemented"; + break; + case StatusCode::SerializationError: + type = "Serialization error"; + break; + case StatusCode::CodeGenError: + type = "CodeGenError in Gandiva"; + break; + case StatusCode::ExpressionValidationError: + type = "ExpressionValidationError"; + break; + case StatusCode::ExecutionError: + type = "ExecutionError in Gandiva"; + break; + default: + type = "Unknown"; + break; + } + return std::string(type); +} + +std::string Status::ToString() const { + std::string result(CodeAsString()); + if (state_ == nullptr) { + return result; + } + result += ": "; + result += state_->msg; + if (state_->detail != nullptr) { + result += ". Detail: "; + result += state_->detail->ToString(); + } + + return result; +} + +void Status::Abort() const { Abort(std::string()); } + +void Status::Abort(const std::string& message) const { + std::cerr << "-- Arrow Fatal Error --\n"; + if (!message.empty()) { + std::cerr << message << "\n"; + } + std::cerr << ToString() << std::endl; + std::abort(); +} + +#ifdef ARROW_EXTRA_ERROR_CONTEXT +void Status::AddContextLine(const char* filename, int line, const char* expr) { + ARROW_CHECK(!ok()) << "Cannot add context line to ok status"; + std::stringstream ss; + ss << "\n" << filename << ":" << line << " " << expr; + state_->msg += ss.str(); +} +#endif + +} // namespace arrow diff --git a/pool/shard001/C++/0023312_rtparse.cpp b/pool/shard001/C++/0023312_rtparse.cpp new file mode 100644 index 0000000000000000000000000000000000000000..06eaff028c73c7c1f948779882374999b47766e0 --- /dev/null +++ b/pool/shard001/C++/0023312_rtparse.cpp @@ -0,0 +1,94 @@ +/**************************************************************************** +** rtparse.cpp - class for manipulating richtext +** Copyright (C) 2001, 2002 Justin Karneges +** +** 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 "rtparse.h" +#include "textutil.h" + +#include // for Qt::escape() + +RTParse::RTParse(const QString &_in) +{ + in = _in; + v_atEnd = in.length() == 0; + v_at = 0; + //printf("rtparse:\n"); +} + +const QString &RTParse::output() const +{ + //printf("final: [%s]\n", out.latin1()); + return out; +} + +QString RTParse::next() +{ + if(v_atEnd) + return ""; + + // if we're at a tag, append it to the output + if(in.at(v_at) == '<') { + QString s; + int n = in.indexOf('>', v_at); + if(n == -1) { + s = in.mid(v_at); + } + else { + ++n; + s = in.mid(v_at, n-v_at); + } + v_at += s.length(); + out += s; + } + + // now find the next tag, and grab the text in between + QString s; + int x = in.indexOf('<', v_at); + if(x == -1) { + s = in.mid(v_at); + v_atEnd = true; + } + else { + s = in.mid(v_at, x-v_at); + } + v_at += s.length(); + //printf("chunk = '%s'\n", s.latin1()); + s = TextUtil::resolveEntities(s); + //printf("resolved = '%s'\n", s.latin1()); + return s; +} + +bool RTParse::atEnd() const +{ + return v_atEnd; +} + +void RTParse::putPlain(const QString &s) +{ + //printf("got this: [%s]\n", s.latin1()); + out += TextUtil::escape(s); + //printf("changed to this: [%s]\n", expandEntities(s).latin1()); +} + +void RTParse::putRich(const QString &s) +{ + out += s; + //printf("+ '%s'\n", s.latin1()); +} + diff --git a/pool/shard001/C++/0023313_Plugin.cpp b/pool/shard001/C++/0023313_Plugin.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a2ab4d9c45463410c6be9e9beb92eb07c88fd9ec --- /dev/null +++ b/pool/shard001/C++/0023313_Plugin.cpp @@ -0,0 +1,268 @@ +/* ************************************************************************ */ +/* Georgiev Lab (c) 2015-2016 */ +/* ************************************************************************ */ +/* Department of Cybernetics */ +/* Faculty of Applied Sciences */ +/* University of West Bohemia in Pilsen */ +/* ************************************************************************ */ +/* */ +/* This file is part of CeCe. */ +/* */ +/* CeCe 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. */ +/* */ +/* CeCe 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 CeCe. If not, see . */ +/* */ +/* ************************************************************************ */ + +// C++ +#include +#include + +// CeCe +#include "cece/config.hpp" +#include "cece/core/DynamicArray.hpp" +#include "cece/core/StaticArray.hpp" +#include "cece/core/Log.hpp" +#include "cece/core/UnitIo.hpp" +#include "cece/core/Shape.hpp" +#include "cece/plugin/definition.hpp" +#include "cece/plugin/Api.hpp" +#include "cece/config/Configuration.hpp" +#include "cece/object/Object.hpp" +#include "cece/simulator/Simulation.hpp" + +#ifdef CECE_RENDER +# include "cece/render/Color.hpp" +#endif + +// NanoSVG +#define NANOSVG_IMPLEMENTATION // Expands implementation +#include "nanosvg/nanosvg.h" + +/* ************************************************************************ */ + +using namespace cece; + +/* ************************************************************************ */ + +namespace { + +/* ************************************************************************ */ + +/** + * @brief Calculate distance of point segment. + * + * @param v + * @param pv + * @param pq + * + * @return + */ +float distPtSegSq(Vector v, Vector vp, Vector vq) +{ + const auto vpq = vq - vp; + const auto dist = vpq.getLengthSquared(); + auto dv = v - vp; + auto t = vpq.dot(dv); + + if (dist > 0) + t /= dist; + + if (t < 0) + t = 0; + else if (t > 1) + t = 1; + + dv = vp + t * vpq - v; + + return dv.getLengthSquared(); +} + +/* ************************************************************************ */ + +/** + * @brief Store cubic bezier curve. + * + * @param out + * @parma + */ +template +void cubicBezier(Fn store, StaticArray, 4> vs, float tol, int level = 0) +{ + // Limit recursion + if (level > 12) + return; + + Log::debug("0: ", vs[0].getX(), "; ", vs[0].getY()); + Log::debug("1: ", vs[1].getX(), "; ", vs[1].getY()); + Log::debug("2: ", vs[2].getX(), "; ", vs[2].getY()); + Log::debug("3: ", vs[3].getX(), "; ", vs[3].getY()); + + const auto v0 = vs[0]; + const auto v1 = vs[1]; + const auto v2 = vs[2]; + const auto v3 = vs[3]; + const auto v01 = (v0 + v1) * 0.5f; + const auto v12 = (v1 + v2) * 0.5f; + const auto v23 = (v2 + v3) * 0.5f; + const auto v012 = (v01 + v12) * 0.5f; + const auto v123 = (v12 + v23) * 0.5f; + const auto v0123 = (v012 + v123) * 0.5f; + + auto dSq = distPtSegSq(v0123, v0, v3); + + if (dSq > tol * tol) + { + cubicBezier(store, {v0, v01, v012, v0123}, tol, level + 1); + cubicBezier(store, {v0123, v123, v23, v3}, tol, level + 1); + } + else + { + store(vs[3]); + } +} + +/* ************************************************************************ */ + +/** + * @brief Store path to vertices. + * + * @param out + * @param npts + * @param closed + * @param tol + */ +template +void storePath(Fn store, NSVGpath* path, float tol) +{ + // Store first vector + //store(Vector{path->pts[0], path->pts[1]}); + + for (int i = 0; i < path->npts - 1; i += 3) + { + float* p = &(path->pts[i * 2]); + cubicBezier(store, { + Vector{p[0], p[1]}, + Vector{p[2], p[3]}, + Vector{p[4], p[5]}, + Vector{p[6], p[7]} + }, tol, 0); + } + + // Store closing vector + //if (path->closed) + // store(Vector{path->pts[0], path->pts[1]}); +} + +/* ************************************************************************ */ + +} + +/* ************************************************************************ */ + +class ObstaclesSvgApi : public plugin::Api +{ + + /** + * @brief Returns a list of required plugins. + * + * @return + */ + DynamicArray requiredPlugins() const override + { + return {"obstacle"}; + } + + + /** + * @brief Load plugin configuration. + * + * @param simulation Current simulation. + * @param config Plugin configuration. + */ + void loadConfig(simulator::Simulation& simulation, const config::Configuration& config) const override + { + const float px = 0.3f; + const auto file = simulation.getResource(config.get("filename")); + + if (!file) + throw RuntimeException("SVG file not found"); + + DynamicArray content; + content.reserve(2048); + + *file >> std::noskipws; + std::copy(std::istream_iterator(*file), std::istream_iterator(), + std::back_inserter(content)); + + // SVG image + NSVGimage* image = nsvgParse(content.data(), "px", 96); + + if (!image) + throw RuntimeException("Cannot parse SVG"); + + auto obstacle = simulation.createObject("obstacle.Polygon", object::Object::Type::Static); + auto& shapes = obstacle->getMutableShapes(); + +#ifdef CECE_RENDER + obstacle->setColor(config.get("color", obstacle->getColor())); +#endif + + const auto size = Vector(image->width, image->height); + + // Coordinate scale + const auto scale = simulation.getWorldSize() / size; + const auto offset = size * 0.5; + + // Foreach shapes + for (NSVGshape* shape = image->shapes; shape != nullptr; shape = shape->next) + { + ShapeEdges oShape; + + // Foreach paths + for (NSVGpath* path = shape->paths; path != nullptr; path = path->next) + { + storePath([&oShape, &offset, &scale] (Vector vec) { + const auto v = (vec - offset) * scale * Vector(1, -1); + if (oShape.edges.empty() || + oShape.edges.back().distanceSquared(v).value() > 0.05) + { + oShape.edges.push_back(v); + Log::debug(v.getX(), "; ", v.getY()); + } + }, path, px * 1.5); + } + + shapes.push_back(std::move(oShape)); + } + + obstacle->initShapes(); + } + + + /** + * @brief Store plugin configuration. + * + * @param simulation Current simulation. + * @param config Plugin configuration. + */ + void storeConfig(const simulator::Simulation& simulation, config::Configuration& config) const override + { + // TODO: implement + } +}; + +/* ************************************************************************ */ + +CECE_DEFINE_PLUGIN(obstacles_svg, ObstaclesSvgApi) + +/* ************************************************************************ */ diff --git a/pool/shard001/C++/0023314_VarioSynthesiser.cpp b/pool/shard001/C++/0023314_VarioSynthesiser.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7b4d63a475e95f9a696c8e078c1b42f0abaee72f --- /dev/null +++ b/pool/shard001/C++/0023314_VarioSynthesiser.cpp @@ -0,0 +1,160 @@ +/* +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 "VarioSynthesiser.hpp" +#include "Math/FastMath.h" +#include "Util/Clamp.hpp" + +#include + +/** + * The minimum and maximum vario range for the constants below [cm/s]. + */ +static constexpr int min_vario = -500, max_vario = 500; + +unsigned +VarioSynthesiser::VarioToFrequency(int ivario) +{ + return ivario > 0 + ? (zero_frequency + (unsigned)ivario * (max_frequency - zero_frequency) + / (unsigned)max_vario) + : (zero_frequency - (unsigned)(ivario * (int)(zero_frequency - min_frequency) / min_vario)); +} + +void +VarioSynthesiser::SetVario(unsigned sample_rate, fixed vario) +{ + const ScopeLock protect(mutex); + + const int ivario = Clamp((int)(vario * 100), min_vario, max_vario); + + if (dead_band_enabled && InDeadBand(ivario)) { + /* inside the "dead band" */ + UnsafeSetSilence(); + return; + } + + /* update the ToneSynthesiser base class */ + SetTone(sample_rate, VarioToFrequency(ivario)); + + if (ivario > 0) { + /* while climbing, the vario sound gets interrupted by silence + periodically */ + + const unsigned period_ms = sample_rate + * (min_period_ms + (max_vario - ivario) + * (max_period_ms - min_period_ms) / max_vario) + / 1000; + + silence_count = period_ms / 3; + audible_count = period_ms - silence_count; + + /* preserve the old "_remaining" values as much as possible, to + avoid chopping off the previous tone */ + + if (audible_remaining > audible_count) + audible_remaining = audible_count; + + if (silence_remaining > silence_count) + silence_remaining = silence_count; + } else { + /* continuous tone while sinking */ + audible_count = 1; + silence_count = 0; + } +} + +void +VarioSynthesiser::SetSilence() +{ + const ScopeLock protect(mutex); + UnsafeSetSilence(); +} + +void +VarioSynthesiser::UnsafeSetSilence() +{ + audible_count = 0; + silence_count = 1; + + if (audible_remaining > 0) + /* quit the current period as early as possible; the method + Synthesise() will take care for finishing the current sine + wave to avoid clicking noise */ + audible_remaining = 1; + + silence_remaining = 0; +} + + +void +VarioSynthesiser::Synthesise(int16_t *buffer, size_t n) +{ + const ScopeLock protect(mutex); + + assert(audible_count > 0 || silence_count > 0); + + if (silence_count == 0) { + /* magic value for "continuous tone" */ + ToneSynthesiser::Synthesise(buffer, n); + return; + } + + while (n > 0) { + if (audible_remaining > 0) { + /* generate a period of audible tone */ + + unsigned o = silence_count > 0 + ? std::min(n, audible_remaining) + : n; + ToneSynthesiser::Synthesise(buffer, o); + buffer += o; + n -= o; + audible_remaining -= o; + + if (audible_remaining == 0 && silence_remaining > 0) { + /* finish the current sine wave to avoid clicking noise */ + audible_remaining = ToZero(); + if (audible_remaining == 0) + /* finished, we can now emit a period of silence */ + Restart(); + } + } else if (silence_remaining > 0) { + /* generate a period of silence (climbing) */ + + unsigned o = audible_count > 0 + ? std::min(n, silence_remaining) + : n; + /* the "silence" PCM sample value is zero */ + std::fill_n(buffer, o, 0); + buffer += o; + n -= o; + silence_remaining -= o; + } else { + /* period finished, begin next one */ + + audible_remaining = audible_count; + silence_remaining = silence_count; + } + } +} diff --git a/pool/shard001/C++/0023318_buildsterbot.cpp b/pool/shard001/C++/0023318_buildsterbot.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f8b1e0a48b7e9cc24c5efa909b940c80e3f9a58e --- /dev/null +++ b/pool/shard001/C++/0023318_buildsterbot.cpp @@ -0,0 +1,91 @@ +/* + buildsterbot library + copyright Christopher Walter James Palmer 2015 +*/ + +#include "Arduino.h" +#include "Buildsterbot.h" +#include + + +void DigitalInput::setup(int pin, bool stateThatMeansIsOn){ + pinMode(pin, INPUT); + _pin = pin; + _stateThatMeansIsOn = stateThatMeansIsOn; +} +bool DigitalInput::isOn(){ + if ( _stateThatMeansIsOn == HIGH) { + return digitalRead(_pin); + } else { + return ! digitalRead(_pin); + } +} +bool DigitalInput::isOff(){ + return ! isOn(); +} + +void DigitalOutput::setup(int pin) { + _pin = pin; + pinMode(_pin, OUTPUT); +} +void DigitalOutput::turnOn() { + digitalWrite(_pin, HIGH); + _stateIsOn = true; +} +void DigitalOutput::turnOff() { + digitalWrite(_pin, LOW); + _stateIsOn = false; +} +bool DigitalOutput::isOn() { + return _stateIsOn; +} +bool DigitalOutput::isOff() { + return ! _stateIsOn; +} + +void AnalogInput::setup(int pin) { + pinMode(pin,INPUT); + _pin = pin; +} +int AnalogInput::reading() { + // _value = 0; + // // take 5 readings + // for (int i; i < 5; i++) { + // _value = _value + analogRead(_pin); + // delay(2); + // } + // _value = (float)l_value / (float)l5; // THIS IS THE PROBLEM + // // return average reading + // return _value; + // return analogRead(_pin); + return analogRead(_pin); +} + +void AnalogOutput::setup(int pin) { + _pin = pin; + pinMode(_pin,OUTPUT); +} +void AnalogOutput::set(int newSetting) { + analogWrite(_pin, newSetting); + _currentSetting = newSetting; +} +int AnalogOutput::setting() { + return _currentSetting; +} + +void SERVO::setup(int pin) { + _pin = pin; + _servo.attach(_pin); + setPosition(0); +} +void SERVO::setPosition(int position){ + if ( position > 180 ) { + _positionSetting = 180; + } else { + _positionSetting = position; + } + _servo.write(_positionSetting); +} +int SERVO::currentPosition(){ + return _positionSetting; +} diff --git a/pool/shard001/C++/0023330_parse_amount.cpp b/pool/shard001/C++/0023330_parse_amount.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7d0b64088009112e2a1904b9f3e08b6164c7467b --- /dev/null +++ b/pool/shard001/C++/0023330_parse_amount.cpp @@ -0,0 +1,124 @@ +// Copyright (c) 2012-2013 The Cryptonote developers +// Distributed under the MIT/X11 software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include "gtest/gtest.h" + +#include "cryptonote_core/cryptonote_format_utils.h" + +using namespace cryptonote; + +namespace +{ + void do_pos_test(uint64_t expected, const std::string& str) + { + uint64_t val; + std::string number_str = str; + std::replace(number_str.begin(), number_str.end(), '_', '.'); + number_str.erase(std::remove(number_str.begin(), number_str.end(), '~'), number_str.end()); + ASSERT_TRUE(parse_amount(val, number_str)); + ASSERT_EQ(expected, val); + } + + void do_neg_test(const std::string& str) + { + uint64_t val; + std::string number_str = str; + std::replace(number_str.begin(), number_str.end(), '_', '.'); + number_str.erase(std::remove(number_str.begin(), number_str.end(), '~'), number_str.end()); + ASSERT_FALSE(parse_amount(val, number_str)); + } +} + +#define TEST_pos(expected, str) \ + TEST(parse_amount, handles_pos_ ## str) \ + { \ + do_pos_test(UINT64_C(expected), #str); \ + } + +#define TEST_neg(str) \ + TEST(parse_amount, handles_neg_ ## str) \ + { \ + do_neg_test(#str); \ + } + +#define TEST_neg_n(str, name) \ + TEST(parse_amount, handles_neg_ ## name) \ + { \ + do_neg_test(#str); \ + } + + +TEST_pos(0, 0); +TEST_pos(0, 00); +TEST_pos(0, 00000000); +TEST_pos(0, 000000000); +TEST_pos(0, 00000000000000000000000000000000); + +TEST_pos(0, _0); +TEST_pos(0, _00); +TEST_pos(0, _00000000); +TEST_pos(0, _000000000); +TEST_pos(0, _00000000000000000000000000000000); + +TEST_pos(0, 00000000_); +TEST_pos(0, 000000000_); +TEST_pos(0, 00000000000000000000000000000000_); + +TEST_pos(0, 0_); +TEST_pos(0, 0_0); +TEST_pos(0, 0_00); +TEST_pos(0, 0_00000000); +TEST_pos(0, 0_000000000); +TEST_pos(0, 0_00000000000000000000000000000000); + +TEST_pos(0, 00_); +TEST_pos(0, 00_0); +TEST_pos(0, 00_00); +TEST_pos(0, 00_00000000); +TEST_pos(0, 00_000000000); +TEST_pos(0, 00_00000000000000000000000000000000); + +TEST_pos(1, 0_00000001); +TEST_pos(1, 0_000000010); +TEST_pos(1, 0_000000010000000000000000000000000); +TEST_pos(9, 0_00000009); +TEST_pos(9, 0_000000090); +TEST_pos(9, 0_000000090000000000000000000000000); + +TEST_pos( 100000000, 1); +TEST_pos( 6553500000000, 65535); +TEST_pos( 429496729500000000, 4294967295); +TEST_pos(18446744073700000000, 184467440737_); +TEST_pos(18446744073700000000, 184467440737_0); +TEST_pos(18446744073700000000, 184467440737_00000000); +TEST_pos(18446744073700000000, 184467440737_000000000); +TEST_pos(18446744073700000000, 184467440737_0000000000000000000); +TEST_pos(18446744073709551615, 184467440737_09551615); + +// Invalid numbers +TEST_neg_n(~, empty_string); +TEST_neg_n(-0, minus_0); +TEST_neg_n(+0, plus_0); +TEST_neg_n(-1, minus_1); +TEST_neg_n(+1, plus_1); +TEST_neg_n(_, only_point); + +// A lot of fraction digits +TEST_neg(0_000000001); +TEST_neg(0_000000009); +TEST_neg(184467440737_000000001); + +// Overflow +TEST_neg(184467440737_09551616); +TEST_neg(184467440738); +TEST_neg(18446744073709551616); + +// Two or more points +TEST_neg(__); +TEST_neg(0__); +TEST_neg(__0); +TEST_neg(0__0); +TEST_neg(0_0_); +TEST_neg(_0_0); +TEST_neg(0_0_0); diff --git a/pool/shard001/C++/0023333_hugoScanRead.cpp b/pool/shard001/C++/0023333_hugoScanRead.cpp new file mode 100644 index 0000000000000000000000000000000000000000..69f36ff1ee1da422967a1ebf476efb83b665a330 --- /dev/null +++ b/pool/shard001/C++/0023333_hugoScanRead.cpp @@ -0,0 +1,132 @@ +/* + Copyright (c) 2003, 2016, 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 + +#include + +#include +#include +#include +#include + +#include + +int main(int argc, const char** argv){ + ndb_init(); + + int _records = 0; + int _loops = 1; + int _abort = 0; + int _parallelism = 1; + const char* _tabname = NULL, *db = 0; + int _help = 0; + int lock = NdbOperation::LM_Read; + int sorted = 0; + + struct getargs args[] = { + { "aborts", 'a', arg_integer, &_abort, "percent of transactions that are aborted", "abort%" }, + { "loops", 'l', arg_integer, &_loops, "number of times to run this program(0=infinite loop)", "loops" }, + { "parallelism", 'p', arg_integer, &_parallelism, "parallelism(1-240)", "para" }, + { "records", 'r', arg_integer, &_records, "Number of records", "recs" }, + { "usage", '?', arg_flag, &_help, "Print help", "" }, + { "lock", 'm', arg_integer, &lock, "lock mode", "" }, + { "sorted", 's', arg_flag, &sorted, "sorted", "" }, + { "database", 'd', arg_string, &db, "Database", "" } + }; + int num_args = sizeof(args) / sizeof(args[0]); + int optind = 0; + char desc[] = + " tabname\n"\ + "This program will scan read all records in one table in Ndb.\n"\ + "It will verify every column read by calculating the expected value.\n"; + + if(getarg(args, num_args, argc, argv, &optind) || argv[optind] == NULL || _help) { + arg_printusage(args, num_args, argv[0], desc); + return NDBT_ProgramExit(NDBT_WRONGARGS); + } + _tabname = argv[optind]; + + // Connect to Ndb + Ndb_cluster_connection con; + if(con.connect(12, 5, 1) != 0) + { + return NDBT_ProgramExit(NDBT_FAILED); + } + Ndb MyNdb( &con, db ? db : "TEST_DB" ); + + if(MyNdb.init() != 0){ + NDB_ERR(MyNdb.getNdbError()); + return NDBT_ProgramExit(NDBT_FAILED); + } + + while(MyNdb.waitUntilReady() != 0) + ndbout << "Waiting for ndb to become ready..." << endl; + + // Check if table exists in db + const NdbDictionary::Table * pTab = NDBT_Table::discoverTableFromDb(&MyNdb, _tabname); + if(pTab == NULL){ + ndbout << " Table " << _tabname << " does not exist!" << endl; + return NDBT_ProgramExit(NDBT_WRONGARGS); + } + + const NdbDictionary::Index * pIdx = 0; + if(optind+1 < argc) + { + pIdx = MyNdb.getDictionary()->getIndex(argv[optind+1], _tabname); + if(!pIdx) + ndbout << " Index " << argv[optind+1] << " not found" << endl; + else + if(pIdx->getType() != NdbDictionary::Index::OrderedIndex) + { + ndbout << " Index " << argv[optind+1] << " is not scannable" << endl; + pIdx = 0; + } + } + + HugoTransactions hugoTrans(*pTab); + int i = 0; + while (i<_loops || _loops==0) { + ndbout << i << ": "; + if(!pIdx) + { + if(hugoTrans.scanReadRecords(&MyNdb, + 0, + _abort, + _parallelism, + (NdbOperation::LockMode)lock) != 0) + { + return NDBT_ProgramExit(NDBT_FAILED); + } + } + else + { + if(hugoTrans.scanReadRecords(&MyNdb, pIdx, + 0, + _abort, + _parallelism, + (NdbOperation::LockMode)lock, + sorted) != 0) + { + return NDBT_ProgramExit(NDBT_FAILED); + } + } + i++; + } + + return NDBT_ProgramExit(NDBT_OK); +} diff --git a/pool/shard001/C++/0023337_AbstractReport.cpp b/pool/shard001/C++/0023337_AbstractReport.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4b7159031f78f3eda2962a3a0100f1637d7907c2 --- /dev/null +++ b/pool/shard001/C++/0023337_AbstractReport.cpp @@ -0,0 +1,335 @@ +/* + * This is QTournament, a badminton tournament management program. + * Copyright (C) 2014 - 2019 Volker Knollmann + * + * 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 + +#include +#include + +#include "AbstractReport.h" +#include "HelperFunc.h" + +using namespace SimpleReportLib; +using namespace QTournament; + +namespace QTournament +{ + + constexpr char AbstractReport::HeadlineStyle[]; + constexpr char AbstractReport::SubheadStyle[]; + constexpr char AbstractReport::IntermediateHeadlineStyle[]; + constexpr char AbstractReport::ResultsheetNameStyle[]; + constexpr char AbstractReport::ResultsheetTeamStyle[]; + constexpr char AbstractReport::ResultsheetGamelabelStyle[]; + constexpr char AbstractReport::BoldStyle[]; + +AbstractReport::AbstractReport(const TournamentDB& _db, const QString& _name) + :db(_db), name(_name), cfg(SqliteOverlay::KeyValueTab{db, TabCfg}) +{ + if (name.isEmpty() || (name == "")) + { + throw std::runtime_error("Got empty name for report"); + } +} + +//---------------------------------------------------------------------------- + +AbstractReport::~AbstractReport() +{ + +} + +//---------------------------------------------------------------------------- + +upSimpleReport AbstractReport::createEmptyReport_Portrait() const +{ + SimpleReportLib::SimpleReportGenerator* rawResult = new SimpleReportLib::SimpleReportGenerator( + WidthA4_mm, HeightA4_mm, DefaultMargin_mm); + rawResult->startNextPage(); + + upSimpleReport result = upSimpleReport(rawResult); + prepStyles(result); + + return result; +} + +//---------------------------------------------------------------------------- + +upSimpleReport AbstractReport::createEmptyReport_Landscape() const +{ + SimpleReportLib::SimpleReportGenerator* rawResult = new SimpleReportLib::SimpleReportGenerator( + HeightA4_mm, WidthA4_mm, DefaultMargin_mm); + rawResult->startNextPage(); + + upSimpleReport result = upSimpleReport(rawResult); + prepStyles(result); + + return result; +} + +//---------------------------------------------------------------------------- + +QString AbstractReport::getName() const +{ + return name; +} + +//---------------------------------------------------------------------------- + +void AbstractReport::setHeaderAndHeadline(SimpleReportLib::SimpleReportGenerator* rep, const QString& headline, const QString& subHead) const +{ + SimpleReportLib::TabSet ts; + ts.addTab(WidthA4_mm / 2.0 - DefaultMargin_mm, SimpleReportLib::TAB_JUSTIFICATION::TAB_CENTER); + rep->pushTabs(ts); + rep->writeLine("\t" + headline, HeadlineStyle, 0.0, BeforeHeadlineSkip_mm); + if (subHead.length() > 0) + { + rep->skip(HeadSubheadSkip_mm); + rep->writeLine("\t" + subHead, SubheadStyle); + } + rep->popTabs(); + rep->skip(AfterHeadlineSkip_mm); +} + +//---------------------------------------------------------------------------- + +void AbstractReport::prepStyles(upSimpleReport& rep) const +{ + // basic font: 2 mm Arial + auto style = rep->getTextStyle(); + style->setFontname(QLatin1Literal("Arial")); + style->setFontSize_MM(2.0); + + // bold font + style = rep->createChildTextStyle(BoldStyle); + style->setBoldState(true); + + // headlines: 4 mm, bold + style = rep->createChildTextStyle(HeadlineStyle); + style->setFontSize_MM(4.0); + style->setBoldState(true); + + // sub-heaadline: 2,5 mm, italic + style = rep->createChildTextStyle(SubheadStyle); + style->setFontSize_MM(2.5); + style->setItalicsState(true); + + // intermediate headine: 3,5 mm, not bold + style = rep->createChildTextStyle(IntermediateHeadlineStyle); + style->setFontSize_MM(3.5); + + // player names in result sheets: 3 mm, bold + style = rep->createChildTextStyle(ResultsheetNameStyle); + style->setFontSize_MM(2.9); + style->setBoldState(true); + + // team names in result sheets: 2 mm, italic + style = rep->createChildTextStyle(ResultsheetTeamStyle); + style->setFontSize_MM(2.0); + style->setItalicsState(true); + + // "Game xx:"-labels in result sheets: 2,5 mm, bold + style = rep->createChildTextStyle(ResultsheetGamelabelStyle); + style->setFontSize_MM(2.5); + style->setBoldState(true); +} + +//---------------------------------------------------------------------------- + +void AbstractReport::printIntermediateHeader(upSimpleReport& rep, const QString& txt, double skipBefore__MM) const +{ + if (skipBefore__MM < 0) skipBefore__MM = 0.0; + + // check for sufficient space + if (!(rep->hasSpaceForAnotherLine(IntermediateHeadlineStyle, skipBefore__MM + SkipAfterIntermediateHeader_mm))) + { + rep->startNextPage(); + } + if (skipBefore__MM > 0) rep->skip(skipBefore__MM); + rep->writeLine(txt, IntermediateHeadlineStyle); + rep->addHorLine(); + rep->skip(SkipAfterIntermediateHeader_mm); +} + +//---------------------------------------------------------------------------- + +void AbstractReport::printMatchList(upSimpleReport& rep, const MatchList& maList, const PlayerPairList& byeList, const QString& continuationString, bool withResults, bool withGroupColumn) const +{ + // prepare a tabset for a table with match results + SimpleReportLib::TabSet ts; + ts.addTab(9.5, SimpleReportLib::TAB_JUSTIFICATION::TAB_RIGHT); // the match number + ts.addTab(13.0, SimpleReportLib::TAB_JUSTIFICATION::TAB_LEFT); // the players + ts.addTab(135.0, SimpleReportLib::TAB_JUSTIFICATION::TAB_CENTER); // the group number + ts.addTab(145, SimpleReportLib::TAB_JUSTIFICATION::TAB_LEFT); // dummy tab for a column label + for (int game=0; game < 5; ++game) + { + double colonPos = 150 + game*12.0; + ts.addTab(colonPos - 1.0, SimpleReportLib::TAB_JUSTIFICATION::TAB_RIGHT); // first score + ts.addTab(colonPos, SimpleReportLib::TAB_JUSTIFICATION::TAB_CENTER); // colon + ts.addTab(colonPos + 1.0, SimpleReportLib::TAB_JUSTIFICATION::TAB_LEFT); // second score + } + + // prepare a table for the match results + SimpleReportLib::TableWriter tw(ts); + tw.setHeader(1, QObject::tr("Match")); + tw.setHeader(2, QObject::tr("Players")); + if (withResults) + { + tw.setHeader(4, QObject::tr("Game results")); + } + + // print the results of all matches + bool usesRoundRobinGroups = false; + for (Match ma : maList) + { + int grpNum = ma.getMatchGroup().getGroupNumber(); + if (grpNum > 0) + { + usesRoundRobinGroups = true; + } + + QStringList rowContent; + rowContent << ""; // first column not used + rowContent << QString::number(ma.getMatchNumber()); + + QString pNames; + if (ma.hasPlayerPair1()) + { + pNames = ma.getPlayerPair1().getDisplayName(); + } else { + // the match is not yet complete + // and thus can't be displayed in the report + continue; + } + + pNames += " : "; + + if (ma.hasPlayerPair2()) + { + pNames += ma.getPlayerPair2().getDisplayName(); + } else { + // the match is not yet complete + // and thus can't be displayed in the report + continue; + } + + rowContent << pNames; + + if (withGroupColumn && (grpNum > 0)) + { + rowContent << QString::number(grpNum); + } else { + rowContent << ""; + } + + rowContent << ""; // a dummy tab for the "Game results" label + + if (withResults) + { + auto ms = ma.getScore(); + if (!ms) continue; + for (int i=0; i < ms->getNumGames(); ++i) + { + auto gs = ms->getGame(i); + assert(gs); + + std::tuple sc = gs->getScore(); + rowContent << QString::number(get<0>(sc)); + rowContent << ":"; + rowContent << QString::number(get<1>(sc)); + } + + // if this was a walkover, add a note in + // the unused space for the 3rd game + if (ma.isWonByWalkover()) + { + rowContent << ""; + rowContent << QObject::tr("(walkover)"); + } + } + + tw.appendRow(rowContent); + } + + // if used we round robins, add a column header for the group number + if (usesRoundRobinGroups && withGroupColumn) + { + tw.setHeader(3, QObject::tr("Group")); + } + + // if we have players with a bye, list those players at the bottom of the table + if (!(byeList.empty())) + { + // sort the list alphabetically (and not, e.g., by group) + // + // we need to do this on a copy of byeList, because byeList is const + // and making it non-const would cause trouble when calling this function + // with an empty list like "PlayerPairList()". + PlayerPairList _byeList{byeList}; + std::sort(_byeList.begin(), _byeList.end(), [](PlayerPair& pp1, PlayerPair& pp2) + { + return pp1.getDisplayName() < pp2.getDisplayName(); + }); + + // print two empty rows as delimiter + QStringList rowContent; + rowContent << ""; + tw.appendRow(rowContent); + tw.appendRow(rowContent); + + // a list of all players having a bye + for (PlayerPair pp : _byeList) + { + rowContent.clear(); + rowContent << ""; // first column not used + rowContent << "---"; // indicates: no match / no match number ==> bye + + rowContent << pp.getDisplayName(); + tw.appendRow(rowContent); + } + } + + tw.setNextPageContinuationCaption(continuationString); + tw.write(rep.get()); +} + +//---------------------------------------------------------------------------- + +void AbstractReport::setHeaderAndFooter(upSimpleReport& rep, const QString& reportName) +{ + QString tName = stdString2QString(cfg[CfgKey_TnmtName]); + QString cName = stdString2QString(cfg[CfgKey_TnmtOrga]); + rep->setGlobalHeader(cName, tName, SimpleReportLib::HeaderFooterStrings::TOKEN_CURDATE); + + QString fl = SimpleReportLib::HeaderFooterStrings::TOKEN_CURTIME; + + QString fr = SimpleReportLib::HeaderFooterStrings::TOKEN_CURPGNUM; + fr += " / "; + fr += SimpleReportLib::HeaderFooterStrings::TOKEN_TOTALPGNUM; + rep->setGlobalFooter(fl , reportName, fr); + + rep->applyHeaderAndFooterOnAllPages(); +} + +//---------------------------------------------------------------------------- + + +//---------------------------------------------------------------------------- + + +} diff --git a/pool/shard001/C++/0023338_ReadList.cpp b/pool/shard001/C++/0023338_ReadList.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a173b936f81787cacd9c51950544600e0429a55 --- /dev/null +++ b/pool/shard001/C++/0023338_ReadList.cpp @@ -0,0 +1,57 @@ +/************************************************************************************************ +* Author : Suraj Singh * +* E-mail : suraj.cse.ism@gmail.com * +* OS : Windows 7 Ultimate (64-bit) * +* Tools Used : Code::Blocks 13.12 with built-in g++ complier * +* * * * * * * * * * * * * * * * * * * * * * * * * +* Description : It reads the list of name of Files to be analysed and stores those * +* names into 2D character matrix name : "nameList" * +* * * * * * * * * * * * * * * * * * * * * * * * * +* Note : nameList is defined in this File * +************************************************************************************************/ + + +/* Default Header Files Included */ +#include +#include +#include /* Used to open directory and read files in it */ +#include +#include +#include + + +/* Customized Header Files Included */ +#include "Header.h" + + +/* Global Data Type */ +char nameList[LIMIT_OF_FILES][LENGTH_OF_NAME] = {0}; /* It holds the list of name of the files */ + + +using namespace std; + + +unsigned int readList(char *workingDir) { + + /* Read number of files in the folder */ + DIR *dir; struct dirent *file; unsigned int countFiles = 0; + if ((dir=opendir(workingDir)) != NULL) { + while ((file=readdir(dir)) != NULL && countFiles < LIMIT_OF_FILES) { + if(strcmp(file->d_name,".") == 0 || strcmp(file->d_name,"..") == 0) { + /* Do nothing */ + } else { + //cout<d_name<d_name); + countFiles++; + } + } + + if(countFiles <= 1) { + countFiles = 0; + } + closedir (dir); + } else { + cout<<"Unable to locate the directory : "< + * 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 + */ + +/* ScriptData +SDName: Dun_Morogh +SD%Complete: 50 +SDComment: Quest support: 1783 +SDCategory: Dun Morogh +EndScriptData */ + +/* ContentData +npc_narm_faulk +EndContentData */ + +#include "precompiled.h" + +/*###### +## npc_narm_faulk +######*/ + +#define SAY_HEAL -1000187 + +struct MANGOS_DLL_DECL npc_narm_faulkAI : public ScriptedAI +{ + uint32 lifeTimer; + bool spellHit; + + npc_narm_faulkAI(Creature* pCreature) : ScriptedAI(pCreature) {Reset();} + + void Reset() + { + lifeTimer = 120000; + m_creature->SetUInt32Value(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_DEAD); + m_creature->SetStandState(UNIT_STAND_STATE_DEAD); + spellHit = false; + } + + void MoveInLineOfSight(Unit *who) { } + + void UpdateAI(const uint32 diff) + { + if (m_creature->IsStandState()) + { + if (lifeTimer < diff) + m_creature->AI()->EnterEvadeMode(); + else + lifeTimer -= diff; + } + } + + void SpellHit(Unit *Hitter, const SpellEntry *Spellkind) + { + if (Spellkind->Id == 8593 && !spellHit) + { + DoCastSpellIfCan(m_creature,32343); + m_creature->SetStandState(UNIT_STAND_STATE_STAND); + m_creature->SetUInt32Value(UNIT_DYNAMIC_FLAGS, 0); + //m_creature->RemoveAllAuras(); + DoScriptText(SAY_HEAL, m_creature, Hitter); + spellHit = true; + } + } + +}; +CreatureAI* GetAI_npc_narm_faulk(Creature* pCreature) +{ + return new npc_narm_faulkAI(pCreature); +} + +void AddSC_dun_morogh() +{ + Script *newscript; + + newscript = new Script; + newscript->Name = "npc_narm_faulk"; + newscript->GetAI = &GetAI_npc_narm_faulk; + newscript->RegisterSelf(); +} diff --git a/pool/shard001/C++/0023356_GridDlg.cpp b/pool/shard001/C++/0023356_GridDlg.cpp new file mode 100644 index 0000000000000000000000000000000000000000..954b807983285ecd1a9307a56a88f211ca1337b9 --- /dev/null +++ b/pool/shard001/C++/0023356_GridDlg.cpp @@ -0,0 +1,72 @@ +/*************** + * MODULE: griddlg.cpp + * PROJECT: Scenario + * VERSION: 1.0 10.12.1996 + * DESCRIPTION: gridsize dialog + * AUTHORS: Mike Hesser + * HISTORY: DATE NAME COMMENT + * 07.09.1996 mh comment + ***************/ + +#include "typedefs.h" +#include "GridDlg.h" +#include "CamView.h" + +/************* + * DESCRIPTION: set & call grid size dialog + * INPUT: - + * OUTPUT: - + *************/ +void CCamView::OnGridsize() +{ + CGridsize dialog; + + dialog.m_Gridsize = pDisplay->gridsize; + + if (dialog.DoModal() == IDOK) + { + pDisplay->gridsize = dialog.m_Gridsize; + sciRedraw(); + } +} + +BEGIN_MESSAGE_MAP(CGridsize, CDialog) +END_MESSAGE_MAP() + +/************* + * DESCRIPTION: constructor + * INPUT: - + * OUTPUT: - + *************/ +CGridsize::CGridsize(CWnd* pParent) + : CDialog(CGridsize::IDD, pParent) +{ +} + +/************* + * DESCRIPTION: center window in middle of screen + * INPUT: (system related) + * OUTPUT: - + *************/ +BOOL CGridsize::OnInitDialog() +{ + CDialog::OnInitDialog(); + CenterWindow(); + + return TRUE; +} + +/************* + * DESCRIPTION: transfer data + * INPUT: (system related) + * OUTPUT: - + *************/ +void CGridsize::DoDataExchange(CDataExchange* pDX) +{ + CDialog::DoDataExchange(pDX); + + DDX_Text(pDX, ID_GRIDSIZE_SIZE, m_Gridsize); + DDV_MinMaxFloat(pDX, m_Gridsize, 0, 1000000); +} + + diff --git a/pool/shard001/C++/0023363_avrasmtoken.cpp b/pool/shard001/C++/0023363_avrasmtoken.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f3dae96fa8178b69bd690484d4daac104d2afce7 --- /dev/null +++ b/pool/shard001/C++/0023363_avrasmtoken.cpp @@ -0,0 +1,201 @@ +/* + * avrasmtoken.cpp -- infrastructure for token handling + * Copyright (C) 2013 Gregoire Liglet and Florent Chiron, University of Kent. + * Copyright (C) 2013-2014 Fred Barnes, University of Kent + * + * 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 "avrasmtoken.h" + +#include +#include + +/*{{{ map for token name lookup*/ +QMap AVRASMToken::_tokenTypeStrings = { + { "NOTOKEN", NOTOKEN }, + { "KEYWORD", KEYWORD }, + { "INTEGER", INTEGER }, + { "REAL", REAL }, + { "STRING", STRING }, + { "NAME", NAME }, + { "SYMBOL", SYMBOL }, + { "COMMENT", COMMENT }, + { "NEWLINE", NEWLINE }, + { "INDENT", INDENT }, + { "OUTDENT", OUTDENT }, + { "INAME", INAME }, + { "LSPECIAL", LSPECIAL }, + { "END", END } +}; +/*}}}*/ + +/*{{{ QString AVRASMToken::tokenTypeToString (TokenType tokenType)*/ +/* + * string representation of token. + */ +QString AVRASMToken::tokenTypeToString (TokenType tokenType) +{ + return _tokenTypeStrings.key(tokenType); +} +/*}}}*/ +/*{{{ AVRASMToken::TokenType AVRASMToken::stringToTokenType (const QString &tokenString)*/ +/* + * token representation of string. + */ +AVRASMToken::TokenType AVRASMToken::stringToTokenType (const QString &tokenString) +{ + return _tokenTypeStrings.value(tokenString, (AVRASMToken::TokenType)-1); +} +/*}}}*/ + +/*{{{ AVRASMToken::AVRASMToken(QObject *parent) : QObject(parent)*/ +/* + * constructor. + */ +AVRASMToken::AVRASMToken(QObject *parent) : QObject(parent) +{ +} +/*}}}*/ + +/*{{{ int AVRASMToken::length () const*/ +/* + * returns the token's length (characters). + */ +int AVRASMToken::length () const +{ + return _length; +} +/*}}}*/ +/*{{{ void AVRASMToken::setLength (int value)*/ +/* + * sets the token's length (characters). + */ +void AVRASMToken::setLength (int value) +{ + _length = value; +} +/*}}}*/ +/*{{{ int AVRASMToken::column () const*/ +/* + * returns the column this token lives at (in source code). + */ +int AVRASMToken::column () const +{ + return _column; +} +/*}}}*/ +/*{{{ void AVRASMToken::setColumn (int value)*/ +/* + * sets the column this token lives at. + */ +void AVRASMToken::setColumn (int value) +{ + _column = value; +} +/*}}}*/ +/*{{{ int AVRASMToken::line () const*/ +/* + * gets the line-number of this token. + */ +int AVRASMToken::line () const +{ + return _line; +} +/*}}}*/ +/*{{{ void AVRASMToken::setLine (int value)*/ +/* + * sets the line-number for this token. + */ +void AVRASMToken::setLine (int value) +{ + _line = value; +} +/*}}}*/ +/*{{{ AVRASMToken::TokenType AVRASMToken::type () const*/ +/* + * gets the type of this token. + */ +AVRASMToken::TokenType AVRASMToken::type () const +{ + return _type; +} +/*}}}*/ +/*{{{ void AVRASMToken::setType (const TokenType &type)*/ +/* + * sets the type of this token. + */ +void AVRASMToken::setType (const TokenType &type) +{ + _type = type; +} +/*}}}*/ +/*{{{ QString AVRASMToken::origin () const*/ +/* + * gets the origin of this token. + */ +QString AVRASMToken::origin () const +{ + return _origin; +} +/*}}}*/ +/*{{{ void AVRASMToken::setOrigin (const QString &origin)*/ +/* + * sets the originl of this token. + */ +void AVRASMToken::setOrigin (const QString &origin) +{ + _origin = origin; +} +/*}}}*/ +/*{{{ QString AVRASMToken::value () const*/ +/* + * gets the value of this token. + */ +QString AVRASMToken::value () const +{ + return _value; +} +/*}}}*/ +/*{{{ void AVRASMToken::setValue (const QString &value)*/ +/* + * sets the value of a token. + */ +void AVRASMToken::setValue (const QString &value) +{ + _value = value; +} +/*}}}*/ +/*{{{ QDebug operator << (QDebug qdebug, const AVRASMToken &token)*/ +/* + * for debugging. + */ +QDebug operator << (QDebug qdebug, const AVRASMToken &token) +{ + bool autoInsertSpaces = qdebug.autoInsertSpaces(); + + qdebug.setAutoInsertSpaces(false); + qdebug << ""; + qdebug.setAutoInsertSpaces(autoInsertSpaces); + return qdebug; +} +/*}}}*/ + diff --git a/pool/shard001/C++/0023373_verify_os2.cc b/pool/shard001/C++/0023373_verify_os2.cc new file mode 100644 index 0000000000000000000000000000000000000000..4897e87430ff506f69d573c8fba29abd07386046 --- /dev/null +++ b/pool/shard001/C++/0023373_verify_os2.cc @@ -0,0 +1,125 @@ +/* + * Copyright 2011 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "gtest/gtest.h" +#include "sfntly/font.h" +#include "sfntly/table/core/os2_table.h" +#include "test/serialization_test.h" + +namespace sfntly { + +const int32_t OS2_VERSION = 1; +const int32_t OS2_XAVG_CHAR_WIDTH = 863; +const int32_t OS2_US_WEIGHT_CLASS = 500; +const int32_t OS2_US_WIDTH_CLASS = 5; +const int32_t OS2_FS_TYPE = 0; +const int32_t OS2_YSUBS_XSIZE = 0; +const int32_t OS2_YSUBS_YSIZE = 2; +const int32_t OS2_YSUBS_XOFFSET = -16560; +const int32_t OS2_YSUBS_YOFFSET = 0; +const int32_t OS2_YSUPS_XSIZE = -25944; +const int32_t OS2_YSUPS_YSIZE = -27176; +const int32_t OS2_YSUPS_XOFFSET = -16376; +const int32_t OS2_YSUPS_YOFFSET = 1; +const int32_t OS2_YSTRIKEOUT_SIZE = 12312; +const int32_t OS2_YSTRIKEOUT_POS = -16224; +const int32_t OS2_SFAMILY_CLASS = 0; +const byte_t OS2_PANOSE[] = { 2, 11, 6, 3, 6, 1, 0, 0, 0, 0 }; +const int64_t OS2_UL_UNICODE_RANGE1 = 0xE00002FFL; +const int64_t OS2_UL_UNICODE_RANGE2 = 0x520020FBL; +const int64_t OS2_UL_UNICODE_RANGE3 = 0L; +const int64_t OS2_UL_UNICODE_RANGE4 = 0L; +const byte_t OS2_ACH_VEND_ID[] = { 'P', 'f', 'E', 'd' }; +const int32_t OS2_FS_SELECTION = 0x0040; +const int32_t OS2_US_FIRST_CHAR_IDX = 0x0020; +const int32_t OS2_US_LAST_CHAR_IDX = 0xFFFF; +const int32_t OS2_STYPO_ASCENDER = 1597; +const int32_t OS2_STYPO_DESCENDER = -451; +const int32_t OS2_STYPO_LINE_GAP = 0; +const int32_t OS2_US_WIN_ASCENT = 2023; +const int32_t OS2_US_WIN_DESCENT = 648; +const int64_t OS2_UL_CODE_PAGE_RANGE1 = 0x2000019FL; +const int64_t OS2_UL_CODE_PAGE_RANGE2 = 0x00000000L; + +static bool VerifyOS_2(Table* table) { + OS2TablePtr os2 = down_cast(table); + if (os2 == NULL) { + return false; + } + + EXPECT_EQ(os2->TableVersion(), OS2_VERSION); + EXPECT_EQ(os2->XAvgCharWidth(), OS2_XAVG_CHAR_WIDTH); + EXPECT_EQ(os2->UsWeightClass(), OS2_US_WEIGHT_CLASS); + EXPECT_EQ(os2->UsWidthClass(), OS2_US_WIDTH_CLASS); + EXPECT_EQ(os2->FsType(), OS2_FS_TYPE); + EXPECT_EQ(os2->YSubscriptXSize(), OS2_YSUBS_XSIZE); + EXPECT_EQ(os2->YSubscriptYSize(), OS2_YSUBS_YSIZE); + EXPECT_EQ(os2->YSubscriptXOffset(), OS2_YSUBS_XOFFSET); + EXPECT_EQ(os2->YSubscriptYOffset(), OS2_YSUBS_YOFFSET); + EXPECT_EQ(os2->YSuperscriptXSize(), OS2_YSUPS_XSIZE); + EXPECT_EQ(os2->YSuperscriptYSize(), OS2_YSUPS_YSIZE); + EXPECT_EQ(os2->YSuperscriptXOffset(), OS2_YSUPS_XOFFSET); + EXPECT_EQ(os2->YSuperscriptYOffset(), OS2_YSUPS_YOFFSET); + EXPECT_EQ(os2->YStrikeoutSize(), OS2_YSTRIKEOUT_SIZE); + EXPECT_EQ(os2->YStrikeoutPosition(), OS2_YSTRIKEOUT_POS); + EXPECT_EQ(os2->SFamilyClass(), OS2_SFAMILY_CLASS); + + ByteVector panose; + os2->Panose(&panose); + EXPECT_EQ(panose.size(), sizeof(OS2_PANOSE)); + for (size_t i = 0; i < panose.size(); ++i) { + EXPECT_EQ(panose[i], OS2_PANOSE[i]); + } + + EXPECT_EQ(os2->UlUnicodeRange1(), OS2_UL_UNICODE_RANGE1); + EXPECT_EQ(os2->UlUnicodeRange2(), OS2_UL_UNICODE_RANGE2); + EXPECT_EQ(os2->UlUnicodeRange3(), OS2_UL_UNICODE_RANGE3); + EXPECT_EQ(os2->UlUnicodeRange4(), OS2_UL_UNICODE_RANGE4); + + ByteVector vend_id; + os2->AchVendId(&vend_id); + EXPECT_EQ(vend_id.size(), sizeof(OS2_ACH_VEND_ID)); + for (size_t i = 0; i < vend_id.size(); ++i) { + EXPECT_EQ(vend_id[i], OS2_ACH_VEND_ID[i]); + } + + EXPECT_EQ(os2->FsSelection(), OS2_FS_SELECTION); + EXPECT_EQ(os2->UsFirstCharIndex(), OS2_US_FIRST_CHAR_IDX); + EXPECT_EQ(os2->UsLastCharIndex(), OS2_US_LAST_CHAR_IDX); + EXPECT_EQ(os2->STypoAscender(), OS2_STYPO_ASCENDER); + EXPECT_EQ(os2->STypoDescender(), OS2_STYPO_DESCENDER); + EXPECT_EQ(os2->STypoLineGap(), OS2_STYPO_LINE_GAP); + EXPECT_EQ(os2->UsWinAscent(), OS2_US_WIN_ASCENT); + EXPECT_EQ(os2->UsWinDescent(), OS2_US_WIN_DESCENT); + EXPECT_EQ(os2->UlCodePageRange1(), OS2_UL_CODE_PAGE_RANGE1); + EXPECT_EQ(os2->UlCodePageRange2(), OS2_UL_CODE_PAGE_RANGE2); + + // TODO(arthurhsu): SxHeight() not tested + // TODO(arthurhsu): SCapHeight() not tested + // TODO(arthurhsu): UsDefaultChar() not tested + // TODO(arthurhsu): UsBreakChar() not tested + // TODO(arthurhsu): UsMaxContext() not tested + + return true; +} + +bool VerifyOS_2(Table* original, Table* target) { + EXPECT_TRUE(VerifyOS_2(original)); + EXPECT_TRUE(VerifyOS_2(target)); + return true; +} + +} // namespace sfntly diff --git a/pool/shard001/C++/0023376_LIS.cpp b/pool/shard001/C++/0023376_LIS.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e2fedefaa32b3565deb1b9f55c03150972259240 --- /dev/null +++ b/pool/shard001/C++/0023376_LIS.cpp @@ -0,0 +1,25 @@ +vll LIS(const vll &elements) { + auto compare = [&](ll x, ll y) { return elements[x] < elements[y];}; + set s(compare); + + vll previous(elements.size(), -1); + + for(ll i = 0; i < elements.size(); i++) { + auto it = s.insert(i).first; + if(it != s.begin()) { + previous[i] = *prev(it); + } + if(*it == i && next(it) != s.end()) { + s.erase(next(it)); + } + } + + vll ans; + ans.push_back(*s.rbegin()); + while(previous[ans.back()] != -1) { + ans.push_back(previous[ans.back()]); + } + + reverse(ans.begin(), ans.end()); + return ans; + } diff --git a/pool/shard001/C++/0023379_DllMain.cpp b/pool/shard001/C++/0023379_DllMain.cpp new file mode 100644 index 0000000000000000000000000000000000000000..52c1c030e07609391b5049ba983187a74efb977e --- /dev/null +++ b/pool/shard001/C++/0023379_DllMain.cpp @@ -0,0 +1,100 @@ +#include +#include +#include +#include +#include +#include +#include "Windows7.h" +#include "JumpList.h" + +static const wchar_t* namelist[] = { + L"¶í¿Ì°¢ÅµË¹¼¶YDWE", + L"¿Æ¶í˹¼¶YDWE", + L"¿ËÀû¶í˹¼¶YDWE", + L"ÐíçêÀïÎ̼¶YDWE", + L"ÒÁ°¢çêÍÐ˹¼¶YDWE", + L"߯ÑǼ¶YDWE", + L"ÈðÑǼ¶YDWE", + L"߯ÃÖ˹¼¶YDWE", + L"ÚÓÄùĦÐ÷Äù¼¶YDWE", + L"¸£°Ø¼¶YDWE", + L"߯µÌ˹¼¶YDWE", + L"¿ËÂåŵ˹¼¶YDWE", +}; + +static const wchar_t* getCurrentAppID() +{ + size_t n = sizeof namelist / sizeof namelist[0]; + size_t random = (size_t)std::random_device()(); + for (size_t i = 0; i < n; ++i) + { + const wchar_t* name = namelist[(random + i) % n]; + HANDLE mutex = CreateMutexW(NULL, TRUE, name); + if (mutex) + { + return name; + } + else if (GetLastError() != ERROR_ALREADY_EXISTS) + { + break; + } + } + + static std::wstring randomresult = L"YDWE.WorldEdit." + std::to_wstring((long long)random); + return randomresult.c_str(); +} + +bool JumpListAddRecentTask(JumpList& jumpList, fs::path const& ydweDirectory, fs::path const& filePath) +{ + HRESULT hr = jumpList.AddTask(filePath.filename().c_str(), [&](base::com::unique_ptr& shellLinkPtr) + { + shellLinkPtr->SetPath((ydweDirectory / L"YDWE.exe").c_str()); + shellLinkPtr->SetArguments((L" -loadfile \"" + filePath.wstring() + L"\"").c_str()); + shellLinkPtr->SetDescription(filePath.c_str()); + shellLinkPtr->SetIconLocation((ydweDirectory / L"bin" / L"logo.ico").c_str(), 0); + }); + + return SUCCEEDED(hr); +} + +void Initialize() +{ + if (bee::platform::get_version().ver < bee::platform::WinVer::Win7) + { + return ; + } + + const wchar_t* currentAppID = 0; + HRESULT hr = windows7::GetCurrentProcessExplicitAppUserModelID((wchar_t**)¤tAppID); + if (FAILED(hr) || !currentAppID) + { + currentAppID = getCurrentAppID(); + windows7::SetCurrentProcessExplicitAppUserModelID(currentAppID); + } + + JumpList jumpList; + jumpList.SetAppID(currentAppID); + if (jumpList.InitializeList()) + { + fs::path ydweDirectory = base::path::ydwe(false); + + jumpList.AddTaskSeparator(); + + jumpList.AddTask(L"YDWEÅäÖÃ", [&](base::com::unique_ptr& shellLinkPtr) + { + shellLinkPtr->SetPath((ydweDirectory / L"bin" / L"YDWEConfig.exe").c_str()); + shellLinkPtr->SetDescription(L"´ò¿ªYDWEÅäÖóÌÐò¡£"); + shellLinkPtr->SetIconLocation((ydweDirectory / L"bin" / L"logo.ico").c_str(), 0); + }); + } +} + +BOOL APIENTRY DllMain(HMODULE module, DWORD reason, LPVOID pReserved) +{ + if (reason == DLL_PROCESS_ATTACH) + { + ::DisableThreadLibraryCalls(module); + } + + return TRUE; +} diff --git a/pool/shard001/C++/0023382_Camera.cpp b/pool/shard001/C++/0023382_Camera.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e1be1578b64fac072a4b89c36a32fb368439b07a --- /dev/null +++ b/pool/shard001/C++/0023382_Camera.cpp @@ -0,0 +1,145 @@ +/* + tdogl::Camera + + Copyright 2012 Thomas Dalling - http://tomdalling.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. + */ +#define _USE_MATH_DEFINES +#include +#include "Camera.h" +#include + + +static const float MaxVerticalAngle = 85.0f; //must be less than 90 to avoid gimbal lock + +static inline float RadiansToDegrees(float radians) { + return radians * 180.0f / (float)M_PI; +} + + +Camera::Camera() : + _position(0.0f, 0.0f, 1.0f), + _horizontalAngle(0.0f), + _verticalAngle(0.0f), + _fieldOfView(50.0f), + _nearPlane(0.01f), + _farPlane(100.0f), + _viewportAspectRatio(4.0f/3.0f) +{ +} + +const glm::vec3& Camera::position() const { + return _position; +} + +void Camera::setPosition(const glm::vec3& position) { + _position = position; +} + +void Camera::offsetPosition(const glm::vec3& offset) { + _position += offset; +} + +float Camera::fieldOfView() const { + return _fieldOfView; +} + +void Camera::setFieldOfView(float fieldOfView) { + assert(fieldOfView > 0.0f && fieldOfView < 180.0f); + _fieldOfView = fieldOfView; +} + +float Camera::nearPlane() const { + return _nearPlane; +} + +float Camera::farPlane() const { + return _farPlane; +} + +void Camera::setNearAndFarPlanes(float nearPlane, float farPlane) { + assert(nearPlane > 0.0f); + assert(farPlane > nearPlane); + _nearPlane = nearPlane; + _farPlane = farPlane; +} + +glm::mat4 Camera::orientation() const { + glm::mat4 orientation; + orientation = glm::rotate(orientation, _verticalAngle, glm::vec3(1,0,0)); + orientation = glm::rotate(orientation, _horizontalAngle, glm::vec3(0,1,0)); + return orientation; +} + +void Camera::offsetOrientation(float upAngle, float rightAngle) { + _horizontalAngle += rightAngle; + _verticalAngle += upAngle; + normalizeAngles(); +} + +void Camera::lookAt(glm::vec3 position) { + assert(position != _position); + glm::vec3 direction = glm::normalize(position - _position); + _verticalAngle = RadiansToDegrees(asinf(-direction.y)); + _horizontalAngle = -RadiansToDegrees(atan2f(-direction.x, -direction.z)); + normalizeAngles(); +} + +float Camera::viewportAspectRatio() const { + return _viewportAspectRatio; +} + +void Camera::setViewportAspectRatio(float viewportAspectRatio) { + assert(viewportAspectRatio > 0.0); + _viewportAspectRatio = viewportAspectRatio; +} + +glm::vec3 Camera::forward() const { + glm::vec4 forward = glm::inverse(orientation()) * glm::vec4(0,0,-1,1); + return glm::vec3(forward); +} + +glm::vec3 Camera::right() const { + glm::vec4 right = glm::inverse(orientation()) * glm::vec4(1,0,0,1); + return glm::vec3(right); +} + +glm::vec3 Camera::up() const { + glm::vec4 up = glm::inverse(orientation()) * glm::vec4(0,1,0,1); + return glm::vec3(up); +} + +glm::mat4 Camera::matrix() const { + return projection() * view(); +} + +glm::mat4 Camera::projection() const { + return glm::perspective(_fieldOfView, _viewportAspectRatio, _nearPlane, _farPlane); +} + +glm::mat4 Camera::view() const { + return orientation() * glm::translate(glm::mat4(), -_position); +} + +void Camera::normalizeAngles() { + _horizontalAngle = fmodf(_horizontalAngle, 360.0f); + //fmodf can return negative values, but this will make them all positive + if(_horizontalAngle < 0.0f) + _horizontalAngle += 360.0f; + + if(_verticalAngle > MaxVerticalAngle) + _verticalAngle = MaxVerticalAngle; + else if(_verticalAngle < -MaxVerticalAngle) + _verticalAngle = -MaxVerticalAngle; +} diff --git a/pool/shard001/C++/0023383_AbstractPointsSchemaHandler.cpp b/pool/shard001/C++/0023383_AbstractPointsSchemaHandler.cpp new file mode 100644 index 0000000000000000000000000000000000000000..95afb2a33520c38f52cf1c652a0c733db947a8af --- /dev/null +++ b/pool/shard001/C++/0023383_AbstractPointsSchemaHandler.cpp @@ -0,0 +1,58 @@ +#include "AbstractPointsSchemaHandler.h" + +AbstractPointsSchemaHandler::AbstractPointsSchemaHandler() +{ + +} + +AbstractPointsSchemaHandler::~AbstractPointsSchemaHandler() +{ + +} + +void AbstractPointsSchemaHandler::ProcessPoints(const Alembic::Abc::IObject& top, + const std::string& child_name, + const StringContainer& i_hierachy_path, + size_t i_requested_index, + float i_relative_shutter_open, + float i_relative_shutter_close, + Alembic::Abc::uint8_t num_motion_samples) const +{ + std::cout << " of type Points"; + Alembic::AbcGeom::IPoints points(top,child_name); + Alembic::AbcGeom::IPointsSchema& schema = points.getSchema(); + + Alembic::Abc::IV3fArrayProperty velocities_property = schema.getVelocitiesProperty(); + Alembic::Abc::IUInt64ArrayProperty ids_property = schema.getIdsProperty(); + if (velocities_property.valid() && ids_property.valid()) + { + std::string unique_object_path; + StringContainer _concatenated_hierachy_path = i_hierachy_path; + _concatenated_hierachy_path.push_back(child_name); + flatten_string_array(_concatenated_hierachy_path, "_", unique_object_path); + std::cout << boost::format(" of type Points, unique_object_path : '%1%'") % unique_object_path << std::endl; + + Alembic::AbcGeom::TimeSamplingPtr ts_ptr = points.getSchema().getTimeSampling(); + Alembic::AbcGeom::TimeSamplingType timeType = ts_ptr->getTimeSamplingType(); + Alembic::AbcGeom::chrono_t tpc = timeType.getTimePerCycle(); + // Alembic::AbcGeom::chrono_t fps = 1.0/tpc; + // std::cout << boost::format("fps = %1%") % fps << std::endl; + if ( timeType.isUniform() ) + { + std::cout << " timeType.isUniform() == true" << std::endl; + size_t start_frame = ts_ptr->getStoredTimes()[0] / tpc; + // std::cout << boost::format("start_frame = %1%") % start_frame << std::endl; + std::string renderman_filename = (boost::format("%s.%04d.rib") % unique_object_path % i_requested_index).str(); + std::cout << boost::format(" renderman_filename : '%1%'") % renderman_filename << std::endl; + EmitPoints(points,start_frame,i_requested_index,renderman_filename,num_motion_samples,i_relative_shutter_open,i_relative_shutter_close); + } + else if (timeType.isCyclic()) + { + std::cout << " timeType.isCyclic() == true" << std::endl; + } + else if (timeType.isAcyclic()) + { + std::cout << " timeType.isAcyclic() == true" << std::endl; + } + } +} diff --git a/pool/shard001/C++/0023396_SimpleFontDataChromiumWin.cpp b/pool/shard001/C++/0023396_SimpleFontDataChromiumWin.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8510dfa52da61a1c005dfbdd976465593aef0697 --- /dev/null +++ b/pool/shard001/C++/0023396_SimpleFontDataChromiumWin.cpp @@ -0,0 +1,221 @@ +/* + * Copyright (C) 2006, 2007 Apple Inc. All Rights Reserved. + * Copyright (c) 2008, 2009, 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 "config.h" +#include "SimpleFontData.h" + +#include "FloatRect.h" +#include "Font.h" +#include "FontCache.h" +#include "FontDescription.h" +#include "HWndDC.h" +#include "PlatformSupport.h" +#include + +#include +#include +#include +#include + +namespace WebCore { + +void SimpleFontData::platformInit() +{ + if (!m_platformData.size()) { + m_fontMetrics.reset(); + m_avgCharWidth = 0; + m_maxCharWidth = 0; + return; + } + + HWndDC dc(0); + HGDIOBJ oldFont = SelectObject(dc, m_platformData.hfont()); + + TEXTMETRIC textMetric = {0}; + if (!GetTextMetrics(dc, &textMetric)) { + if (PlatformSupport::ensureFontLoaded(m_platformData.hfont())) { + // Retry GetTextMetrics. + // FIXME: Handle gracefully the error if this call also fails. + // See http://crbug.com/6401. + if (!GetTextMetrics(dc, &textMetric)) + LOG_ERROR("Unable to get the text metrics after second attempt"); + } + } + + m_avgCharWidth = textMetric.tmAveCharWidth; + m_maxCharWidth = textMetric.tmMaxCharWidth; + + // FIXME: Access ascent/descent/lineGap with floating point precision. + float ascent = textMetric.tmAscent; + float descent = textMetric.tmDescent; + float lineGap = textMetric.tmExternalLeading; + float xHeight = ascent * 0.56f; // Best guess for xHeight for non-Truetype fonts. + + OUTLINETEXTMETRIC outlineTextMetric; + if (GetOutlineTextMetrics(dc, sizeof(outlineTextMetric), &outlineTextMetric) > 0) { + m_fontMetrics.setUnitsPerEm(outlineTextMetric.otmEMSquare); + + // This is a TrueType font. We might be able to get an accurate xHeight. + GLYPHMETRICS glyphMetrics = {0}; + MAT2 identityMatrix = {{0, 1}, {0, 0}, {0, 0}, {0, 1}}; + DWORD len = GetGlyphOutlineW(dc, 'x', GGO_METRICS, &glyphMetrics, 0, 0, &identityMatrix); + if (len != GDI_ERROR && glyphMetrics.gmBlackBoxY > 0) + xHeight = static_cast(glyphMetrics.gmBlackBoxY); + } + + m_fontMetrics.setAscent(ascent); + m_fontMetrics.setDescent(descent); + m_fontMetrics.setLineGap(lineGap); + m_fontMetrics.setXHeight(xHeight); + m_fontMetrics.setLineSpacing(ascent + descent + lineGap); + + SelectObject(dc, oldFont); +} + +void SimpleFontData::platformCharWidthInit() +{ + // charwidths are set in platformInit. +} + +void SimpleFontData::platformDestroy() +{ +} + +PassRefPtr SimpleFontData::createScaledFontData(const FontDescription& fontDescription, float scaleFactor) const +{ + LOGFONT winFont; + GetObject(m_platformData.hfont(), sizeof(LOGFONT), &winFont); + float scaledSize = scaleFactor * fontDescription.computedSize(); + winFont.lfHeight = -lroundf(scaledSize); + HFONT hfont = CreateFontIndirect(&winFont); + return SimpleFontData::create(FontPlatformData(hfont, scaledSize, m_platformData.orientation()), isCustomFont(), false); +} + +PassRefPtr SimpleFontData::smallCapsFontData(const FontDescription& fontDescription) const +{ + if (!m_derivedFontData) + m_derivedFontData = DerivedFontData::create(isCustomFont()); + if (!m_derivedFontData->smallCaps) + m_derivedFontData->smallCaps = createScaledFontData(fontDescription, .7); + + return m_derivedFontData->smallCaps; +} + +PassRefPtr SimpleFontData::emphasisMarkFontData(const FontDescription& fontDescription) const +{ + if (!m_derivedFontData) + m_derivedFontData = DerivedFontData::create(isCustomFont()); + if (!m_derivedFontData->emphasisMark) + m_derivedFontData->emphasisMark = createScaledFontData(fontDescription, .5); + + return m_derivedFontData->emphasisMark; +} + +bool SimpleFontData::containsCharacters(const UChar* characters, int length) const +{ + // This used to be implemented with IMLangFontLink2, but since that code has + // been disabled, this would always return false anyway. + return false; +} + +void SimpleFontData::determinePitch() +{ + // TEXTMETRICS have this. Set m_treatAsFixedPitch based off that. + HWndDC dc(0); + HGDIOBJ oldFont = SelectObject(dc, m_platformData.hfont()); + + // Yes, this looks backwards, but the fixed pitch bit is actually set if the font + // is *not* fixed pitch. Unbelievable but true. + TEXTMETRIC textMetric = {0}; + if (!GetTextMetrics(dc, &textMetric)) { + if (PlatformSupport::ensureFontLoaded(m_platformData.hfont())) { + // Retry GetTextMetrics. + // FIXME: Handle gracefully the error if this call also fails. + // See http://crbug.com/6401. + if (!GetTextMetrics(dc, &textMetric)) + LOG_ERROR("Unable to get the text metrics after second attempt"); + } + } + + m_treatAsFixedPitch = ((textMetric.tmPitchAndFamily & TMPF_FIXED_PITCH) == 0); + + SelectObject(dc, oldFont); +} + +FloatRect SimpleFontData::platformBoundsForGlyph(Glyph glyph) const +{ + HWndDC hdc(0); + SetGraphicsMode(hdc, GM_ADVANCED); + HGDIOBJ oldFont = SelectObject(hdc, m_platformData.hfont()); + + GLYPHMETRICS gdiMetrics; + static const MAT2 identity = { 0, 1, 0, 0, 0, 0, 0, 1 }; + if (GetGlyphOutline(hdc, glyph, GGO_METRICS | GGO_GLYPH_INDEX, &gdiMetrics, 0, 0, &identity) == -1) { + if (PlatformSupport::ensureFontLoaded(m_platformData.hfont())) { + // Retry GetTextMetrics. + // FIXME: Handle gracefully the error if this call also fails. + // See http://crbug.com/6401. + if (GetGlyphOutline(hdc, glyph, GGO_METRICS | GGO_GLYPH_INDEX, &gdiMetrics, 0, 0, &identity) == -1) + LOG_ERROR("Unable to get the glyph metrics after second attempt"); + } + } + + SelectObject(hdc, oldFont); + + return FloatRect(gdiMetrics.gmptGlyphOrigin.x, -gdiMetrics.gmptGlyphOrigin.y, + gdiMetrics.gmBlackBoxX, gdiMetrics.gmBlackBoxY); +} + +float SimpleFontData::platformWidthForGlyph(Glyph glyph) const +{ + if (!m_platformData.size()) + return 0; + + HWndDC dc(0); + HGDIOBJ oldFont = SelectObject(dc, m_platformData.hfont()); + + int width = 0; + if (!GetCharWidthI(dc, glyph, 1, 0, &width)) { + // Ask the browser to preload the font and retry. + if (PlatformSupport::ensureFontLoaded(m_platformData.hfont())) { + // FIXME: Handle gracefully the error if this call also fails. + // See http://crbug.com/6401. + if (!GetCharWidthI(dc, glyph, 1, 0, &width)) + LOG_ERROR("Unable to get the char width after second attempt"); + } + } + + SelectObject(dc, oldFont); + + return static_cast(width); +} + +} // namespace WebCore diff --git a/pool/shard001/C++/0023398_PluginInstaller.cpp b/pool/shard001/C++/0023398_PluginInstaller.cpp new file mode 100644 index 0000000000000000000000000000000000000000..438b9c07e12ca3bf6de21859785dd7180f610b87 --- /dev/null +++ b/pool/shard001/C++/0023398_PluginInstaller.cpp @@ -0,0 +1,227 @@ +/** + * + * This file is part of Tulip (www.tulip-software.org) + * + * Authors: David Auber and the Tulip development Team + * from LaBRI, University of Bordeaux 1 and Inria Bordeaux - Sud Ouest + * + * Tulip 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. + * + * Tulip 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 +#include "PluginGenerate.h" + +#include +#include + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +using namespace std; +using namespace tlp; + +int main(int argc,char **argv) { + if(argc != 5 && argc != 6) { + cout << "How to use :" << endl; + cout << " First arg : plugin file" << endl; + cout << " Second arg : doxygen generated plugin doc file" << endl; + cout << " Third arg : target directory" << endl; + cout << " 4th arg : generate .xml/.doc files (yes/no)" << endl; + cout << " 5th arg : i386/i64 : default i386" << endl; + exit(1); + } + + QString pluginPath=argv[1]; + QString pluginDocPath=argv[2]; + QString targetPath=argv[3]; + + cout << "plugin path : " << pluginPath.toStdString() << endl; + cout << "plugin doc path : " << pluginDocPath.toStdString() << endl; + cout << "target path : " << targetPath.toStdString() << endl; + + bool generateDoc=true; + + if(QString(argv[4])=="no") + generateDoc=false; + + QString subDir("i386"); + + if(argc>=6) + subDir=QString(argv[5]); + + QApplication app(argc, argv); + QFileInfo fileInfo(pluginPath); + QDir srcDir = fileInfo.dir(); + QString suffix = fileInfo.suffix(); + + char *getEnvTlp=getenv("TLP_DIR"); +#if defined(_WIN32) + putenv("TLP_DIR="); +#else + setenv("TLP_DIR","",true); +#endif + PluginLoaderWithInfo plug; + initTulipLib(NULL); + loadPlugin(pluginPath.toStdString(), &plug); + + if (generateDoc) { + //GlyphManager::getInst().loadPlugins(&plug); //Glyph plugins + InteractorManager::getInst().loadPlugins(&plug); + ViewPluginsManager::getInst().loadPlugins(&plug); + ControllerPluginsManager::getInst().loadPlugins(&plug); + } + + if (!plug.errorMsgs.empty()) { + cout << "Error when loading plugins:"<< endl; + cout << plug.errorMsgs << endl; + return EXIT_FAILURE; + } + +#if defined(_WIN32) + + if (getEnvTlp) + putenv((string("TLP_DIR=") + getEnvTlp).c_str()); + else + putenv("TLP_DIR="); + +#else + + if (getEnvTlp) + setenv("TLP_DIR",getEnvTlp,true); + else + unsetenv("TLP_DIR"); + +#endif + + TemplateFactory::ObjectCreator::const_iterator itGlyphs; + vector glyphsName; + + for (itGlyphs=GlyphFactory::factory->objMap.begin(); itGlyphs != GlyphFactory::factory->objMap.end(); ++itGlyphs) { + glyphsName.push_back((itGlyphs)->first); + } + + TemplateFactory::ObjectCreator::const_iterator itInteractors; + vector interactorsName; + + for (itInteractors=InteractorFactory::factory->objMap.begin(); itInteractors != InteractorFactory::factory->objMap.end(); ++itInteractors) { + interactorsName.push_back((itInteractors)->first); + } + + TemplateFactory::ObjectCreator::const_iterator itViews; + vector viewsName; + + for (itViews=ViewFactory::factory->objMap.begin(); itViews != ViewFactory::factory->objMap.end(); ++itViews) { + viewsName.push_back((itViews)->first); + } + + + for(size_t i=0; i::iterator it=glyphsName.begin(); it!=glyphsName.end(); ++it) { + if(plug.pluginsList[i].name==(*it)) { + plug.pluginsList[i].type="Glyph"; + } + } + + for(vector::iterator it=interactorsName.begin(); it!=interactorsName.end(); ++it) { + if(plug.pluginsList[i].name==(*it)) { + plug.pluginsList[i].type="Interactor"; + } + } + + for(vector::iterator it=viewsName.begin(); it!=viewsName.end(); ++it) { + if(plug.pluginsList[i].name==(*it)) { + plug.pluginsList[i].type="View"; + } + } + + if(plug.pluginsList[i].type=="") + plug.pluginsList[i].type="Algorithm"; + } + + LocalPluginInfo pluginInfo; + + if(plug.pluginsList.size()>1) { + bool equal=true; + + for(size_t i=0; i + + +SshConnectionForm::SshConnectionForm(const QString &name, QWidget *parent) + : QWidget(parent) + , m_client(name) + , ui(new Ui::SshConnectionForm) +{ + ui->setupUi(this); + QObject::connect(&m_client, &SshClient::sshStateChanged, this, &SshConnectionForm::onSshStateChanged); + QObject::connect(&m_client, &SshClient::channelsChanged, [this](int nb){ ui->channelsCount->setText(QString("%1").arg(nb));}); +} + +SshConnectionForm::~SshConnectionForm() +{ + delete ui; +} + +void SshConnectionForm::on_connectButton_clicked() +{ + if((m_client.sshState() == SshClient::SshState::Unconnected)) + { + m_client.setPassphrase(ui->passwordEdit->text()); + m_client.connectToHost(ui->loginEdit->text(), ui->hostnameEdit->text(), ui->portEdit->text().toUShort()); + } + else + { + m_client.disconnectFromHost(); + } +} + +void SshConnectionForm::onSshStateChanged(SshClient::SshState sshState) +{ + qWarning() << "New SSH State: " << sshState; + ui->sshStateText->setText(QMetaEnum::fromType().valueToKey( int(sshState) )); + ui->connectButton->setText((sshState == SshClient::SshState::Unconnected)?("Connect"):("Disconnect")); + ui->actionTabWidget->setEnabled(sshState == SshClient::SshState::Ready); +} + +void SshConnectionForm::on_createDirectTunnelButton_clicked() +{ + if(ui->portInput->text().length() > 0) + { + DirectTunnelForm *form = new DirectTunnelForm(&m_client, ui->hostInput->text(), "0.0.0.0", ui->portInput->text().toUShort(), this); + QObject::connect(form, &DirectTunnelForm::destroyme, this, &SshConnectionForm::destroyChannel); + ui->listTunnels->layout()->addWidget(form); + } +} + +void SshConnectionForm::destroyChannel() +{ + QObject *obj = QObject::sender(); + QWidget *ch = qobject_cast(obj); + if(ch) + { + qWarning() << "Remove channel" << ch; + ui->listTunnels->layout()->removeWidget(ch); + ch->deleteLater(); + } +} + +void SshConnectionForm::on_createReverseTunnelButton_clicked() +{ + if(ui->rtargetPortInput->text().length() > 0) + { + ReverseTunnelForm *form = new ReverseTunnelForm(&m_client, ui->rListenPortInput->text().toUShort(), ui->rhostInput->text(), ui->rtargetPortInput->text().toUShort(), this); + QObject::connect(form, &ReverseTunnelForm::destroyme, this, &SshConnectionForm::destroyChannel); + ui->listTunnels->layout()->addWidget(form); + } +} diff --git a/pool/shard001/C++/0023404_CrashDaemon.cpp b/pool/shard001/C++/0023404_CrashDaemon.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d6e8339de3c1baa5bcd0e8e24ed3739266a9292f --- /dev/null +++ b/pool/shard001/C++/0023404_CrashDaemon.cpp @@ -0,0 +1,298 @@ +#include "StdAfx.h" +#include "CrashDaemon.h" + + +#include +#include + +#include +#include + +#include +#pragma comment(lib, "dbghelp.lib") + + + +namespace +{ + ////////////////////////////////////////////////////////////////////////// + // È«¾Ö±äÁ¿ + CrashDaemon::PrevWriteDumpCallback g_PrevWriteDumpCallback = NULL; + CrashDaemon::PostWriteDumpCallback g_PostWriteDumpCallback = NULL; + + ULONG64 g_EipMemBase = 0; + ULONG g_EipMemSize = 0; + BOOL g_EipMemWritten = FALSE; + + ////////////////////////////////////////////////////////////////////////// + // WriteDumpÏà¹Ø·½·¨ + + void ReserveMemory(struct _EXCEPTION_POINTERS *ExceptionInfo) + { + // Find a memory region of 256 bytes centered on the + // faulting instruction pointer. + const ULONG64 instruction_pointer = +#if defined(_M_IX86) + ExceptionInfo->ContextRecord->Eip; +#elif defined(_M_AMD64) + ExceptionInfo->ContextRecord->Rip; +#else +#error Unsupported platform +#endif + + MEMORY_BASIC_INFORMATION info; + if (VirtualQueryEx(::GetCurrentProcess(), + reinterpret_cast(instruction_pointer), + &info, + sizeof(MEMORY_BASIC_INFORMATION)) != 0 && + info.State == MEM_COMMIT) + { + // Attempt to get 128 bytes before and after the instruction + // pointer, but settle for whatever's available up to the + // boundaries of the memory region. + const ULONG64 kIPMemorySize = 256; + ULONG64 base = + (std::max)(reinterpret_cast(info.BaseAddress), + instruction_pointer - (kIPMemorySize / 2)); + ULONG64 end_of_range = + (std::min)(instruction_pointer + (kIPMemorySize / 2), + reinterpret_cast(info.BaseAddress) + + info.RegionSize); + ULONG size = static_cast(end_of_range - base); + + g_EipMemBase = base; + g_EipMemSize = size; + } + } + + // static + BOOL CALLBACK MinidumpWriteDumpCallback( + PVOID context, + const PMINIDUMP_CALLBACK_INPUT callback_input, + PMINIDUMP_CALLBACK_OUTPUT callback_output) + { + context; + switch (callback_input->CallbackType) + { + case MemoryCallback: + { + if(g_EipMemBase == NULL || g_EipMemWritten) + return FALSE; + + // Include the specified memory region. + g_EipMemWritten = TRUE; + callback_output->MemoryBase = g_EipMemBase; + callback_output->MemorySize = g_EipMemSize; + + return TRUE; + } + + // Include all modules. + case IncludeModuleCallback: + case ModuleCallback: + return TRUE; + + // Include all threads. + case IncludeThreadCallback: + case ThreadCallback: + return TRUE; + + // Stop receiving cancel callbacks. + case CancelCallback: + callback_output->CheckCancel = FALSE; + callback_output->Cancel = FALSE; + return TRUE; + } + // Ignore other callback types. + return FALSE; + } + + BOOL CallPrevWriteDump(IN DWORD dwThreadId, IN const EXCEPTION_POINTERS* ExceptionPointer) + { + return (g_PrevWriteDumpCallback == NULL || g_PrevWriteDumpCallback(dwThreadId, ExceptionPointer)); + } + + void CallPostWriteDump(IN LPCTSTR szFilePath) + { + if(g_PostWriteDumpCallback) + { + g_PostWriteDumpCallback(szFilePath); + } + } + + void GenerateCrashDump(DWORD dwThreadId, EXCEPTION_POINTERS *ExceptionInfo) + { + if(!CallPrevWriteDump(dwThreadId, ExceptionInfo)) + return; + + MINIDUMP_EXCEPTION_INFORMATION info = {0}; + info.ThreadId = dwThreadId; + info.ExceptionPointers = ExceptionInfo; + info.ClientPointers = FALSE; + + MINIDUMP_CALLBACK_INFORMATION callback = {&MinidumpWriteDumpCallback, 0}; + + ReserveMemory(ExceptionInfo); + + TCHAR szDumpPath[1024]; + TCHAR szDumpFilePath[1024]; + ::GetTempPath(1024, szDumpPath); + srand((unsigned int)time(NULL)); + ::GetTempFileName(szDumpPath, _T("soya"), rand(), szDumpFilePath); + + HANDLE hFile = ::CreateFile(szDumpFilePath, GENERIC_WRITE, 0, 0, CREATE_ALWAYS, 0, 0); + + ::MiniDumpWriteDump(::GetCurrentProcess(), + ::GetCurrentProcessId(), + hFile, + MiniDumpNormal, + &info, + NULL, + &callback + ); + + ::CloseHandle(hFile); + + CallPostWriteDump(szDumpFilePath); + } + + ////////////////////////////////////////////////////////////////////////// + // ¸÷ÖÖ±ÀÀ£´¦Àí·½·¨ + + // SetUnhandledExceptionFilter + LONG WINAPI ExceptionFilter(struct _EXCEPTION_POINTERS *ExceptionInfo) + { + DWORD dwThreadId = ::GetCurrentThreadId(); + + GenerateCrashDump(dwThreadId, ExceptionInfo); + + return EXCEPTION_EXECUTE_HANDLER; + } + + // _set_invalid_parameter_handler + void __cdecl InvalidParameterHandler(const wchar_t * exception, + const wchar_t * function, + const wchar_t * file, + unsigned int line, + uintptr_t pReserved) + { + pReserved; + line; + file; + function; + exception; + EXCEPTION_RECORD exception_record = {}; + CONTEXT exception_context = {}; + EXCEPTION_POINTERS exception_ptrs = { &exception_record, &exception_context }; + + ::RtlCaptureContext(&exception_context); + +#ifndef STATUS_INVALID_PARAMETER +#define STATUS_INVALID_PARAMETER (0xC000000DL) +#endif /* STATUS_INVALID_PARAMETER */ + + exception_record.ExceptionCode = static_cast(STATUS_INVALID_PARAMETER); + + DWORD dwThreadId = ::GetCurrentThreadId(); + GenerateCrashDump(dwThreadId, &exception_ptrs); + + exit(1); + } + + // _set_purecall_handler + void __cdecl PurecallHandler(void) + { + EXCEPTION_RECORD exception_record = {}; + CONTEXT exception_context = {}; + EXCEPTION_POINTERS exception_ptrs = { &exception_record, &exception_context }; + + ::RtlCaptureContext(&exception_context); + +#ifndef STATUS_PURE_CALL +#define STATUS_PURE_CALL (0xC137000DL) +#endif /* STATUS_PURE_CALL */ + + exception_record.ExceptionCode = static_cast(STATUS_PURE_CALL); + + DWORD dwThreadId = ::GetCurrentThreadId(); + + GenerateCrashDump(dwThreadId, &exception_ptrs); + + exit(1); + } + + // signal + void _cdecl SignalHandler(int signal) + { + EXCEPTION_RECORD exception_record = {}; + CONTEXT exception_context = {}; + EXCEPTION_POINTERS exception_ptrs = { &exception_record, &exception_context }; + + ::RtlCaptureContext(&exception_context); + +#ifndef STATUS_SIGNAL_ABORT +#define STATUS_SIGNAL_ABORT (0xC137000EL) +#endif /* STATUS_SIGNAL_ABORT */ +#ifndef STATUS_SIGNAL_TERM +#define STATUS_SIGNAL_TERM (0xC137000FL) +#endif /* STATUS_SIGNAL_TERM */ + + exception_record.ExceptionCode = (signal == SIGABRT) ? STATUS_SIGNAL_ABORT : STATUS_SIGNAL_TERM; + + DWORD dwThreadId = ::GetCurrentThreadId(); + + GenerateCrashDump(dwThreadId, &exception_ptrs); + + exit(1); + } + + // set_new_handler + void __cdecl NewOperatorHandler() + { + EXCEPTION_RECORD exception_record = {}; + CONTEXT exception_context = {}; + EXCEPTION_POINTERS exception_ptrs = { &exception_record, &exception_context }; + + ::RtlCaptureContext(&exception_context); + +#ifndef STATUS_NEW_FAILED +#define STATUS_NEW_FAILED (0xC1370010L) +#endif /* STATUS_NEW_FAILED */ + + exception_record.ExceptionCode = static_cast(STATUS_NEW_FAILED); + + DWORD dwThreadId = ::GetCurrentThreadId(); + + GenerateCrashDump(dwThreadId, &exception_ptrs); + + exit(1); + } + + ////////////////////////////////////////////////////////////////////////// + // ¸¨Öú·½·¨ + void SetupCrashFilter() + { + SetUnhandledExceptionFilter(&ExceptionFilter); + _set_invalid_parameter_handler(&InvalidParameterHandler); + _set_purecall_handler(&PurecallHandler); + + signal(SIGABRT, &SignalHandler); + signal(SIGTERM, &SignalHandler); + + _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT); + + _set_new_mode(1); + set_new_handler(&NewOperatorHandler); + } +} + +namespace CrashDaemon +{ + void StartCrashClient(IN PrevWriteDumpCallback prev, IN PostWriteDumpCallback post) + { + g_PrevWriteDumpCallback = prev; + g_PostWriteDumpCallback = post; + + SetupCrashFilter(); + } +}; diff --git a/pool/shard001/C++/0023406_LayoutThemeFontProviderWin.cpp b/pool/shard001/C++/0023406_LayoutThemeFontProviderWin.cpp new file mode 100644 index 0000000000000000000000000000000000000000..35a7a4aad33505b22b2c378551661d7c8c733899 --- /dev/null +++ b/pool/shard001/C++/0023406_LayoutThemeFontProviderWin.cpp @@ -0,0 +1,135 @@ +/* + * Copyright (C) 2012 Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE 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/LayoutThemeFontProvider.h" + +#include "core/CSSValueKeywords.h" +#include "platform/fonts/FontCache.h" +#include "platform/fonts/FontDescription.h" +#include "platform/win/HWndDC.h" +#include "platform/win/SystemInfo.h" +#include "wtf/text/WTFString.h" + +#define SIZEOF_STRUCT_WITH_SPECIFIED_LAST_MEMBER(structName, member) \ + offsetof(structName, member) + \ + (sizeof static_cast(nullptr)->member) +#define NONCLIENTMETRICS_SIZE_PRE_VISTA \ + SIZEOF_STRUCT_WITH_SPECIFIED_LAST_MEMBER(NONCLIENTMETRICS, lfMessageFont) + +namespace blink { + +// Converts |points| to pixels. One point is 1/72 of an inch. +static float pointsToPixels(float points) +{ + float pixelsPerInch = 96.0f * FontCache::deviceScaleFactor(); + static const float pointsPerInch = 72.0f; + return points / pointsPerInch * pixelsPerInch; +} + +static bool getNonClientMetrics(NONCLIENTMETRICS* metrics) +{ + static UINT size = isWindowsVistaOrGreater() ? + sizeof(NONCLIENTMETRICS) : NONCLIENTMETRICS_SIZE_PRE_VISTA; + metrics->cbSize = size; + bool success = !!SystemParametersInfo(SPI_GETNONCLIENTMETRICS, size, metrics, 0); + ASSERT_UNUSED(success, success); + return success; +} + +// Return the height of system font |font| in pixels. We use this size by +// default for some non-form-control elements. +static float systemFontSize(const LOGFONT& font) +{ + float size = -font.lfHeight; + if (size < 0) { + HFONT hFont = CreateFontIndirect(&font); + if (hFont) { + HWndDC hdc(0); // What about printing? Is this the right DC? + if (hdc) { + HGDIOBJ hObject = SelectObject(hdc, hFont); + TEXTMETRIC tm; + GetTextMetrics(hdc, &tm); + SelectObject(hdc, hObject); + size = tm.tmAscent; + } + DeleteObject(hFont); + } + } + + // The "codepage 936" bit here is from Gecko; apparently this helps make + // fonts more legible in Simplified Chinese where the default font size is + // too small. + // + // FIXME: http://b/1119883 Since this is only used for "small caption", + // "menu", and "status bar" objects, I'm not sure how much this even + // matters. Plus the Gecko patch went in back in 2002, and maybe this + // isn't even relevant anymore. We should investigate whether this should + // be removed, or perhaps broadened to be "any CJK locale". + // + return ((size < 12.0f) && (GetACP() == 936)) ? 12.0f : size; +} + +// static +void LayoutThemeFontProvider::systemFont(CSSValueID systemFontID, FontStyle& fontStyle, FontWeight& fontWeight, float& fontSize, AtomicString& fontFamily) +{ + fontStyle = FontStyleNormal; + fontWeight = FontWeightNormal; + fontSize = s_defaultFontSize; + fontFamily = defaultGUIFont(); + + switch (systemFontID) { + case CSSValueSmallCaption: + fontSize = FontCache::smallCaptionFontHeight(); + fontFamily = FontCache::smallCaptionFontFamily(); + break; + case CSSValueMenu: + fontSize = FontCache::menuFontHeight(); + fontFamily = FontCache::menuFontFamily(); + break; + case CSSValueStatusBar: + fontSize = FontCache::statusFontHeight(); + fontFamily = FontCache::statusFontFamily(); + break; + case CSSValueWebkitMiniControl: + case CSSValueWebkitSmallControl: + case CSSValueWebkitControl: + // Why 2 points smaller? Because that's what Gecko does. + fontSize = s_defaultFontSize - pointsToPixels(2); + fontFamily = defaultGUIFont(); + break; + default: + fontSize = s_defaultFontSize; + fontFamily = defaultGUIFont(); + break; + } +} + +// static +void LayoutThemeFontProvider::setDefaultFontSize(int fontSize) +{ + s_defaultFontSize = static_cast(fontSize); +} + +} // namespace blink diff --git a/pool/shard001/C++/0023411_rigid_object.cpp b/pool/shard001/C++/0023411_rigid_object.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d760ae94887fcea1d03207bd5c1749a573c6db26 --- /dev/null +++ b/pool/shard001/C++/0023411_rigid_object.cpp @@ -0,0 +1,230 @@ +/*****************************************************************************/ +/* Copyright (c) 2015, Karl Pauwels */ +/* All rights reserved. */ +/* */ +/* Redistribution and use in source and binary forms, with or without */ +/* modification, are permitted provided that the following conditions */ +/* are met: */ +/* */ +/* 1. Redistributions of source code must retain the above copyright */ +/* notice, this list of conditions and the following disclaimer. */ +/* */ +/* 2. Redistributions in binary form must reproduce the above copyright */ +/* notice, this list of conditions and the following disclaimer in the */ +/* documentation and/or other materials provided with the distribution. */ +/* */ +/* 3. Neither the name of the copyright holder nor the names of its */ +/* contributors may be used to endorse or promote products derived from */ +/* this software without specific prior written permission. */ +/* */ +/* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS */ +/* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT */ +/* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR */ +/* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT */ +/* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, */ +/* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT */ +/* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, */ +/* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY */ +/* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT */ +/* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE */ +/* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ +/*****************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include + +#include + +#include + +namespace render { + +RigidObject::RigidObject(std::string file_name, + Ogre::SceneManager *scene_manager, int segment_ind) + : segment_ind_{ segment_ind }, scene_manager_{ scene_manager } { + Ogre::MeshPtr object_mesh = render::loadMeshFromResource(file_name); + entity_ = scene_manager_->createEntity(file_name); + Ogre::MaterialPtr mat = + Ogre::MaterialManager::getSingleton().getByName("textured"); + std::stringstream ss; + Ogre::MaterialPtr cloned_mat = mat->clone(ss.str()); + Ogre::Pass *pass = cloned_mat->getTechnique(0)->getPass(0); + Ogre::TextureUnitState *tex_unit = pass->createTextureUnitState(); + Ogre::MaterialPtr tmp = Ogre::MaterialManager::getSingleton().getByName( + object_mesh->getSubMesh(0)->getMaterialName()); + tex_unit->setTextureName(tmp->getTechnique(0) + ->getPass(0) + ->getTextureUnitState(0) + ->getTextureName()); + entity_->setMaterial(cloned_mat); + + texture_name_ = tex_unit->getTextureName(); + file_name_ = file_name; + + Ogre::SubEntity *pSub = entity_->getSubEntity(0); + // mark segment index for vertex shader + pSub->setCustomParameter(1, Ogre::Vector4(segment_ind_, 0, 0, 0)); + + visual_node_ = scene_manager_->getRootSceneNode()->createChildSceneNode(); + visual_node_->attachObject(entity_); + + // store the vertex positions + extractMeshPositions(object_mesh.get()); + // std::cout << "extracted " << positions_.size() << " vertices\n"; + + // compute the bounding box + computeBoundingBox(); +} + +RigidObject::~RigidObject() { + visual_node_->detachAllObjects(); + scene_manager_->destroyEntity(entity_); + scene_manager_->destroySceneNode(visual_node_); + // may still need to remove the materials but most seems to be cleaned up + Ogre::TextureManager::getSingleton().unload(texture_name_); + Ogre::TextureManager::getSingleton().remove(texture_name_); + Ogre::MeshManager::getSingleton().unload(file_name_); + Ogre::MeshManager::getSingleton().remove(file_name_); +} + +void RigidObject::setPose(const Ogre::Vector3 &position, + const Ogre::Quaternion &orientation) { + visual_node_->setPosition(position); + visual_node_->setOrientation(orientation); +} + +void RigidObject::setVisible(bool visible) { + visual_node_->setVisible(visible); +} + +void RigidObject::setSegmentIndex(int segment_ind) { + segment_ind_ = segment_ind; + + Ogre::SubEntity *pSub = entity_->getSubEntity(0); + // mark segment index for vertex shader + pSub->setCustomParameter(1, Ogre::Vector4(segment_ind_, 0, 0, 0)); +} + +void RigidObject::extractMeshPositions(const Ogre::Mesh *const mesh) { + bool added_shared = false; + size_t current_offset = 0; + size_t shared_offset = 0; + size_t next_offset = 0; + + n_positions_ = 0; + + // Calculate how many vertices and indices we're going to need + for (unsigned short i = 0; i < mesh->getNumSubMeshes(); ++i) { + Ogre::SubMesh *submesh = mesh->getSubMesh(i); + // We only need to add the shared vertices once + if (submesh->useSharedVertices) { + if (!added_shared) { + n_positions_ += mesh->sharedVertexData->vertexCount; + added_shared = true; + } + } else { + n_positions_ += submesh->vertexData->vertexCount; + } + } + + // Allocate space for the vertices + positions_.resize(3 * n_positions_); + + added_shared = false; + + // Run through the submeshes again, adding the data into the vector + for (unsigned short i = 0; i < mesh->getNumSubMeshes(); ++i) { + Ogre::SubMesh *submesh = mesh->getSubMesh(i); + + Ogre::VertexData *vertex_data = submesh->useSharedVertices + ? mesh->sharedVertexData + : submesh->vertexData; + + if ((!submesh->useSharedVertices) || + (submesh->useSharedVertices && !added_shared)) { + if (submesh->useSharedVertices) { + added_shared = true; + shared_offset = current_offset; + } + + const Ogre::VertexElement *posElem = + vertex_data->vertexDeclaration->findElementBySemantic( + Ogre::VES_POSITION); + + Ogre::HardwareVertexBufferSharedPtr vbuf = + vertex_data->vertexBufferBinding->getBuffer(posElem->getSource()); + + unsigned char *vertex = static_cast( + vbuf->lock(Ogre::HardwareBuffer::HBL_READ_ONLY)); + + // There is _no_ baseVertexPointerToElement() which takes an Ogre::Real or + // a double + // as second argument. So make it float, to avoid trouble when Ogre::Real + // will + // be compiled/typedefed as double: + // Ogre::Real* pReal; + float *pReal; + + for (size_t j = 0; j < vertex_data->vertexCount; + ++j, vertex += vbuf->getVertexSize()) { + posElem->baseVertexPointerToElement(vertex, &pReal); + Ogre::Vector3 pt(pReal[0], pReal[1], pReal[2]); + // vertices[current_offset + j] = (orient * (pt * scale)) + + // position; + size_t IND = 3 * (current_offset + j); + positions_.at(IND) = pt.x; + positions_.at(IND + 1) = pt.y; + // positions_.at(IND+2) = -pt.z; // flip z + positions_.at(IND + 2) = pt.z; + } + + vbuf->unlock(); + next_offset += vertex_data->vertexCount; + } + } +} + +void RigidObject::computeBoundingBox() { + _bounding_box.resize(8 * 3); + Eigen::Map vertices_f(getPositions().data(), 3, + getNPositions()); + Eigen::MatrixXd vertices; + vertices = vertices_f.cast(); + + // subtract vertices mean + Eigen::Vector3d mean_vertices = vertices.rowwise().mean(); + vertices = vertices - mean_vertices.replicate(1, getNPositions()); + + // compute eigenvector covariance matrix + Eigen::EigenSolver eigen_solver(vertices * + vertices.transpose()); + Eigen::MatrixXd real_eigenvectors = eigen_solver.eigenvectors().real(); + + // rotate centered vertices with inverse eigenvector matrix + vertices = real_eigenvectors.transpose() * vertices; + + // compute simple bounding box + auto mn = vertices.rowwise().minCoeff(); + auto mx = vertices.rowwise().maxCoeff(); + Eigen::Matrix bounding_box; + bounding_box << mn(0), mn(0), mn(0), mn(0), mx(0), mx(0), mx(0), mx(0), mn(1), + mn(1), mx(1), mx(1), mn(1), mn(1), mx(1), mx(1), mn(2), mx(2), mn(2), + mx(2), mn(2), mx(2), mn(2), mx(2); + + // rotate and translate bounding box back to original position + Eigen::Matrix3d rot_back = real_eigenvectors; + Eigen::Translation tra_back(mean_vertices); + Eigen::Transform t = tra_back * rot_back; + bounding_box = t * bounding_box; + + // convert to float + Eigen::Map bounding_box_f(_bounding_box.data(), 3, 8); + + bounding_box_f = bounding_box.cast(); +} +} diff --git a/pool/shard001/C++/0023416_rtd_callback.cpp b/pool/shard001/C++/0023416_rtd_callback.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1d004d20dcef2f7ea6291fa562937f960778ae70 --- /dev/null +++ b/pool/shard001/C++/0023416_rtd_callback.cpp @@ -0,0 +1,32 @@ + +#include "rtd_callback.h" + +CallbackImpl::CallbackImpl(){ + + Event_RTD_Update = OpenEvent( EVENT_MODIFY_STATE , false, _T("RTD_UPDATE") ); + + if( Event_RTD_Update == NULL ){ + throw "RTD_UPDATE Open error - " + GetLastError() ; + } +} + +HRESULT STDMETHODCALLTYPE CallbackImpl::UpdateNotify(){ + + if( Event_RTD_Update ) + SetEvent ( Event_RTD_Update ); // Signal Update + + return S_OK; +} + +HRESULT STDMETHODCALLTYPE CallbackImpl::Disconnect(){ + return S_OK; +} +HRESULT STDMETHODCALLTYPE CallbackImpl::get_HeartbeatInterval( long *value){ + *value=-1; + return S_OK; +} +HRESULT STDMETHODCALLTYPE CallbackImpl::put_HeartbeatInterval( long value ){ + return S_OK; +} + + diff --git a/pool/shard001/C++/0023421_command_allocator_pool.cc b/pool/shard001/C++/0023421_command_allocator_pool.cc new file mode 100644 index 0000000000000000000000000000000000000000..1738e534ff5c416768f8b4ffb232f9ec7e394edb --- /dev/null +++ b/pool/shard001/C++/0023421_command_allocator_pool.cc @@ -0,0 +1,63 @@ +#include "command_allocator_pool.h" + +#include "core/get.h" +#include "renderer/device.h" + +namespace blowbox +{ + //------------------------------------------------------------------------------------------------------ + CommandAllocatorPool::CommandAllocatorPool(D3D12_COMMAND_LIST_TYPE type) : + type_(type) + { + + } + + //------------------------------------------------------------------------------------------------------ + CommandAllocatorPool::~CommandAllocatorPool() + { + for (size_t i = 0; i < allocator_pool_.size(); i++) + { + allocator_pool_[i]->Release(); + } + + allocator_pool_.clear(); + } + + //------------------------------------------------------------------------------------------------------ + ID3D12CommandAllocator* CommandAllocatorPool::RequestAllocator(uint64_t completed_fence_value) + { + ID3D12CommandAllocator* allocator = nullptr; + + if (!available_allocators_.empty()) + { + auto pair = available_allocators_.front(); + + // if the found allocator's expiry fence point (TIME POINT) was earlier than the + // one that is currently requested (CURRENT TIME POINT), the allocator is no longer + // in use by the GPU, so we can re-use it. + if (pair.first <= completed_fence_value) + { + allocator = pair.second; + BLOWBOX_ASSERT_HR(allocator->Reset()); + available_allocators_.pop(); + } + } + + if (allocator == nullptr) + { + BLOWBOX_ASSERT_HR(Get::Device()->Get()->CreateCommandAllocator(type_, IID_PPV_ARGS(&allocator))); + wchar_t allocator_name[32]; + swprintf(allocator_name, 32, L"CommandAllocator %zu", allocator_pool_.size()); + allocator->SetName(allocator_name); + allocator_pool_.push_back(allocator); + } + + return allocator; + } + + //------------------------------------------------------------------------------------------------------ + void CommandAllocatorPool::DiscardAllocator(uint64_t fence_value, ID3D12CommandAllocator* allocator) + { + available_allocators_.push(eastl::make_pair(fence_value, allocator)); + } +} \ No newline at end of file diff --git a/pool/shard001/C++/0023423_max-points-on-a-line.cpp b/pool/shard001/C++/0023423_max-points-on-a-line.cpp new file mode 100644 index 0000000000000000000000000000000000000000..aea79362827bc11dd36437a5b9676ff2403fac53 --- /dev/null +++ b/pool/shard001/C++/0023423_max-points-on-a-line.cpp @@ -0,0 +1,102 @@ +#include +#include +#include +#include +#include +#include +#include + +struct Vector { + double x; + double y; + Vector() : x(0), y(0) {} + Vector(double a, double b) : x(a), y(b) {} + + bool operator > (const Vector& v) const + { + if (abs(this->x - v.x) < numeric_limits::epsilon()) { + //printf("y:%lf-%lf\n", this->y, v.y); + return this->y > v.y; + } + + + //printf("x:%lf-%lf\n", this->x, v.x); + return this->x > v.x; + } +}; + +class Solution { +public: + void getNormal(Point &a, Point &b, Vector &norm) { + double deltaX = a.x - b.x; + double deltaY = a.y - b.y; + double length = sqrt(pow(deltaY, 2) + pow(deltaX, 2)); + norm.x = deltaX != 0 ? deltaX / length : 0; + norm.y = deltaY != 0 ? deltaY / length : 0; + } + + int maxPoints(vector &points) { + if (points.size() < 3) { + return points.size(); + } + int max = 0; + unordered_map>> slopsHash; + unordered_map> dups; + Vector v; + for (int i = 0; i < points.size(); ++i) { + dups[points[i].x][points[i].y]++; + if (dups[points[i].x][points[i].y] > 1) { + continue; + } + + for (int j = i + 1; j < points.size(); ++j) { + if (points[i].x == points[j].x && points[i].y == points[j].y) { + continue; + } + + getNormal(points[i], points[j], v); + if (v.x < 0) { + v.x *= -1; + v.y *= -1; + } + + if (v.x == 0) { + v.y = abs(v.y); + } + + slopsHash[points[i].x][points[i].y].push_back(v); + } + } + + Vector u; + vector slops; + for (Point p : points) { + int cmax = dups[p.x][p.y]; + slops = slopsHash[p.x][p.y]; + if (slops.empty()) { + max = std::max(cmax, max); + continue; + } + cmax -= 1; + std::sort(slops.begin(), slops.end(), greater()); + Vector w = slops[0]; + cmax += 2; + max = std::max(cmax, max); + for (int j = 1; j < slops.size(); ++j) + { + u = slops[j]; + if (abs(w.x - u.x) < numeric_limits::epsilon() && + abs(w.y - u.y) < numeric_limits::epsilon()) { + cmax++; + } + else { + w = u; + cmax = 2; + } + max = std::max(cmax, max); + } + } + + return max; + } +}; \ No newline at end of file diff --git a/pool/shard001/C++/0023425_ssd_ftlparent.cpp b/pool/shard001/C++/0023425_ssd_ftlparent.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3da5a1110b0c5a0ceef6a08ed3517427e180308d --- /dev/null +++ b/pool/shard001/C++/0023425_ssd_ftlparent.cpp @@ -0,0 +1,93 @@ +/* Copyright 2011 Matias Bjørling */ + +/* ssd_ftlparent.cpp */ + +/* FlashSim 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. */ + +/* FlashSim 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 FlashSim. If not, see . */ + +/****************************************************************************/ + +/* + * Implements parent interface for all FTL implementations to use. + */ + +#include "ssd.h" + +using namespace ssd; + +// Initialization of the block layer. +//Block_manager *Block_manager::inst = NULL; + + +FtlParent::FtlParent(Controller &controller) : controller(controller) +{ + //Block_manager::instance_initialize(this); + //bm = new ssd::Block_manager(this); + bm = instance_initialize_BlockManager(); + + printf("FtlParent::FtlParent Number of addressable blocks: %u\n", NUMBER_OF_ADDRESSABLE_BLOCKS); + +} + + +ssd::Block_manager* FtlParent::instance_initialize_BlockManager() +{ + + this->bm = new ssd::Block_manager(this); + return bm; +} + +ssd::Block_manager* FtlParent::get_BlockManager() +{ + return bm; +} + + +ssd::ulong FtlParent::get_erases_remaining(const Address &address) const +{ + + return controller.get_erases_remaining(address); +} + +void FtlParent::get_least_worn(Address &address) const +{ + controller.get_least_worn(address); + + return; +} + +enum page_state FtlParent::get_state(const Address &address) const +{ + return controller.get_state(address); +} + +enum block_state FtlParent::get_block_state(const Address &address) const +{ + return controller.get_block_state(address); +} + +Block *FtlParent::get_block_pointer(const Address &address) +{ + return controller.get_block_pointer(address); +} + +void FtlParent::cleanup_block(Event &event, Block *block) +{ + assert(false); + return; +} + +void FtlParent::print_ftl_statistics() +{ + return; +} diff --git a/pool/shard001/C++/0023430_wheelspeed_6a_test.cc b/pool/shard001/C++/0023430_wheelspeed_6a_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..9f82da0a56d341ac344e8b13d4f1880a80744efe --- /dev/null +++ b/pool/shard001/C++/0023430_wheelspeed_6a_test.cc @@ -0,0 +1,45 @@ +/****************************************************************************** + * 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/canbus/vehicle/lincoln/protocol/wheelspeed_6a.h" + +#include "gtest/gtest.h" + +namespace apollo { +namespace canbus { +namespace lincoln { + +TEST(Wheelspeed6aTest, General) { + Wheelspeed6a wheelspeed; + uint8_t data[8] = {0x61, 0x62, 0x63, 0x64, 0x51, 0x52, 0x53, 0x54}; + int32_t length = 8; + ChassisDetail cd; + struct timeval timestamp; + wheelspeed.Parse(data, length, timestamp, &cd); + + EXPECT_TRUE(cd.vehicle_spd().is_wheel_spd_fl_valid()); + EXPECT_DOUBLE_EQ(cd.vehicle_spd().wheel_spd_rr(), 215.87); + EXPECT_TRUE(cd.vehicle_spd().is_wheel_spd_fr_valid()); + EXPECT_DOUBLE_EQ(cd.vehicle_spd().wheel_spd_rl(), 210.73); + EXPECT_TRUE(cd.vehicle_spd().is_wheel_spd_rl_valid()); + EXPECT_DOUBLE_EQ(cd.vehicle_spd().wheel_spd_fr(), 256.99); + EXPECT_TRUE(cd.vehicle_spd().is_wheel_spd_rr_valid()); + EXPECT_DOUBLE_EQ(cd.vehicle_spd().wheel_spd_fl(), 251.85); +} + +} // namespace lincoln +} // namespace canbus +} // namespace apollo diff --git a/pool/shard001/C++/0023445_stratholme.cpp b/pool/shard001/C++/0023445_stratholme.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6b6bbe13cbd00919933f0b4fef2c12dd21165050 --- /dev/null +++ b/pool/shard001/C++/0023445_stratholme.cpp @@ -0,0 +1,282 @@ +/* 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, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +/* ScriptData +SDName: Stratholme +SD%Complete: 100 +SDComment: Misc mobs for instance. pGo-script to apply aura and start event for quest 8945 +SDCategory: Stratholme +EndScriptData */ + +/* ContentData +go_gauntlet_gate +mob_freed_soul +mob_restless_soul +mobs_spectral_ghostly_citizen +EndContentData */ + +#include "ScriptedPch.h" +#include "stratholme.h" + +/*###### +## go_gauntlet_gate (this is the _first_ of the gauntlet gates, two exist) +######*/ + +bool GOHello_go_gauntlet_gate(Player* pPlayer, GameObject* pGo) +{ + ScriptedInstance* pInstance = pGo->GetInstanceData(); + + if (!pInstance) + return false; + + if (pInstance->GetData(TYPE_BARON_RUN) != NOT_STARTED) + return false; + + if (Group *pGroup = pPlayer->GetGroup()) + { + for (GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next()) + { + Player* pGroupie = itr->getSource(); + if (!pGroupie) + continue; + + if (pGroupie->GetQuestStatus(QUEST_DEAD_MAN_PLEA) == QUEST_STATUS_INCOMPLETE && + !pGroupie->HasAura(SPELL_BARON_ULTIMATUM) && + pGroupie->GetMap() == pGo->GetMap()) + pGroupie->CastSpell(pGroupie,SPELL_BARON_ULTIMATUM,true); + } + } else if (pPlayer->GetQuestStatus(QUEST_DEAD_MAN_PLEA) == QUEST_STATUS_INCOMPLETE && + !pPlayer->HasAura(SPELL_BARON_ULTIMATUM) && + pPlayer->GetMap() == pGo->GetMap()) + pPlayer->CastSpell(pPlayer,SPELL_BARON_ULTIMATUM,true); + + pInstance->SetData(TYPE_BARON_RUN,IN_PROGRESS); + return false; +} + +/*###### +## mob_freed_soul +######*/ + +//Possibly more of these quotes around. +#define SAY_ZAPPED0 -1329000 +#define SAY_ZAPPED1 -1329001 +#define SAY_ZAPPED2 -1329002 +#define SAY_ZAPPED3 -1329003 + +struct mob_freed_soulAI : public ScriptedAI +{ + mob_freed_soulAI(Creature *c) : ScriptedAI(c) {} + + void Reset() + { + DoScriptText(RAND(SAY_ZAPPED0,SAY_ZAPPED1,SAY_ZAPPED2,SAY_ZAPPED3), m_creature); + } + + void EnterCombat(Unit* who) {} +}; + +CreatureAI* GetAI_mob_freed_soul(Creature* pCreature) +{ + return new mob_freed_soulAI (pCreature); +} + +/*###### +## mob_restless_soul +######*/ + +#define SPELL_EGAN_BLASTER 17368 +#define SPELL_SOUL_FREED 17370 +#define QUEST_RESTLESS_SOUL 5282 +#define ENTRY_RESTLESS 11122 +#define ENTRY_FREED 11136 + +struct mob_restless_soulAI : public ScriptedAI +{ + mob_restless_soulAI(Creature *c) : ScriptedAI(c) {} + + uint64 Tagger; + uint32 Die_Timer; + bool Tagged; + + void Reset() + { + Tagger = 0; + Die_Timer = 5000; + Tagged = false; + } + + void EnterCombat(Unit* who) {} + + void SpellHit(Unit *caster, const SpellEntry *spell) + { + if (caster->GetTypeId() == TYPEID_PLAYER) + { + if (!Tagged && spell->Id == SPELL_EGAN_BLASTER && CAST_PLR(caster)->GetQuestStatus(QUEST_RESTLESS_SOUL) == QUEST_STATUS_INCOMPLETE) + { + Tagged = true; + Tagger = caster->GetGUID(); + } + } + } + + void JustSummoned(Creature *summoned) + { + summoned->CastSpell(summoned,SPELL_SOUL_FREED,false); + } + + void JustDied(Unit* Killer) + { + if (Tagged) + m_creature->SummonCreature(ENTRY_FREED, m_creature->GetPositionX(), m_creature->GetPositionY(), m_creature->GetPositionZ(), m_creature->GetOrientation(), TEMPSUMMON_TIMED_DESPAWN, 300000); + } + + void UpdateAI(const uint32 diff) + { + if (Tagged) + { + if (Die_Timer <= diff) + { + if (Unit* pTemp = Unit::GetUnit(*m_creature,Tagger)) + { + CAST_PLR(pTemp)->KilledMonsterCredit(ENTRY_RESTLESS, m_creature->GetGUID()); + m_creature->Kill(m_creature); + } + } else Die_Timer -= diff; + } + } +}; + +CreatureAI* GetAI_mob_restless_soul(Creature* pCreature) +{ + return new mob_restless_soulAI (pCreature); +} + +/*###### +## mobs_spectral_ghostly_citizen +######*/ + +enum eGhostlyCitizenSpells +{ + SPELL_HAUNTING_PHANTOM = 16336, + SPELL_SLAP = 6754 +}; + +struct mobs_spectral_ghostly_citizenAI : public ScriptedAI +{ + mobs_spectral_ghostly_citizenAI(Creature *c) : ScriptedAI(c) {} + + uint32 Die_Timer; + bool Tagged; + + void Reset() + { + Die_Timer = 5000; + Tagged = false; + } + + void EnterCombat(Unit* who) {} + + void SpellHit(Unit *caster, const SpellEntry *spell) + { + if (!Tagged && spell->Id == SPELL_EGAN_BLASTER) + Tagged = true; + } + + void JustDied(Unit* Killer) + { + if (Tagged) + { + for (uint32 i = 1; i <= 4; ++i) + { + //100%, 50%, 33%, 25% chance to spawn + if (urand(1,i) == 1) + DoSummon(ENTRY_RESTLESS, me, 20.0f, 600000); + } + } + } + + void UpdateAI(const uint32 diff) + { + if (Tagged) + { + if (Die_Timer <= diff) + m_creature->Kill(m_creature); + else Die_Timer -= diff; + } + + if (!UpdateVictim()) + return; + + DoMeleeAttackIfReady(); + } + + void ReceiveEmote(Player* pPlayer, uint32 emote) + { + switch(emote) + { + case TEXTEMOTE_DANCE: + EnterEvadeMode(); + break; + case TEXTEMOTE_RUDE: + if (m_creature->IsWithinDistInMap(pPlayer, 5)) + DoCast(pPlayer, SPELL_SLAP, false); + else + m_creature->HandleEmoteCommand(EMOTE_ONESHOT_RUDE); + break; + case TEXTEMOTE_WAVE: + m_creature->HandleEmoteCommand(EMOTE_ONESHOT_WAVE); + break; + case TEXTEMOTE_BOW: + m_creature->HandleEmoteCommand(EMOTE_ONESHOT_BOW); + break; + case TEXTEMOTE_KISS: + m_creature->HandleEmoteCommand(EMOTE_ONESHOT_FLEX); + break; + } + } +}; + +CreatureAI* GetAI_mobs_spectral_ghostly_citizen(Creature* pCreature) +{ + return new mobs_spectral_ghostly_citizenAI (pCreature); +} + +void AddSC_stratholme() +{ + Script *newscript; + + newscript = new Script; + newscript->Name = "go_gauntlet_gate"; + newscript->pGOHello = &GOHello_go_gauntlet_gate; + newscript->RegisterSelf(); + + newscript = new Script; + newscript->Name = "mob_freed_soul"; + newscript->GetAI = &GetAI_mob_freed_soul; + newscript->RegisterSelf(); + + newscript = new Script; + newscript->Name = "mob_restless_soul"; + newscript->GetAI = &GetAI_mob_restless_soul; + newscript->RegisterSelf(); + + newscript = new Script; + newscript->Name = "mobs_spectral_ghostly_citizen"; + newscript->GetAI = &GetAI_mobs_spectral_ghostly_citizen; + newscript->RegisterSelf(); +} + diff --git a/pool/shard001/C++/0023448_1005.cc b/pool/shard001/C++/0023448_1005.cc new file mode 100644 index 0000000000000000000000000000000000000000..81726d47068820030c6ea4a5ffefe3ee04e4dff0 --- /dev/null +++ b/pool/shard001/C++/0023448_1005.cc @@ -0,0 +1,39 @@ +#include +#include +#include + +using namespace std; + +double M_PI0=3.141593; + +/* + delta=50平方単位増加後の半径の増加した量 + length=もとの半径の長さ + M_PI*(length+delta)*(length+delta)/2-M_PI*length*length/2=50 + delta=-length+sqrt((100+M_PI*length*length)/M_PI) + */ +int main(void){ + int n; + cin >> n; + for(int i=0;i> x >> y; + double delta; + double length=0; + double distance=sqrt(x*x+y*y); + //cout << "distance:" << distance < +#include +#include + +struct TestT { + int x; + + TestT() noexcept : x(10) {} + TestT(const TestT& v) noexcept : x(v.x) {} + TestT(int, int t) noexcept : x(t) {} + + ~TestT() { x = 0; } + + TestT* operator&() const noexcept + { + return nullptr; + } +}; + +inline bool operator==(TestT x, TestT y) noexcept +{ + return x.x == y.x; +} + +BOOST_AUTO_TEST_CASE(alloctor_int) +{ + mstd::allocator alloc; + + auto p = alloc.allocate(10); + + BOOST_REQUIRE(!std::all_of(p, p + 10, [](int x){ return x == 0; })); + + std::fill_n(p, 10, 100); + BOOST_REQUIRE_EQUAL(std::count(p, p + 10, 100), 10); + + BOOST_REQUIRE_EQUAL(alloc.address(*p), p); + BOOST_REQUIRE_EQUAL(alloc.address(*(p + 1)), p + 1); + + alloc.deallocate(p); +} + +BOOST_AUTO_TEST_CASE(allocator_class) +{ + mstd::allocator alloc; + + auto x = alloc.allocate(1); + + BOOST_REQUIRE(x); + BOOST_CHECK_NE(x->x, 10); + + alloc.construct(x); + BOOST_CHECK_EQUAL(x->x, 10); + + alloc.destroy(x); + BOOST_CHECK_EQUAL(x->x, 0); + + for (auto t: {3, 4, 5, 6}) { + alloc.construct(x, 0, t); + BOOST_CHECK_EQUAL(x->x, t); + + alloc.destroy(x); + BOOST_CHECK_EQUAL(x->x, 0); + } + + TestT cp{0, 100}; + alloc.construct(x, cp); + BOOST_CHECK_EQUAL(x->x, 100); + + BOOST_REQUIRE_EQUAL(&cp, static_cast(nullptr)); + + BOOST_REQUIRE_EQUAL(x, alloc.address(*x)); + + alloc.deallocate(x); +} + +BOOST_AUTO_TEST_CASE(construct) +{ + mstd::allocator alloc; + + constexpr auto sz = 10; + constexpr auto val = 3; + + auto p = alloc.allocate(sz); + + std::fill_n(p, sz, val); + BOOST_REQUIRE_EQUAL(std::count(p, p + sz, val), sz); + + mstd::destroy(p, p + sz); + BOOST_REQUIRE_EQUAL(std::count(p, p + sz, val), sz); + + alloc.deallocate(p); + + mstd::allocator alloc2; + auto q = alloc2.allocate(sz); + std::uninitialized_fill_n(q, sz, TestT{}); + + BOOST_REQUIRE_EQUAL(std::count(q, q + sz, TestT{}), sz); + + mstd::destroy(q, q + sz); + BOOST_REQUIRE_EQUAL(std::count(q, q + sz, TestT{0, 0}), sz); + + alloc2.deallocate(q); +} diff --git a/pool/shard001/C++/0023457_KeypadDialog.cpp b/pool/shard001/C++/0023457_KeypadDialog.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8289927f389c5c66413d0dfb8f9808b5125f84aa --- /dev/null +++ b/pool/shard001/C++/0023457_KeypadDialog.cpp @@ -0,0 +1,217 @@ + +/* Copyright (C) 2012 - Alex Lee, 9V1Al +* modifications of the original program by John Melton +* 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 Pl +*/ + +#include "KeypadDialog.h" +#include "ui_KeypadDialog.h" + +#include + + +KeypadDialog::KeypadDialog(QWidget *parent) : + QDialog(parent), + ui(new Ui::KeypadDialog) +{ + ui->setupUi(this); + + ui->frequency->setStyleSheet("QLabel { background-color : black; color : green; }"); + + + connect(ui->pushButton_0,SIGNAL(clicked()),this,SLOT(key_0())); + connect(ui->pushButton_1,SIGNAL(clicked()),this,SLOT(key_1())); + connect(ui->pushButton_2,SIGNAL(clicked()),this,SLOT(key_2())); + connect(ui->pushButton_3,SIGNAL(clicked()),this,SLOT(key_3())); + connect(ui->pushButton_4,SIGNAL(clicked()),this,SLOT(key_4())); + connect(ui->pushButton_5,SIGNAL(clicked()),this,SLOT(key_5())); + connect(ui->pushButton_6,SIGNAL(clicked()),this,SLOT(key_6())); + connect(ui->pushButton_7,SIGNAL(clicked()),this,SLOT(key_7())); + connect(ui->pushButton_8,SIGNAL(clicked()),this,SLOT(key_8())); + connect(ui->pushButton_9,SIGNAL(clicked()),this,SLOT(key_9())); + connect(ui->pushButton_period,SIGNAL(clicked()),this,SLOT(key_period())); + + connect(ui->buttonBox,SIGNAL(clicked(QAbstractButton*)),this,SLOT(clicked(QAbstractButton*))); + + ui->buttonBox->button(QDialogButtonBox::Ok)->setFocus(); + + frequency=""; + showFrequency(); +} + +KeypadDialog::~KeypadDialog() +{ + delete ui; +} + +long long KeypadDialog::getFrequency() { + return (long long)(frequency.toDouble()*1000000.0); +} + +void KeypadDialog::clear() { + frequency=""; + showFrequency(); +} + +void KeypadDialog::commitFrequency() { + if ((long long)(frequency.toDouble() * 1000000.0)!=0) + emit setKeypadFrequency((long long)(frequency.toDouble() * 1000000.0)); +} + +void KeypadDialog::clicked(QAbstractButton* button) { + qDebug()<<"KeypadDialog::clicked "<text(); + if(button->text()=="&OK") { + commitFrequency(); + } else if(button->text()=="Reset") { + frequency=""; + showFrequency(); + } else { + } +} + +void KeypadDialog::key_0() { + //frequency=frequency*10; + frequency.append("0"); + showFrequency(); +} + +void KeypadDialog::key_1() { + //frequency=(frequency*10)+1; + frequency.append("1"); + showFrequency(); +} + +void KeypadDialog::key_2() { + //frequency=(frequency*10)+2; + frequency.append("2"); + showFrequency(); +} + +void KeypadDialog::key_3() { + //frequency=(frequency*10)+3; + frequency.append("3"); + showFrequency(); +} + +void KeypadDialog::key_4() { + //frequency=(frequency*10)+4; + frequency.append("4"); + showFrequency(); +} + +void KeypadDialog::key_5() { + //frequency=(frequency*10)+5; + frequency.append("5"); + showFrequency(); +} + +void KeypadDialog::key_6() { + //frequency=(frequency*10)+6; + frequency.append("6"); + showFrequency(); +} + +void KeypadDialog::key_7() { + //frequency=(frequency*10)+7; + frequency.append("7"); + showFrequency(); +} + +void KeypadDialog::key_8() { + //frequency=(frequency*10)+8; + frequency.append("8"); + showFrequency(); +} + +void KeypadDialog::key_9() { + //frequency=(frequency*10)+9; + frequency.append("9"); + showFrequency(); +} + +void KeypadDialog::key_period() { + //frequency=frequency*1000; + if(frequency.count(".")==0) { + frequency.append("."); + showFrequency(); + } +} + +void KeypadDialog::keyPressEvent(QKeyEvent *event) { + switch (event->key()) { + case Qt::Key_0: + frequency.append("0"); + showFrequency(); + break; + case Qt::Key_1: + frequency.append("1"); + showFrequency(); + break; + case Qt::Key_2: + frequency.append("2"); + showFrequency(); + break; + case Qt::Key_3: + frequency.append("3"); + showFrequency(); + break; + case Qt::Key_4: + frequency.append("4"); + showFrequency(); + break; + case Qt::Key_5: + frequency.append("5"); + showFrequency(); + break; + case Qt::Key_6: + frequency.append("6"); + showFrequency(); + break; + case Qt::Key_7: + frequency.append("7"); + showFrequency(); + break; + case Qt::Key_8: + frequency.append("8"); + showFrequency(); + break; + case Qt::Key_9: + frequency.append("9"); + showFrequency(); + break; + case Qt::Key_Period: + if (frequency.count(".") == 0) { + frequency.append("."); + showFrequency(); + } + break; + + case Qt::Key_Backspace: + if (frequency.length() > 0) { + frequency.remove(frequency.length()-1, 1); + showFrequency(); + } + break; + + default: + QDialog::keyPressEvent(event); + } +} + +void KeypadDialog::showFrequency() { + //QString f; + //f.sprintf("%lld.%03lld.%03lld",frequency/1000000,frequency%1000000/1000,frequency%1000); + ui->frequency->setText(frequency); +} diff --git a/pool/shard001/C++/0023463_enter_world_request_wracDetail.cpp b/pool/shard001/C++/0023463_enter_world_request_wracDetail.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f3b7bd3c59d32e25e3aa2887ccfd81da285da606 --- /dev/null +++ b/pool/shard001/C++/0023463_enter_world_request_wracDetail.cpp @@ -0,0 +1,27 @@ +#include <_enter_world_request_wracDetail.hpp> +#include + + +START_ATF_NAMESPACE + namespace Detail + { + Info::_enter_world_request_wracsize2_ptr _enter_world_request_wracsize2_next(nullptr); + Info::_enter_world_request_wracsize2_clbk _enter_world_request_wracsize2_user(nullptr); + + int _enter_world_request_wracsize2_wrapper(struct _enter_world_request_wrac* _this) + { + return _enter_world_request_wracsize2_user(_this, _enter_world_request_wracsize2_next); + }; + + ::std::array _enter_world_request_wrac_functions = + { + _hook_record { + (LPVOID)0x14011f240L, + (LPVOID *)&_enter_world_request_wracsize2_user, + (LPVOID *)&_enter_world_request_wracsize2_next, + (LPVOID)cast_pointer_function(_enter_world_request_wracsize2_wrapper), + (LPVOID)cast_pointer_function((int(_enter_world_request_wrac::*)())&_enter_world_request_wrac::size) + }, + }; + }; // end namespace Detail +END_ATF_NAMESPACE diff --git a/pool/shard001/C++/0023468_dircompleter.cpp b/pool/shard001/C++/0023468_dircompleter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..749305e1dd65652c05e9b364b0a222508b004baa --- /dev/null +++ b/pool/shard001/C++/0023468_dircompleter.cpp @@ -0,0 +1,41 @@ +/* + * Copyright (C) 2015 Thomas Lübking + * This file is part of Phototonic Image Viewer. + * + * Phototonic 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. + * + * Phototonic 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 Phototonic. If not, see . + */ + +#include +#include "dircompleter.h" + +DirCompleter::DirCompleter(QObject *parent) : QCompleter(parent) +{ + QDirModel *model = new QDirModel; + model->setFilter(QDir::AllDirs | QDir::NoDotAndDotDot); + model->setLazyChildCount(true); + setModel(model); +} + +QString DirCompleter::pathFromIndex(const QModelIndex &index) const +{ + return QCompleter::pathFromIndex(index) + "/"; +} + +QStringList DirCompleter::splitPath(const QString &path) const +{ + if (path.startsWith("~")) { + return QCompleter::splitPath(QString(path).replace(0, 1, QDir::homePath())); + } + return QCompleter::splitPath(path); +} diff --git a/pool/shard001/C++/0023470_WindowGeometry.cc b/pool/shard001/C++/0023470_WindowGeometry.cc new file mode 100644 index 0000000000000000000000000000000000000000..28dd6f923facf551b5857035a6fca9e851f90d72 --- /dev/null +++ b/pool/shard001/C++/0023470_WindowGeometry.cc @@ -0,0 +1,55 @@ +/* + * surf - visualizing algebraic curves and algebraic surfaces + * Copyright (C) 1996-1997 Friedrich-Alexander-Universitaet + * Erlangen-Nuernberg + * 1997-2000 Johannes Gutenberg-Universitaet Mainz + * Authors: Stephan Endrass, Hans Huelf, Ruediger Oertel, + * Kai Schneider, Ralf Schmitt, Johannes Beigel + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + * + */ + + +#include "WindowGeometry.h" + +WindowGeometry::WindowGeometry (int w, int h) +{ + setSize(w,h); +} + +void WindowGeometry::setSize(int w, int h) +{ + width = w; + height = h; + setFactor(); +} + +void WindowGeometry::setFactor () +{ + if( width == height ) { + width_factor = 10.0; + height_factor = 10.0; + } else if( width < height ) { + width_factor = 10.0; + height_factor = 10.0*height/width; + } else { + width_factor = 10.0*width/height; + height_factor = 10.0; + } + + toUserXFactor = 2*width_factor/(double) (width-1); + toUserYFactor = -2*height_factor/(double)(height-1); +} diff --git a/pool/shard001/C++/0023471_Mesh.cpp b/pool/shard001/C++/0023471_Mesh.cpp new file mode 100644 index 0000000000000000000000000000000000000000..66ef802abeb6f310ce1df856e900e3ea26d7a063 --- /dev/null +++ b/pool/shard001/C++/0023471_Mesh.cpp @@ -0,0 +1,36 @@ +#include "Assets/Mesh.h" +#include "Utilities/IO/Mesh_IO.h" +#include "Engine.h" +#include "glm/glm.hpp" +#include "glm/geometric.hpp" + + +Shared_Mesh::Shared_Mesh(Engine& engine, const std::string& filename, const bool& threaded) +{ + auto newAsset = std::dynamic_pointer_cast(engine.getManager_Assets().shareAsset( + typeid(Mesh).name(), + filename, + [&engine, filename]() { return std::make_shared(engine, filename); }, + threaded + )); + swap(newAsset); +} + +Mesh::Mesh(Engine& engine, const std::string& filename) : Asset(engine, filename) {} + +void Mesh::initialize() +{ + if (!Mesh_IO::Import_Model(m_engine, getFileName(), m_geometry)) { + // Create hard-coded alternative + m_geometry.vertices = { glm::vec3(-1, -1, 0), glm::vec3(1, -1, 0), glm::vec3(1, 1, 0),glm::vec3(-1, -1, 0), glm::vec3(1, 1, 0), glm::vec3(-1, 1, 0) }; + m_geometry.normals = { glm::vec3(1, 0, 0), glm::vec3(1, 0, 0), glm::vec3(1, 0, 0), glm::vec3(1, 0, 0), glm::vec3(1, 0, 0), glm::vec3(1, 0, 0) }; + m_geometry.tangents = { glm::vec3(0, 1, 0), glm::vec3(0, 1, 0), glm::vec3(0, 1, 0), glm::vec3(0, 1, 0), glm::vec3(0, 1, 0), glm::vec3(0, 1, 0) }; + m_geometry.bitangents = { glm::vec3(0, 0, 1), glm::vec3(0, 0, 1), glm::vec3(0, 0, 1), glm::vec3(0, 0, 1), glm::vec3(0, 0, 1), glm::vec3(0, 0, 1) }; + m_geometry.texCoords = { glm::vec2(0, 0), glm::vec2(0, 0), glm::vec2(0, 0), glm::vec2(0, 0), glm::vec2(0, 0), glm::vec2(0, 0) }; + m_geometry.materialIndices = { 0U, 0U, 0U, 0U, 0U, 0U }; + m_geometry.bones.resize(m_geometry.vertices.size()); + m_geometry.materials.emplace_back(Material_Strings{}); + } + + Asset::finalize(); +} \ No newline at end of file diff --git a/pool/shard001/C++/0023473_LogicalUnotFunction.cpp b/pool/shard001/C++/0023473_LogicalUnotFunction.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b76fcb1b173edf9cee73a9cd9ebd9c3dda5cec9e --- /dev/null +++ b/pool/shard001/C++/0023473_LogicalUnotFunction.cpp @@ -0,0 +1,46 @@ +#include "LogicalUnotFunction.h" +#include "TypedDagNode.h" + +namespace RevBayesCore { class DagNode; } +using namespace RevBayesCore; + +LogicalUnotFunction::LogicalUnotFunction(const TypedDagNode *l) : TypedFunction( new Boolean(false) ), + left( l ) +{ + // add the parameters as parents + this->addParameter( left ); + + update(); +} + + +LogicalUnotFunction::~LogicalUnotFunction( void ) { + // We don't delete the parameters, because they might be used somewhere else too. The model needs to do that! +} + + + +LogicalUnotFunction* LogicalUnotFunction::clone( void ) const +{ + + return new LogicalUnotFunction( *this ); +} + + +void LogicalUnotFunction::update( void ) +{ + + *(this->value) = !( left->getValue() ); + +} + + + +void LogicalUnotFunction::swapParameterInternal(const DagNode *oldP, const DagNode *newP) { + + if ( oldP == left ) { + left = static_cast* >( newP ); + } + +} + diff --git a/pool/shard001/C++/0023476_SVGResourcesCache.cpp b/pool/shard001/C++/0023476_SVGResourcesCache.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b1adc7e6e8ed0ab3df881dc8d5f483ec91cfc5d2 --- /dev/null +++ b/pool/shard001/C++/0023476_SVGResourcesCache.cpp @@ -0,0 +1,172 @@ +/* + * Copyright (C) Research In Motion Limited 2010. All rights reserved. + * + * 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" +#include "core/layout/svg/SVGResourcesCache.h" + +#include "core/HTMLNames.h" +#include "core/layout/svg/LayoutSVGResourceContainer.h" +#include "core/layout/svg/SVGResources.h" +#include "core/layout/svg/SVGResourcesCycleSolver.h" +#include "core/svg/SVGDocumentExtensions.h" + +namespace blink { + +SVGResourcesCache::SVGResourcesCache() +{ +} + +SVGResourcesCache::~SVGResourcesCache() +{ +} + +void SVGResourcesCache::addResourcesFromLayoutObject(LayoutObject* object, const ComputedStyle& style) +{ + ASSERT(object); + ASSERT(!m_cache.contains(object)); + + const SVGComputedStyle& svgStyle = style.svgStyle(); + + // Build a list of all resources associated with the passed LayoutObject. + OwnPtr newResources = SVGResources::buildResources(object, svgStyle); + if (!newResources) + return; + + // Put object in cache. + SVGResources* resources = m_cache.set(object, newResources.release()).storedValue->value.get(); + + // Run cycle-detection _afterwards_, so self-references can be caught as well. + SVGResourcesCycleSolver solver(object, resources); + solver.resolveCycles(); + + // Walk resources and register the layout object as a client of each resource. + HashSet resourceSet; + resources->buildSetOfResources(resourceSet); + + for (auto* resourceContainer : resourceSet) + resourceContainer->addClient(object); +} + +void SVGResourcesCache::removeResourcesFromLayoutObject(LayoutObject* object) +{ + OwnPtr resources = m_cache.take(object); + if (!resources) + return; + + // Walk resources and unregister the layout object as a client of each resource. + HashSet resourceSet; + resources->buildSetOfResources(resourceSet); + + for (auto* resourceContainer : resourceSet) + resourceContainer->removeClient(object); +} + +static inline SVGResourcesCache& resourcesCache(Document& document) +{ + return document.accessSVGExtensions().resourcesCache(); +} + +SVGResources* SVGResourcesCache::cachedResourcesForLayoutObject(const LayoutObject* layoutObject) +{ + ASSERT(layoutObject); + return resourcesCache(layoutObject->document()).m_cache.get(layoutObject); +} + +void SVGResourcesCache::clientLayoutChanged(LayoutObject* object) +{ + SVGResources* resources = cachedResourcesForLayoutObject(object); + if (!resources) + return; + + // Invalidate the resources if either the LayoutObject itself changed, + // or we have filter resources, which could depend on the layout of children. + if (object->selfNeedsLayout() || resources->filter()) + resources->removeClientFromCache(object); +} + +static inline bool layoutObjectCanHaveResources(LayoutObject* layoutObject) +{ + ASSERT(layoutObject); + return layoutObject->node() && layoutObject->node()->isSVGElement() && !layoutObject->isSVGInlineText(); +} + +void SVGResourcesCache::clientStyleChanged(LayoutObject* layoutObject, StyleDifference diff, const ComputedStyle& newStyle) +{ + ASSERT(layoutObject); + ASSERT(layoutObject->node()); + ASSERT(layoutObject->node()->isSVGElement()); + + if (!diff.hasDifference() || !layoutObject->parent()) + return; + + // In this case the proper SVGFE*Element will decide whether the modified CSS properties require + // a relayout or paintInvalidation. + if (layoutObject->isSVGResourceFilterPrimitive() && !diff.needsLayout()) + return; + + // Dynamic changes of CSS properties like 'clip-path' may require us to recompute the associated + // resources for a LayoutObject. + // TODO(fs): Avoid passing in a useless StyleDifference, but instead compare oldStyle/newStyle + // to see which resources changed to be able to selectively rebuild individual resources, + // instead of all of them. + if (layoutObjectCanHaveResources(layoutObject)) { + SVGResourcesCache& cache = resourcesCache(layoutObject->document()); + cache.removeResourcesFromLayoutObject(layoutObject); + cache.addResourcesFromLayoutObject(layoutObject, newStyle); + } + + LayoutSVGResourceContainer::markForLayoutAndParentResourceInvalidation(layoutObject, false); +} + +void SVGResourcesCache::clientWasAddedToTree(LayoutObject* layoutObject, const ComputedStyle& newStyle) +{ + if (!layoutObject->node()) + return; + LayoutSVGResourceContainer::markForLayoutAndParentResourceInvalidation(layoutObject, false); + + if (!layoutObjectCanHaveResources(layoutObject)) + return; + SVGResourcesCache& cache = resourcesCache(layoutObject->document()); + cache.addResourcesFromLayoutObject(layoutObject, newStyle); +} + +void SVGResourcesCache::clientWillBeRemovedFromTree(LayoutObject* layoutObject) +{ + if (!layoutObject->node()) + return; + LayoutSVGResourceContainer::markForLayoutAndParentResourceInvalidation(layoutObject, false); + + if (!layoutObjectCanHaveResources(layoutObject)) + return; + SVGResourcesCache& cache = resourcesCache(layoutObject->document()); + cache.removeResourcesFromLayoutObject(layoutObject); +} + +void SVGResourcesCache::clientDestroyed(LayoutObject* layoutObject) +{ + ASSERT(layoutObject); + + SVGResources* resources = cachedResourcesForLayoutObject(layoutObject); + if (resources) + resources->removeClientFromCache(layoutObject); + SVGResourcesCache& cache = resourcesCache(layoutObject->document()); + cache.removeResourcesFromLayoutObject(layoutObject); +} + +} diff --git a/pool/shard001/C++/0023489_db_message_filter.cc b/pool/shard001/C++/0023489_db_message_filter.cc new file mode 100644 index 0000000000000000000000000000000000000000..766adbb1c7e74d6ee7bd0d00e845e31b8e7557e0 --- /dev/null +++ b/pool/shard001/C++/0023489_db_message_filter.cc @@ -0,0 +1,53 @@ +// Copyright (c) 2011 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/common/db_message_filter.h" + +#include "content/common/database_messages.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebDatabase.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebString.h" + +DBMessageFilter::DBMessageFilter() { +} + +bool DBMessageFilter::OnMessageReceived(const IPC::Message& message) { + bool handled = true; + IPC_BEGIN_MESSAGE_MAP(DBMessageFilter, message) + IPC_MESSAGE_HANDLER(DatabaseMsg_UpdateSize, OnDatabaseUpdateSize) + IPC_MESSAGE_HANDLER(DatabaseMsg_UpdateSpaceAvailable, + OnDatabaseUpdateSpaceAvailable) + IPC_MESSAGE_HANDLER(DatabaseMsg_ResetSpaceAvailable, + OnDatabaseResetSpaceAvailable) + IPC_MESSAGE_HANDLER(DatabaseMsg_CloseImmediately, + OnDatabaseCloseImmediately) + IPC_MESSAGE_UNHANDLED(handled = false) + IPC_END_MESSAGE_MAP() + return handled; +} + +void DBMessageFilter::OnDatabaseUpdateSize(const string16& origin_identifier, + const string16& database_name, + int64 database_size) { + WebKit::WebDatabase::updateDatabaseSize( + origin_identifier, database_name, database_size); +} + +void DBMessageFilter::OnDatabaseUpdateSpaceAvailable( + const string16& origin_identifier, + int64 space_available) { + WebKit::WebDatabase::updateSpaceAvailable( + origin_identifier, space_available); +} + +void DBMessageFilter::OnDatabaseResetSpaceAvailable( + const string16& origin_identifier) { + WebKit::WebDatabase::resetSpaceAvailable(origin_identifier); +} + +void DBMessageFilter::OnDatabaseCloseImmediately( + const string16& origin_identifier, + const string16& database_name) { + WebKit::WebDatabase::closeDatabaseImmediately( + origin_identifier, database_name); +} diff --git a/pool/shard001/C++/0023490_SessionBuildEnvironment.cpp b/pool/shard001/C++/0023490_SessionBuildEnvironment.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fd85e644cc7c65f2798a833cef62a0c257568322 --- /dev/null +++ b/pool/shard001/C++/0023490_SessionBuildEnvironment.cpp @@ -0,0 +1,237 @@ +/* + * SessionBuildEnvironment.cpp + * + * Copyright (C) 2009-12 by RStudio, Inc. + * + * Unless you have received this program directly from RStudio pursuant + * to the terms of a commercial license agreement with RStudio, then + * this program is licensed to you under the terms of version 3 of the + * GNU Affero General Public License. This program is distributed WITHOUT + * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, + * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the + * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. + * + */ + +#include +#include + +#include +#include + +#include +#include + +#include +#include +#include + +#include + +#include + +using namespace rstudio::core ; + +namespace rstudio { +namespace session { +namespace module_context { + +#ifdef _WIN32 + +namespace { + +r_util::RToolsInfo scanPathForRTools() +{ + // first confirm ls.exe is in Rtools + r_util::RToolsInfo noToolsFound; + FilePath lsPath = module_context::findProgram("ls.exe"); + if (lsPath.empty()) + return noToolsFound; + + // we have a candidate installPath + FilePath installPath = lsPath.parent().parent(); + core::system::ensureLongPath(&installPath); + if (!installPath.childPath("Rtools.txt").exists()) + return noToolsFound; + + // find the version path + FilePath versionPath = installPath.childPath("VERSION.txt"); + if (!versionPath.exists()) + return noToolsFound; + + // further verify that gcc is in Rtools + FilePath gccPath = module_context::findProgram("gcc.exe"); + if (!gccPath.exists()) + return noToolsFound; + if (!gccPath.parent().parent().parent().childPath("Rtools.txt").exists()) + return noToolsFound; + + // Rtools is in the path -- now crack the VERSION file + std::string contents; + Error error = core::readStringFromFile(versionPath, &contents); + if (error) + { + LOG_ERROR(error); + return noToolsFound; + } + + // extract the version + boost::algorithm::trim(contents); + boost::regex pattern("Rtools version (\\d\\.\\d\\d)[\\d\\.]+$"); + boost::smatch match; + if (boost::regex_search(contents, match, pattern)) + return r_util::RToolsInfo(match[1], installPath); + else + return noToolsFound; +} + +std::string formatPath(const FilePath& filePath) +{ + FilePath displayPath = filePath; + core::system::ensureLongPath(&displayPath); + return boost::algorithm::replace_all_copy( + displayPath.absolutePath(), "/", "\\"); +} + +template +bool doAddRtoolsToPathIfNecessary(T* pTarget, std::string* pWarningMessage) +{ + // can we find ls.exe and gcc.exe on the path? if so then + // we assume Rtools are already there (this is the same test + // used by devtools) + bool rToolsOnPath = false; + Error error = r::exec::RFunction(".rs.isRtoolsOnPath").call(&rToolsOnPath); + if (error) + LOG_ERROR(error); + if (rToolsOnPath) + { + // perform an extra check to see if the version on the path is not + // compatible with the currenly running version of R + r_util::RToolsInfo rTools = scanPathForRTools(); + if (!rTools.empty()) + { + if (!module_context::isRtoolsCompatible(rTools)) + { + boost::format fmt( + "WARNING: Rtools version %1% is on the PATH (intalled at %2%) " + "but is " + "not compatible with the currently running version of R." + "\n\nPlease download and install the appropriate version of " + "Rtools to ensure that packages are built correctly:" + "\n\nhttp://cran.rstudio.com/bin/windows/Rtools/" + "\n\nNote that in addition to installing a compatible verison you " + "also need to remove the incompatible version from your PATH"); + *pWarningMessage = boost::str( + fmt % rTools.name() % formatPath(rTools.installPath())); + } + } + + return false; + } + + // ok so scan for R tools + std::vector rTools; + error = core::r_util::scanRegistryForRTools(&rTools); + if (error) + { + LOG_ERROR(error); + return false; + } + + // enumerate them to see if we have a compatible version + // (go in reverse order for most recent first) + std::vector::const_reverse_iterator it = rTools.rbegin(); + for ( ; it != rTools.rend(); ++it) + { + if (module_context::isRtoolsCompatible(*it)) + { + r_util::prependToSystemPath(*it, pTarget); + return true; + } + } + + // if we found no version of rtools whatsoever then print warning and return + if (rTools.empty()) + { + *pWarningMessage = + "WARNING: Rtools is required to build R packages but is not " + "currently installed. " + "Please download and install the appropriate " + "version of Rtools before proceeding:\n\n" + "http://cran.rstudio.com/bin/windows/Rtools/"; + } + else + { + // Rtools installed but no compatible version, print a suitable warning + pWarningMessage->append( + "WARNING: Rtools is required to build R packages but no version " + "of Rtools compatible with the currently running version of R " + "was found. Note that the following incompatible version(s) " + "of Rtools were found:\n\n"); + + std::vector::const_iterator fwdIt = rTools.begin(); + for (; fwdIt != rTools.end(); ++fwdIt) + { + std::string path = formatPath(fwdIt->installPath()); + boost::format fmt(" - Rtools %1% (installed at %2%)\n"); + pWarningMessage->append(boost::str(fmt % fwdIt->name() % path)); + } + + pWarningMessage->append( + "\nPlease download and install the appropriate " + "version of Rtools before proceeding:\n\n" + "http://cran.rstudio.com/bin/windows/Rtools/"); + } + + return false; +} + + +} // anonymous namespace + +bool isRtoolsCompatible(const r_util::RToolsInfo& rTools) +{ + bool isCompatible = false; + Error error = r::exec::evaluateString(rTools.versionPredicate(), + &isCompatible); + if (error) + LOG_ERROR(error); + return isCompatible; +} + +bool addRtoolsToPathIfNecessary(std::string* pPath, + std::string* pWarningMessage) +{ + return doAddRtoolsToPathIfNecessary(pPath, pWarningMessage); +} + +bool addRtoolsToPathIfNecessary(core::system::Options* pEnvironment, + std::string* pWarningMessage) +{ + return doAddRtoolsToPathIfNecessary(pEnvironment, pWarningMessage); +} + + +#else + +bool isRtoolsCompatible(const r_util::RToolsInfo& rTools) +{ + return false; +} + +bool addRtoolsToPathIfNecessary(std::string* pPath, + std::string* pWarningMessage) +{ + return false; +} + +bool addRtoolsToPathIfNecessary(core::system::Options* pEnvironment, + std::string* pWarningMessage) +{ + return false; +} +#endif + +} // namespace module_context +} // namespace session +} // namespace rstudio diff --git a/pool/shard001/C++/0023492_Ring.cpp b/pool/shard001/C++/0023492_Ring.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5143c0b94b1a01279fce67b997ef9883a20ede93 --- /dev/null +++ b/pool/shard001/C++/0023492_Ring.cpp @@ -0,0 +1,185 @@ +// ƒŠƒ“ƒOƒNƒ‰ƒX +// 2016. 1.24 ƒvƒƒOƒ‰ƒ€ì¬ +// Author : SyunMizuno + + +#include "Ring.h" +#include "../../GameFramework/framework/Utility/Math/MathUtility.h" +#include "../../GameFramework/framework/Graphic/Graphics.h" + + +typedef struct { + Point3 vtx; + D3DCOLOR diffuse; + Point2 tex; +} VERTEX_RING; + +#define FVF_RING ( D3DFVF_XYZ | D3DFVF_DIFFUSE | D3DFVF_TEX1 ) + + + +/* // +// ƒRƒ“ƒXƒgƒ‰ƒNƒ^ // +// */ +Ring::Ring() : + m_fScrollSpeed(1.0f), + m_fRadius(1.0f), + m_fWeight(3.0f), + m_pTex(NULL) +{ + SetName("Ring"); + PreSet(); +} + + +/* // +// ƒfƒXƒgƒ‰ƒNƒ^ // +// */ +Ring::~Ring() { + +} + + +/* // +// XV // +// */ +void Ring::Update() { + if (m_tRing[POLYGON_NUM].Alpha >= 1.0f) + return; + + float alpha = m_tRing[0].Alpha; + + bool flg = true; + for (int i = 0; i < POLYGON_NUM + 1; ++i) { + if (flg) { + if (m_tRing[i].Alpha < 1.0f) + m_tRing[i].Alpha += (m_fScrollSpeed * Time::GetDeltaTime()); + } + float limit = 1.0f / POLYGON_NUM * (i + 1); + + // ŽŸ‚Ì’¸“_‚ðXVŠm”F + if (alpha >= limit) { + flg = true; + } else { + flg = false; + } + } +} + + +/* // +// •`‰æ // +// */ +void Ring::LateDraw() { + DWORD Cull, Light, dest; + + //----- ’¸“_ + VERTEX_RING Vertex[(POLYGON_NUM + 1) * 2]; + for (int i = 0, p = 0; i < POLYGON_NUM + 1; ++ i, p += 2) { + // F + Vertex[p].diffuse = + Vertex[p + 1].diffuse = Color(1.0f, 1.0f, 1.0f, m_tRing[i].Alpha); + // ’¸“_ + Vertex[p].vtx.x = + Vertex[p + 1].vtx.x = m_tRing[i].Pos.x; + Vertex[p].vtx.y = m_fWeight / 2.0f; + Vertex[p + 1].vtx.y = Vertex[p].vtx.y * -1.0f; + Vertex[p].vtx.z = + Vertex[p + 1].vtx.z = m_tRing[i].Pos.z; + // ƒeƒNƒXƒ`ƒƒ + Vertex[p].tex = Point2(m_tRing[i].Tex.x, 0.0f); + Vertex[p+1].tex = Point2(m_tRing[i].Tex.x, 1.0f); + } + + // ƒCƒ“ƒfƒbƒNƒX + unsigned short Index[(POLYGON_NUM + 1) * 2]; + for (int i = 0; i < (POLYGON_NUM + 1) * 2; ++ i) { + Index[i] = i; + } + + //----- •`‰æ + // Ý’è‚̕ۑ¶ + DWORD zwrite, texv; + LPDIRECT3DDEVICE9 pDevice = GetGraphics()->GetDevice(); + pDevice->GetRenderState(D3DRS_CULLMODE, &Cull); + pDevice->GetRenderState(D3DRS_LIGHTING, &Light); + pDevice->GetRenderState(D3DRS_DESTBLEND, &dest); + pDevice->GetRenderState(D3DRS_ZWRITEENABLE, &zwrite); + pDevice->GetSamplerState(0, D3DSAMP_ADDRESSV, &texv); + + // Ý’è‚̕ύX + pDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE); // ƒJƒŠƒ“ƒO‚ðÁ‚· + pDevice->SetRenderState(D3DRS_LIGHTING, FALSE); + pDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_ONE); + pDevice->SetRenderState(D3DRS_ZWRITEENABLE, FALSE); + pDevice->SetSamplerState(0, D3DSAMP_ADDRESSU, D3DTADDRESS_CLAMP); + + pDevice->SetTransform(D3DTS_WORLD, &GetTransform()->GetWorld()); + pDevice->SetFVF(FVF_RING); + pDevice->SetTexture(0, m_pTex); + pDevice->DrawIndexedPrimitiveUP( + D3DPT_TRIANGLESTRIP, + 0, + (POLYGON_NUM + 1) * 2, // ’¸“_” + POLYGON_NUM * 2, // –ʐ” + Index, // ƒCƒ“ƒfƒbƒNƒX + D3DFMT_INDEX16, + Vertex, // ’¸“_ + sizeof(VERTEX_RING)); + + // Ý’è‚ð–ß‚· + pDevice->SetRenderState(D3DRS_CULLMODE, Cull); + pDevice->SetRenderState(D3DRS_LIGHTING, Light); + pDevice->SetRenderState(D3DRS_DESTBLEND, dest); + pDevice->SetRenderState(D3DRS_ZWRITEENABLE, zwrite); + pDevice->SetSamplerState(0, D3DSAMP_ADDRESSV, texv); +} + + +/* // +// ”¼ŒaÝ’è // +// */ +void Ring::SetRadius(float r) { + m_fRadius = r; + PreSet(); +} + + +/* // +// ÄÝ’è // +// */ +void Ring::PreSet() { + float deg = 360.0f / POLYGON_NUM; + float buf = 1.0f / POLYGON_NUM; + for (int i = 0; i < POLYGON_NUM; i ++) { + m_tRing[i].Pos.x = m_fRadius * sinf(D3DXToRadian(i*deg)); + m_tRing[i].Pos.y = 0.0f; + m_tRing[i].Pos.z = m_fRadius * cosf(D3DXToRadian(i*deg)); + m_tRing[i].Tex = Point2(buf * (POLYGON_NUM - i), 0.0f); + m_tRing[i].Alpha = 0.0f; + } + m_tRing[POLYGON_NUM].Pos.x = m_fRadius * sinf(D3DXToRadian(0.0f)); + m_tRing[POLYGON_NUM].Pos.y = 0.0f; + m_tRing[POLYGON_NUM].Pos.z = m_fRadius * cosf(D3DXToRadian(0.0f)); + m_tRing[POLYGON_NUM].Tex = Point2(0.0f, 0.0f); + m_tRing[POLYGON_NUM].Alpha = 0.0f; +} + + +/* // +// ƒXƒNƒ[ƒ‹‘¬“xÝ’è // +// */ +void Ring::SetScrollSpeed(float v) { + if (v <= 0.0f) return; + m_fScrollSpeed = v; +} + + +/* // +// ƒŠƒZƒbƒg // +// */ +void Ring::Reset() { + for (int i = 0; i < POLYGON_NUM + 1; i ++) { + m_tRing[i].Alpha = 0.0f; + } +} \ No newline at end of file diff --git a/pool/shard001/C++/0023493_ShaderSystem.cpp b/pool/shard001/C++/0023493_ShaderSystem.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a5d4c797d535cd402f8c11415cf7a9a992755dc1 --- /dev/null +++ b/pool/shard001/C++/0023493_ShaderSystem.cpp @@ -0,0 +1,311 @@ +/* + +Copyright (c) 2004-2006 Jesper Svennevid, Daniel Collin + +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 "ShaderSystem.h" +#ifndef PS2_EMU +#include +#endif +#include + +/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +#ifndef PS2_EMU +extern "C" u32 ShaderShellVu1_CodeStart __attribute__((section(".vudata"))); +extern "C" u32 ShaderShellVu1_CodeEnd __attribute__((section(".vudata"))); + +extern "C" u32 ShaderShellStub_NextChunk __attribute__((section(".vudata"))); +extern "C" u32 ShaderShellStub_End __attribute__((section(".vudata"))); + +extern "C" u32 ShaderSystemStub_CodeStart __attribute__((section(".vudata"))); +extern "C" u32 ShaderSystemStub_CodeEnd __attribute__((section(".vudata"))); + +#else + +u32 ShaderShellVu1_CodeStart; +u32 ShaderShellVu1_CodeEnd; + +u32 ShaderShellStub_NextChunk; +u32 ShaderShellStub_End; + +u32 ShaderSystemStub_CodeStart; +u32 ShaderSystemStub_CodeEnd; + +#endif + +/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +namespace zenic +{ + namespace ps2 + { + +/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +const u32 ShaderSystem::m_opcodeNopLower = 0x8000033c; // nop +const u32 ShaderSystem::m_opcodeNopUpper = 0x000002ff; // nop +const u32 ShaderSystem::m_opcodeBalRetAddress = 0x42000000 | 15 << 16; // bal vi15, x +const u32 ShaderSystem::m_opcodeJrVi15 = 0x48007800; // jr vi15 + +/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +ShaderSystem::ShaderSystem(uint endAddress) : + m_shaderCount(0), + m_startAddress(0), + m_endAddress(endAddress), + m_active(false) +{ + memset(m_shaders, 0, sizeof(Shader) * MaxShaders); + + m_shellStart = calcSize(&ShaderShellVu1_CodeStart, &ShaderShellStub_NextChunk) + 1; + +#ifndef ZENIC_FINAL + uint shellSize = calcSize(&ShaderShellStub_NextChunk, &ShaderShellStub_End); +#endif + uint stubSize = calcSize(&ShaderSystemStub_CodeStart, &ShaderSystemStub_CodeEnd); + + // prepatch the shader shell. + + ZENIC_ASSERT_DESC(shellSize == stubSize, "ShaderStub and Shell doesnt match."); + + memcpy(&ShaderShellStub_NextChunk, &ShaderSystemStub_CodeStart, (stubSize-1) * 8); +} + +/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +void ShaderSystem::activate() +{ + Vu1* vu1Handler = Vu1::instance(); + + vu1Handler->clearCache(); + vu1Handler->getProgram(MasterChain::instance()->chain(), 3, &ShaderShellVu1_CodeStart, &ShaderShellVu1_CodeEnd); + + m_startAddress = m_currentAddress = vu1Handler->currentLocation(); + m_active = true; +} + +/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +void ShaderSystem::deactivate() +{ + m_active = false; + + memset(m_shaders, 0, sizeof(Shader) * MaxShaders); + m_shaderCount = 0; + m_startAddress = 0; +} + +/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +void ShaderSystem::activateShaders(Shader* shaders, uint shaderCount) +{ + ZENIC_ASSERT_DESC(shaderCount < MaxSimultaneousShaders, "Maximum simultaneous shaders exceeded"); + + uint foundShaderCount = 0; + Dma& dmaChain = MasterChain::instance()->chain(); + + // check if all shaders is in memory already + + for (uint i = 0; i < m_shaderCount; ++i) + { + for (uint p = 0; p < shaderCount; ++p) + { + if (m_shaders[i].start == shaders[p].start) + { + foundShaderCount++; + shaders[p].address = m_shaders[i].address; + shaders[p].uploaded = true; + break; + } + } + } + + // if all shaders arent uploaded, we need to add them to the chain + // and "shaders" struct will be filled with correct address here + + if (foundShaderCount != shaderCount) + { + uploadShaders(dmaChain, shaders, shaderCount); + } + + // We may be able to do one optimization here, if the shaders is located on the same addresses as the last + // time we actually dont need to add this mpg here. + + dmaChain.addSrcCntTag(0, VIF_MPG(MaxSimultaneousShaders << 1, m_shellStart)); + + // we test just adding noops for now + + uint programCounter = m_shellStart + 2; + + for (uint i = 0; i < shaderCount; ++i) + { + dmaChain.add32(m_opcodeBalRetAddress | shaders[i].address - programCounter); // jump is pc relative + dmaChain.add32(m_opcodeNopUpper); + + dmaChain.add32(m_opcodeNopLower); + dmaChain.add32(m_opcodeNopUpper); + + programCounter += 2; + } + + // dummy write nop's to the slots not used + + for (uint i = 0; i < MaxSimultaneousShaders - shaderCount; ++i) + { + dmaChain.add32(m_opcodeNopLower); + dmaChain.add32(m_opcodeNopUpper); + + dmaChain.add32(m_opcodeNopLower); + dmaChain.add32(m_opcodeNopUpper); + } + + dmaChain.endPacket(); +} + +/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +void ShaderSystem::uploadShaders(Dma& dmaChain, Shader* shaders, uint shaderCount) +{ + uint totalShaderSize = shaderListSize(shaders, shaderCount); + + // make sure that we havet wrapped the memory + + if ((m_currentAddress + totalShaderSize) > m_endAddress) + { + reset(); + + for (uint i = 0; i < shaderCount; ++i) + shaders[i].uploaded = false; + } + + // check so that the shaders actually fit the memory + +#ifndef ZENIC_FINAL + totalShaderSize = shaderListSize(shaders, shaderCount); + ZENIC_ASSERT_DESC((m_currentAddress + totalShaderSize) < m_endAddress, "Amount of shaders dosent fit codememory"); +#endif + + dmaChain.addSrcCntTag(VIF_FLUSH()); + dmaChain.endPacket(); + + for (uint i = 0; i < shaderCount; ++i) + { + //if (!shaders[i].uploaded) + { + uploadShader(dmaChain, shaders[i]); + } + + ZENIC_ASSERT_DESC(m_shaderCount < MaxShaders, "Maximum ShaderLimit crossed"); + } +} + +/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +void ShaderSystem::uploadShader(Dma& dmaChain, Shader& shader) +{ + s32 size = calcSize(shader.start, shader.end); + u32* start = shader.start; + + shader.uploaded = true; + shader.address = m_currentAddress; + + while (size > 0) + { + u32 currentCount = size > 128 ? 128 : size; + dmaChain.addSrcRefTag(start, currentCount >> 1, 0, VIF_MPG(currentCount, m_currentAddress)); + size -= currentCount; + start += currentCount * 2; + m_currentAddress += currentCount; + } + + + // TODO: Remove this code if possible + // We need this for adding a jr vi15 at the end of the shader as vcl doesnt like to do it for us. + + dmaChain.addSrcCntTag(0,VIF_MPG(1 << 1, m_currentAddress - 2)); + + dmaChain.add32(m_opcodeJrVi15); + dmaChain.add32(m_opcodeNopUpper); + + dmaChain.add32(m_opcodeNopLower); + dmaChain.add32(m_opcodeNopUpper); + + dmaChain.endPacket(); + + m_shaders[m_shaderCount].address = shader.address; + m_shaders[m_shaderCount].start = shader.start; + m_shaders[m_shaderCount].end = shader.end; + m_shaders[m_shaderCount].uploaded = true; + m_shaderCount++; +} + +/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +uint ShaderSystem::shaderListSize(Shader* shaders, uint shaderCount) +{ + uint totalShaderSize = 0; + + for (uint i = 0; i < shaderCount; ++i) + { + if (!shaders[i].uploaded) + totalShaderSize += calcSize(shaders[i].start, shaders[i].end); + } + + return totalShaderSize; +} + + + +/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +void ShaderSystem::reset() +{ + m_shaderCount = 0; + m_currentAddress = m_startAddress; +} + +/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +inline u32 ShaderSystem::calcSize(const u32* start, const u32* end) +{ + uint size = (end-start)/2; + + // if size is odd we have make it even in order for the transfer to work + // (quadwords, because of that its VERY important to have an extra nop nop + // at the end of each vuprogram + + if (size & 1) + size++; + + return size; +} + + +/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + } +} + diff --git a/pool/shard001/C++/0023507_data_out_stack_02.cc b/pool/shard001/C++/0023507_data_out_stack_02.cc new file mode 100644 index 0000000000000000000000000000000000000000..1b3bea4f673bb719431ee138b507079f8739f807 --- /dev/null +++ b/pool/shard001/C++/0023507_data_out_stack_02.cc @@ -0,0 +1,101 @@ +// --------------------------------------------------------------------- +// +// Copyright (C) 2003 - 2017 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. +// +// --------------------------------------------------------------------- + + +// slight variation of data_out_stack_01, but calling add_data_vector with a +// vector second argument. on most systems this doesn't make a difference, but +// on some it failed linking in the past due to non-existence of weak symbols + +#include "../tests.h" +#include "data_out_common.h" +#include +#include + + + + +template +void +check_this (const DoFHandler &, + const Vector &, + const Vector &) +{ + // 3d would generate 4d data, which + // we don't presently support + // + // output for 2d+time is not + // presently implemented +} + + + +template <> +void +check_this<1> (const DoFHandler<1> &dof_handler, + const Vector &v_node, + const Vector &v_cell) +{ + const unsigned int dim = 1; + + DataOutStack data_out_stack; + data_out_stack.declare_data_vector ("node_data", + DataOutStack::dof_vector); + data_out_stack.declare_data_vector ("cell_data", + DataOutStack::cell_vector); + + + data_out_stack.new_parameter_value (1., 1.); + data_out_stack.attach_dof_handler (dof_handler); + + std::vector names_1, names_2; + names_1.push_back ("node_data"); + names_2.push_back ("cell_data"); + data_out_stack.add_data_vector (v_node, names_1); + data_out_stack.add_data_vector (v_cell, names_2); + data_out_stack.build_patches (); + data_out_stack.finish_parameter_value (); + + Vector vn1 (v_node.size()); + vn1 = v_node; + vn1 *= 2.; + Vector vc1 (v_cell.size()); + vc1 = v_cell; + vc1 *= 3.; + data_out_stack.new_parameter_value (1., 1.); + data_out_stack.attach_dof_handler (dof_handler); + data_out_stack.add_data_vector (vn1, names_1); + data_out_stack.add_data_vector (vc1, names_2); + data_out_stack.build_patches (); + data_out_stack.finish_parameter_value (); + + data_out_stack.write_dx (deallog.get_file_stream()); + data_out_stack.set_flags (DataOutBase::UcdFlags(true)); + data_out_stack.write_ucd (deallog.get_file_stream()); + data_out_stack.write_gmv (deallog.get_file_stream()); + data_out_stack.write_tecplot (deallog.get_file_stream()); + data_out_stack.write_vtk (deallog.get_file_stream()); + data_out_stack.write_gnuplot (deallog.get_file_stream()); + data_out_stack.write_deal_II_intermediate (deallog.get_file_stream()); + + // the following is only + // implemented for 2d (=1d+time) + if (dim == 1) + { + data_out_stack.write_povray (deallog.get_file_stream()); + data_out_stack.write_eps (deallog.get_file_stream()); + } +} + + diff --git a/pool/shard001/C++/0023523_tmk2tx.cpp b/pool/shard001/C++/0023523_tmk2tx.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d90bf607464875388dfbf62ce13d91202c584ddc --- /dev/null +++ b/pool/shard001/C++/0023523_tmk2tx.cpp @@ -0,0 +1,126 @@ +// (c) 1996-97 +// 1999.12.21 TV kohendatud vastavask uuendatud X2TABEL klassile + +#define STRICT +#include +#include +#include + +#include "tmk2tx.h" +#include "cxxbs3.h" + +// {{ (C)2002 + +bool MKTAc::Start(const long offSet, CPFSFile *in) + { + assert( EmptyClassInvariant() ); + int i; + + in->Seek(offSet); + if(in->ReadUnsigned(&n)==false) + return false; + mktc=new MKTc[n]; + for(i=0; i < n; i++) + { + if(mktc[i].Read(in)==false) + return false; + } + assert( ClassInvariant() ); + return true; + } + +void MKTAc::Stop(void) + { + if(mktc) + delete [] mktc; + InitClassVariables(); + assert( EmptyClassInvariant() ); + } + +int MKTc::Compare(const MKTc *mktc, const int sortOrder) + { + FSUNUSED(sortOrder); + assert( ClassInvariant() ); + + int i, cmp; + if((cmp=n - mktc->n)!=0) + return cmp; + for(i=0; i < n; i++) + { + if((cmp=mkt1c[i].lgNr - mktc->mkt1c[i].lgNr)!=0) + return cmp; + if((cmp=mkt1c[i].tyMuut.Compare(mktc->mkt1c[i].tyMuut))!=0) + return cmp; + } + return 0; // v�rdsed + } + +bool MKTc::Read(CPFSFile *in) + { + if(in->ReadUnsigned(&n)==false) + { + return false; + } + for(int i=0; i< n; i++) + { + if(in->ReadUnsigned(&(mkt1c[i].lgNr))==false) + { + //ASSERT( false ); + return false; + } + if(in->ReadString(&(mkt1c[i].tyMuut))==false) + { + //ASSERT( false ); + return false; + } + if(mkt1c[i].tyMuut.GetLength()==0) + { + mkt1c[i].tyMuut=FSxSTR(""); + } + } + assert( ClassInvariant() ); + return true; + } + +bool MKTc::Write(CPFSFile *out) + { + assert( ClassInvariant() ); + if(out->WriteUnsigned(n)==false) + { + assert( false ); + return false; + } + for(int i=0; i < n; i++) + { + if(out->WriteUnsigned(mkt1c[i].lgNr)==false) + { + assert( false ); + return false; + } + // kirjutada koos '\0'-baidiga + if(out->WriteStringB(&(mkt1c[i].tyMuut), true)==false) + { + assert( false ); + return false; + } + } + return true; + } + +bool MKTc::WriteAsText(CPFSFile *out) + { + assert( ClassInvariant() ); + CFSbaseSTRING xStr; + int i; + + for(i=0; i < n; i++) + { + xStr.Format(FSxSTR("%d,%s "), + mkt1c[i].lgNr, (const FSxCHAR *)(mkt1c[i].tyMuut)); + + if(out->WriteString((const FSxCHAR *)xStr, (int)(xStr.GetLength())-1)==false) // kirjuta ilma '\0'-baidita + return false; + } + out->WriteStringB(FSxSTR("\n")); + return true; + } diff --git a/pool/shard001/C++/0023529_mitkContourTest.cpp b/pool/shard001/C++/0023529_mitkContourTest.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2c805d4ebab04478358af8e07cf64f34b044118e --- /dev/null +++ b/pool/shard001/C++/0023529_mitkContourTest.cpp @@ -0,0 +1,61 @@ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ + +#include "mitkContour.h" +#include "mitkCommon.h" +#include "mitkTestingMacros.h" + +#include + +int mitkContourTest(int /*argc*/, char* /*argv*/[]) +{ + MITK_TEST_BEGIN("Contour"); + mitk::Contour::Pointer contour = mitk::Contour::New(); + MITK_TEST_CONDITION_REQUIRED(contour.IsNotNull(), "Testing initialization!"); + + mitk::Point3D p; + p.Fill(0); + contour->AddVertex(p); + p.Fill(1); + contour->AddVertex(p); + p.Fill(2); + contour->AddVertex(p); + MITK_TEST_CONDITION_REQUIRED(contour->GetNumberOfPoints() == 3, "Testing AddVertex()"); + + mitk::Contour::PointsContainerPointer points = contour->GetPoints(); + MITK_TEST_CONDITION_REQUIRED(points.IsNotNull(), "Testing GetPoints()"); + + contour->Initialize(); + MITK_TEST_CONDITION_REQUIRED(contour->GetNumberOfPoints() == 0, "Testing Initialize()!"); + + contour->SetPoints(points); + MITK_TEST_CONDITION_REQUIRED(contour->GetNumberOfPoints() == 3, "Testimg SetPoints()!"); + + mitk::Contour::PathPointer path = contour->GetContourPath(); + MITK_TEST_CONDITION_REQUIRED(path.IsNotNull(), "Testing GetContourPath()!"); + + contour->UpdateOutputInformation(); + contour->SetClosed(false); + MITK_TEST_CONDITION_REQUIRED(!contour->GetClosed(), "Testing GetClosed()!"); + + mitk::Contour::Pointer cloneContour = contour->Clone(); + MITK_TEST_CONDITION_REQUIRED(cloneContour.IsNotNull(), "Testing clone instantiation!"); + MITK_TEST_CONDITION_REQUIRED(cloneContour.GetPointer() != contour.GetPointer(), "Testing cloned object is not original object!"); + MITK_TEST_CONDITION_REQUIRED(cloneContour->GetGeometry()->GetCenter() == contour->GetGeometry()->GetCenter(), "Testing if Geometry is cloned!"); + MITK_TEST_CONDITION_REQUIRED(cloneContour->GetPoints() == points, "Testing cloning of point data!"); + + MITK_TEST_END(); +} diff --git a/pool/shard001/C++/0023533_tree_order_statistics.cc b/pool/shard001/C++/0023533_tree_order_statistics.cc new file mode 100644 index 0000000000000000000000000000000000000000..5921cbf583babf1d232a35d60132fcf0b4b3fa42 --- /dev/null +++ b/pool/shard001/C++/0023533_tree_order_statistics.cc @@ -0,0 +1,105 @@ +// -*- C++ -*- + +// Copyright (C) 2005-2014 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 +// . + + +// Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. + +// Permission to use, copy, modify, sell, and distribute this software +// is hereby granted without fee, provided that the above copyright +// notice appears in all copies, and that both that copyright notice +// and this permission notice appear in supporting documentation. None +// of the above authors, nor IBM Haifa Research Laboratories, make any +// representation about the suitability of this software for any +// purpose. It is provided "as is" without express or implied +// warranty. + +/** + * @file tree_order_statistics_timing_test.cpp + * Contains test for order_statisticsing trees. + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +void +usage(); + +int +main(int argc, char* a_p_argv[]) +{ + using namespace __gnu_pbds::test; + size_t vn = 200; + size_t vs = 200; + size_t vm = 2100; + + try + { + xml_test_performance_formatter fmt("Size", "Average time (sec.)"); + + { + typedef tree_order_statistics_test< true> test_t; + test_t tst(vn, vs, vm); + typedef tree_common_types, __gnu_pbds::tree_order_statistics_node_update>::performance_tl tl_t; + tl_t tl; + __gnu_cxx::typelist::apply(tst, tl); + } + + { + typedef tree_order_statistics_test test_t; + test_t tst(vn, vs, vm); + typedef native_set native_set_t; + tst(native_set_t()); + } + } + catch(...) + { + std::cerr << "Test failed" << std::endl; + return -1; + } + return 0; +} + +void +usage() +{ + using namespace std; + cerr << "usage: tree_order_statistics_timing_test.out " << + endl << endl; + + cerr << "This test checks the performance of order statistics" + " in tree based containers. " << endl; + cerr << "Specifically, it does the following:" << endl; + cerr << "* Creates a tree" << endl; + cerr << "* Inserts integers into the tree" << endl; + cerr << "* Checks the order-statistics of each entry in the tree" << endl; + cerr << "* Repeats the above test some times" + << endl; + + cerr << endl << endl; + + cerr << "vn = minimum size of the tree" << endl; + cerr << "vs = step size of the tree" << endl; + cerr << "vm = maximum size of the tree" << endl; +} diff --git a/pool/shard001/C++/0023540_node_atc18_sdcrn_qn.cpp b/pool/shard001/C++/0023540_node_atc18_sdcrn_qn.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bfb95f6a5244446bddb4a5ee57a6b490a42e239e --- /dev/null +++ b/pool/shard001/C++/0023540_node_atc18_sdcrn_qn.cpp @@ -0,0 +1,75 @@ +/*************************************************************************** + * Copyright (C) 2007 by Simon Schulz * + * Simon.Schulz@esa.int * + * * + ***************************************************************************/ + ///this file was automatically created by 1 on Thu Jan 24 13:58:30 2008 + +#include "node_atc18_sdcrn_qn.h" + +//register to node factory +std::string Node_ATC18_SDCRN_QN::node_factory_dummy = Node_factory::register_create_function("ATC18_SDCRN_QN",Node_ATC18_SDCRN_QN::create_function); +std::string Node_ATC18_SDCRN_QN::node_factory_dummy2 = Node_factory::register_output("ATC18_SDCRN","QN"); + +Node_ATC18_SDCRN_QN::Node_ATC18_SDCRN_QN(const char *name) : Node(name, 3){ + port_map_vector.push_back("CP"); //0 + port_map_vector.push_back("D"); //1 + port_map_vector.push_back("CDN"); //2 + +} + +Node_ATC18_SDCRN_QN::~Node_ATC18_SDCRN_QN() +{ +} + +std::string Node_ATC18_SDCRN_QN::get_input_name(int i) +{ + switch(i){ + case(0): return("CP"); + case(1): return("D"); + case(2): return("CDN"); + default: return ""; + } + +} + +//NOTE: evaluate is different for FF elements! +// -> for an evaluate call we actually calculate the values using the inputs +// while get_value() just returns a value set before +// we use this for example when having "loops" from the output FF to the +// input of this FF. (think about it ;) ) +int Node_ATC18_SDCRN_QN::evaluate() +{ +//define some helpers, makes it easier to write function + #define CP input_nodes[0]->get_value(run) + #define D input_nodes[1]->get_value(run) + #define CDN input_nodes[2]->get_value(run) + #define SC 0 + #define SD D + #define QN value + #define Q !(QN) + + + int run = last_eval++; + last_run_value = (!(1?(CDN?(SC?SD:D):0):1)); + return last_run_value; +} + +Node *Node_ATC18_SDCRN_QN::get_ff_input_node() +{ + #define IN_CP input_nodes[0] + #define IN_D input_nodes[1] + #define IN_CDN input_nodes[2] + return IN_D; + +} + +std::string Node_ATC18_SDCRN_QN::get_formula() +{ + return std::string(get_name()); +} + +int Node_ATC18_SDCRN_QN::get_value(int run) +{ + return !value; +} diff --git a/pool/shard001/C++/0023550_ftermios.cpp b/pool/shard001/C++/0023550_ftermios.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6dda47c480119a9e64c9216da5feb66011a30ea8 --- /dev/null +++ b/pool/shard001/C++/0023550_ftermios.cpp @@ -0,0 +1,254 @@ +/*********************************************************************** +* ftermios.cpp - Provides access to POSIX tty I/O control * +* * +* This file is part of the FINAL CUT widget toolkit * +* * +* Copyright 2018-2021 Markus Gans * +* * +* FINAL CUT 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. * +* * +* FINAL CUT 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 * +* . * +***********************************************************************/ + +#if defined(__CYGWIN__) + #undef __STRICT_ANSI__ // need for fileno + #define _POSIX_C_SOURCE 200809L + #define _BSD_SOURCE +#endif + +#include + +#if defined(__CYGWIN__) + #define __STRICT_ANSI__ // need for bits/c++config.h +#endif + +#include +#include + +#include "final/output/tty/fterm.h" +#include "final/output/tty/ftermios.h" + +namespace finalcut +{ + +// static class attributes +int FTermios::stdin_no; +int FTermios::stdout_no; +int FTermios::stderr_no; +bool FTermios::raw_mode; +termios FTermios::term_init; + + +//---------------------------------------------------------------------- +// class FTermios +//---------------------------------------------------------------------- + +// constructors and destructor +//---------------------------------------------------------------------- +FTermios::FTermios() +{ + init(); +} + +// public methods of FTermios +//---------------------------------------------------------------------- +void FTermios::init() +{ + // Assertion: programm start in cooked mode + raw_mode = false; + + // Get file descriptor for standard input and standard output + stdin_no = fileno(stdin); + stdout_no = fileno(stdout); + stderr_no = fileno(stderr); +} + +//---------------------------------------------------------------------- +termios FTermios::getTTY() +{ + struct termios t{}; + + if ( tcgetattr(stdin_no, &t) == -1 ) + throw std::system_error(errno, std::generic_category()); + + return t; +} + +//---------------------------------------------------------------------- +void FTermios::setTTY (const termios& t) +{ + tcsetattr (stdin_no, TCSADRAIN, &t); +} + +//---------------------------------------------------------------------- +void FTermios::storeTTYsettings() +{ + // Store termios settings + try + { + term_init = getTTY(); + } + catch (const std::system_error&) + { + throw std::current_exception(); + } +} + +//---------------------------------------------------------------------- +void FTermios::restoreTTYsettings() +{ + // Restore termios settings + setTTY (term_init); +} + +//---------------------------------------------------------------------- +void FTermios::setHardwareEcho() +{ + // Info under: man 3 termios + struct termios t{}; + tcgetattr (stdin_no, &t); + + // local mode + t.c_lflag &= uInt(ECHO | ECHONL); + + // input mode + t.c_iflag &= uInt(ICRNL | INLCR | IGNCR); + + // output mode + t.c_oflag &= uInt(ONLCR); + + // set the new termios settings + setTTY (t); +} + +//---------------------------------------------------------------------- +void FTermios::unsetHardwareEcho() +{ + // Info under: man 3 termios + struct termios t{}; + tcgetattr (stdin_no, &t); + + // local mode + t.c_lflag &= uInt(~(ECHO | ECHONL)); + + // input mode + t.c_iflag &= uInt(~(ICRNL | INLCR | IGNCR)); + + // output mode + t.c_oflag &= uInt(~ONLCR); + + // set the new termios settings + setTTY (t); +} + +//---------------------------------------------------------------------- +void FTermios::setCaptureSendCharacters() +{ + struct termios t{}; + tcgetattr (stdin_no, &t); + t.c_lflag &= uInt(~(ICANON | ECHO)); + t.c_cc[VTIME] = 10; // Timeout in deciseconds + t.c_cc[VMIN] = 0; // Minimum number of characters + tcsetattr (stdin_no, TCSANOW, &t); +} + +//---------------------------------------------------------------------- +void FTermios::unsetCaptureSendCharacters() +{ + struct termios t{}; + tcgetattr (stdin_no, &t); + t.c_lflag |= uInt(ICANON | ECHO); + t.c_cc[VTIME] = 0; // Timeout in deciseconds + t.c_cc[VMIN] = 1; // Minimum number of characters + setTTY (t); +} + +//---------------------------------------------------------------------- +bool FTermios::setRawMode (bool enable) +{ + // set + unset flags for raw mode + if ( raw_mode == enable ) + return raw_mode; + + // Info under: man 3 termios + struct termios t{}; + tcgetattr (stdin_no, &t); + + if ( enable ) + { + // local mode +#if DEBUG + // Exit with ctrl-c only if compiled with "DEBUG" option + t.c_lflag &= uInt(~(ICANON | IEXTEN)); +#else + t.c_lflag &= uInt(~(ICANON | ISIG | IEXTEN)); +#endif + + // input mode + t.c_iflag &= uInt(~(IXON | BRKINT | PARMRK)); + + // defines the terminal special characters for noncanonical read + t.c_cc[VTIME] = 0; // Timeout in deciseconds + t.c_cc[VMIN] = 1; // Minimum number of characters + + // set the new termios settings + setTTY (t); + raw_mode = true; + } + else + { + // local mode + t.c_lflag |= uInt(ISIG | ICANON | (term_init.c_lflag & IEXTEN)); + + // input mode + t.c_iflag |= uInt(IXON | BRKINT | PARMRK); + + // set the new termios settings + setTTY (t); + raw_mode = false; + } + + return raw_mode; +} + +//---------------------------------------------------------------------- +uInt FTermios::getBaudRate() +{ + std::unordered_map outspeed; + outspeed[B0] = 0; // hang up + outspeed[B50] = 50; // 50 baud + outspeed[B75] = 75; // 75 baud + outspeed[B110] = 110; // 110 baud + outspeed[B134] = 134; // 134.5 baud + outspeed[B150] = 150; // 150 baud + outspeed[B200] = 200; // 200 baud + outspeed[B300] = 300; // 300 baud + outspeed[B600] = 600; // 600 baud + outspeed[B1200] = 1200; // 1,200 baud + outspeed[B1800] = 1800; // 1,800 baud + outspeed[B2400] = 2400; // 2,400 baud + outspeed[B4800] = 4800; // 4,800 baud + outspeed[B9600] = 9600; // 9,600 baud + outspeed[B19200] = 19200; // 19,200 baud + outspeed[B38400] = 38400; // 38,400 baud + outspeed[B57600] = 57600; // 57,600 baud + outspeed[B115200] = 115200; // 115,200 baud + outspeed[B230400] = 230400; // 230,400 baud + + if ( outspeed.find(cfgetospeed(&term_init)) != outspeed.end() ) + return outspeed[cfgetospeed(&term_init)]; + + return 0; +} + +} // namespace finalcut diff --git a/pool/shard001/C++/0023560_smobs.cc b/pool/shard001/C++/0023560_smobs.cc new file mode 100644 index 0000000000000000000000000000000000000000..7bdaaa7f922017055367d496abe3c852a744b479 --- /dev/null +++ b/pool/shard001/C++/0023560_smobs.cc @@ -0,0 +1,76 @@ +/* + smobs.cc -- implement Smob protection + + source file of the GNU LilyPond music typesetter + + (c) 2005--2007 Han-Wen Nienhuys +*/ + +#include "smobs.hh" + +/* + The CDR contains the actual protected list. + */ +static SCM smob_protection_list = SCM_EOL; + +void +init_smob_protection () +{ + smob_protection_list = scm_cons (SCM_BOOL_F, SCM_EOL); + scm_gc_protect_object (smob_protection_list); +} +ADD_SCM_INIT_FUNC (init_smob_protection, init_smob_protection); + +LY_DEFINE (ly_smob_protects, "ly:smob-protects", + 0, 0, 0, (), + "Return LilyPond's internal smob protection list.") +{ + return scm_is_pair (smob_protection_list) + ? scm_cdr (smob_protection_list) + : SCM_EOL; +} + +void +protect_smob (SCM smob, SCM *prot_cons) +{ +#if 0 + SCM s = scm_cdr (smob_protection_list); + while (scm_is_pair (s) && scm_car (s) == SCM_BOOL_F) + { + s = scm_cdr (s); + } + SCM prot = scm_cons (smob, s); + scm_set_cdr_x (smob_protection_list, + prot); + *prot_cons = prot; +#else + (void) prot_cons; + scm_gc_protect_object (smob); +#endif +} + +void +unprotect_smob (SCM smob, SCM *prot_cons) +{ +#if 1 + (void) prot_cons; + scm_gc_unprotect_object (smob); +#else + SCM next = scm_cdr (*prot_cons); + + if (next == SCM_EOL) + scm_set_car_x (*prot_cons, SCM_BOOL_F); + else + { + scm_set_car_x (*prot_cons, SCM_BOOL_F); + while (scm_is_pair (next) + && scm_car (next) == SCM_BOOL_F) + + next = scm_cdr (next); + + scm_set_cdr_x (*prot_cons, next); + } + + *prot_cons = SCM_EOL; +#endif +} diff --git a/pool/shard001/C++/0023562_class.cpp b/pool/shard001/C++/0023562_class.cpp new file mode 100644 index 0000000000000000000000000000000000000000..df7137d7833b9750ebce9c39f16add20e5c77136 --- /dev/null +++ b/pool/shard001/C++/0023562_class.cpp @@ -0,0 +1,124 @@ +#include +#define MAX 40 + +class Stock //¹¹½¨Àà +{ +private : //˽ÓгÉÔ± + char company[MAX]; + int shares; + double share_val; + double total_val; + void set_tot() + { + total_val = shares * share_val; + } +public : //¹«ÓóÉÔ± + Stock(); + ~Stock(); + Stock( const char * co, int n = 0, double pr = 0 ); + void buy( int num, double price ); + void sell( int num, double price ); + void update( double price ); + void show(); + const Stock & topval( const Stock & s )const; +} ; +Stock::Stock() +{ + std::cout << "Default constructor called.\n"; + std::strcpy( company, "no name" ); + shares = 0; + share_val = 0; + total_val = 0; +} +Stock::~Stock() +{ + std::cout << "Bye, " << company << std::endl; + return ; +} +/**********¼Èë¹ÉƱÊý¾Ý**********/ +Stock::Stock( const char * co, int n, double pr ) +{ + std::strncpy( company, co, 39 ); + company[39] = '\0'; + + if ( n < 0 ) + { + std::cout << "Number of shares can't be negative." + << company << " shares set to zero.\n"; + shares = 0; + } + else + shares = n; + share_val = pr; + set_tot(); + + return ; +} + +/**********Âò½ø¹ÉƱ**********/ +void Stock::buy( int num, double price ) +{ + if ( num < 0 ) + { + std::cout << "Number of shares purchsaed can't be negative." + << "Transaction is aborted.\n"; + } + else + { + shares += num; + share_val = price; + set_tot(); + } +} +/**********Âô³ö¹ÉƱ**********/ +void Stock::sell( int num, double price ) +{ + if ( num < 0 ) + { + std::cout << "Number of shares purchsaed can't be negative." + << "Transaction is aborted.\n"; + } + else if ( num > shares ) + { + std::cout << "You can't sell more than you have! " + << "Transaction is aborted.\n"; + } + else + { + std::cout << "After selled, the information as follow:" << std::endl; + shares -= num; + share_val = price; + set_tot(); + } + + return ; +} +/**********¸üÐÂ¹ÉÆ±Êý¾Ý**********/ +void Stock::update( double price ) +{ + share_val = price; + set_tot(); + std::cout << "After update, the information as follow:" << std::endl; + + return ; +} +/**********չʾ¹ÉƱÊý¾Ý**********/ +void Stock::show() +{ + using std::cout; + using std::endl; + + cout << "Company: " << company << endl; + cout << "Shares: "<< shares << endl; + cout << "Share Price: $" << share_val << endl; + cout << "Total Worth: $" << total_val << endl << endl; + + return ; +} +/**********±È½ÏÊý¾Ý**********/ +const Stock & Stock::topval( const Stock & s ) const +{ + if ( s.total_val > total_val ) + return s; + return *this; //thisÖ¸ÕëµÄÓ÷¨£¬·µ»ØconstÒþ²ØµÄÀà +} diff --git a/pool/shard001/C++/0023575_csvpredictionwriter.cpp b/pool/shard001/C++/0023575_csvpredictionwriter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..79ef6b598207dbd1f2add651e644c891fccd42fb --- /dev/null +++ b/pool/shard001/C++/0023575_csvpredictionwriter.cpp @@ -0,0 +1,116 @@ +/*****************************************************************************/ +/* */ +/* HST-Reader */ +/* https://github.com/terentjew-alexey/Hst-reader */ +/* */ +/* C S V P R E D I C T I O N W R I T E R C L A S S */ +/* */ +/* Aleksey Terentew */ +/* terentew.aleksey@ya.ru */ +/* */ +/*****************************************************************************/ + +#include "include/csvpredictionwriter.h" +#include +#include +#include +#include +#include + +CsvPredictionWriter::CsvPredictionWriter(QObject *parent) : CsvWriter(parent), + header(nullptr), + dataPrediction(nullptr) +{} + +CsvPredictionWriter::CsvPredictionWriter(QString fName) : CsvWriter(fName), + header(nullptr), + dataPrediction(nullptr) +{} + +CsvPredictionWriter::~CsvPredictionWriter() +{ + if( header ) + delete header; + if( dataPrediction ) { + for( qint32 i = 0; i < dataPrediction->size(); i++ ) + delete (*dataPrediction)[i]; + delete dataPrediction; + } +} + +PHeader *CsvPredictionWriter::getHeader() +{ + if( header == nullptr ) + header = new PHeader; + return header; +} + +QList *CsvPredictionWriter::getDataPredictionPtr() +{ + if( dataPrediction == nullptr ) + dataPrediction = new QList; + return dataPrediction; +} + +void CsvPredictionWriter::writeFile(void) +{ + if( fileName == "" ) + return; + if( !fileName.contains(".csv") ) + fileName += ".csv"; + QFile file( fileName, this ); + if( file.open(QIODevice::WriteOnly) ) { + QTextStream output( &file ); + // Write header + QString headerStr = QString("%1;%2;%3;%4;%5;%6;%7;%8\n") + .arg( header->Version ) + .arg( header->Copyright ) + .arg( header->Symbol ) + .arg( header->Period ) + .arg( header->Digits ) + .arg( QDateTime::fromTime_t( header->TimeSign ) + .toString("yyyy.MM.dd hh:mm:ss") ) + .arg( QDateTime::fromTime_t( header->LastSync ) + .toString("yyyy.MM.dd hh:mm:ss") ) + .arg( header->Depth ); + output << headerStr; + // Write prediction + QString buffer; + for( qint32 idx = 0; idx < dataPrediction->size(); idx++ ) { + buffer = QDateTime::fromTime_t( (*dataPrediction)[idx]->Time ) + .toString("yyyy.MM.dd hh:mm:ss"); + for( qint32 j = 0; j < header->Depth; j++ ) { + buffer += ';'; + buffer += QString::number( (*dataPrediction)[idx]->High[j], + 'f', header->Digits ); + } + buffer += '\n'; + output << buffer; + buffer = QDateTime::fromTime_t( (*dataPrediction)[idx]->Time ) + .toString("yyyy.MM.dd hh:mm:ss"); + for( qint32 j = 0; j < header->Depth; j++ ) { + buffer += ';'; + buffer += QString::number( (*dataPrediction)[idx]->Low[j], + 'f', header->Digits ); + } + buffer += '\n'; + output << buffer; + buffer = QDateTime::fromTime_t( (*dataPrediction)[idx]->Time ) + .toString("yyyy.MM.dd hh:mm:ss"); + for( qint32 j = 0; j < header->Depth; j++ ) { + buffer += ';'; + buffer += QString::number( (*dataPrediction)[idx]->Close[j], + 'f', header->Digits ); + } + buffer += '\n'; + output << buffer; + } + file.close(); + } +} + +void CsvPredictionWriter::writeFile(const QString fName) +{ + setFileName( fName ); + CsvPredictionWriter::writeFile(); +} diff --git a/pool/shard001/C++/0023580_UForm_AParkDocumentsView_PlanovyiViddil.cpp b/pool/shard001/C++/0023580_UForm_AParkDocumentsView_PlanovyiViddil.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8023f059923614e2128f5790e9e15659d3fd4d3d --- /dev/null +++ b/pool/shard001/C++/0023580_UForm_AParkDocumentsView_PlanovyiViddil.cpp @@ -0,0 +1,137 @@ +//--------------------utech--------------------utech--------------------utech-------------------- +// +// Ôàéë âèêîíàííÿ êëàñó â³êíà íàëàøòóâàííÿ ïðîãðàìè +// +// Ñòâîðåíèé ïðîãðàì³ñòàìè Êîìïàí³¿ "Óòåõ" 29.03.2009ð. +// Ó êëàñ³ âèêîðèñòîâóþòüñÿ êîìïîíåíòè á³áë³îòåêè QT4.x +// +//--------------------utech--------------------utech--------------------utech-------------------- +#include "UForm_AParkDocumentsView_PlanovyiViddil.h" + +#include "UDifFunc_APark.h" +#include "UPrintDocs_APark.h" +#include "UPrintDocs.h" +#include "UDialogYMFilter.h" +#include "UDialog_AParkDateFilter.h" +#include "UDialog_AParkMarshrutTypeDateFilter.h" +#include "UDialog_AParkAutobusDateFilter.h" +#include + +#include +//--------------------utech--------------------utech--------------------utech-------------------- +UForm_AParkDocumentsView_PlanovyiViddil::UForm_AParkDocumentsView_PlanovyiViddil(int tWType, QWidget *parent) + : UAParkTabWidget(tWType, parent) +{ + ui.setupUi(this); + + ui.dateEdit_filtr->setDate(QDate::currentDate()); + + connect(ui.pushButton_printPlanyValovyhDohodiv, SIGNAL(clicked()), + this, SLOT(action_printPlanyValovyhDohodiv_activated())); + connect(ui.pushButton_printVidomistVykonannyaPlanuVDen, SIGNAL(clicked()), + this, SLOT(action_printVidomistVykonannyaPlanuVDen_activated())); + connect(ui.pushButton_printZvedenaVidomistPoDorojnihLystahZaMisyac, SIGNAL(clicked()), + this, SLOT(action_printZvedenaVidomistPoDorojnihLystahZaMisyac_activated())); + connect(ui.pushButton_printZvedenaVidomistPoTupahMarshrutivZaMisyac, SIGNAL(clicked()), + this, SLOT(action_printZvedenaVidomistPoTupahMarshrutivZaMisyac_activated())); + connect(ui.pushButton_printZvitProZdanuVyruchkuGotivkoyu, SIGNAL(clicked()), + this, SLOT(action_printZvitProZdanuVyruchkuGotivkoyu_activated())); + connect(ui.pushButton_printZvitProPerevezPilgPasajyriv, SIGNAL(clicked()), + this, SLOT(action_printZvitProPerevezPilgPasajyriv_activated())); + + connect(ui.pushButton_print_perelik_pracivnykiv, SIGNAL(clicked()), + this, SLOT(action_print_perelik_pracivnykiv_activated())); +} +//--------------------utech--------------------utech--------------------utech-------------------- +void UForm_AParkDocumentsView_PlanovyiViddil::populateToolBar(QToolBar * tBar) +{ + +} +//--------------------utech--------------------utech--------------------utech-------------------- +UForm_AParkDocumentsView_PlanovyiViddil::~UForm_AParkDocumentsView_PlanovyiViddil() +{ + +} +//--------------------utech--------------------utech--------------------utech-------------------- +void UForm_AParkDocumentsView_PlanovyiViddil::action_printPlanyValovyhDohodiv_activated() +{ + UDialog_AParkDateFilter *d = new UDialog_AParkDateFilter(ui.dateEdit_filtr->date(), "Äàòà Ïëàí³â", "dd.MM.yyyy"); + if (d->exec()){ + UPrintDocs_APark *printDocs = new UPrintDocs_APark(); + printDocs->print_planyValovyhDohodiv(d->date()); + connect(this, SIGNAL(mainWindowClosed()), printDocs->printform, SLOT(close())); + delete printDocs; + } + delete d; +} +//--------------------utech--------------------utech--------------------utech-------------------- +void UForm_AParkDocumentsView_PlanovyiViddil::action_printVidomistVykonannyaPlanuVDen_activated() +{ + UDialog_AParkDateFilter *d = new UDialog_AParkDateFilter(ui.dateEdit_filtr->date(), "Äàòà äëÿ â³äîìîñò³"); + if (d->exec()){ + UPrintDocs_APark *printDocs = new UPrintDocs_APark(); + printDocs->print_vidomistVykonannyaPlanuVDen(d->date()); + connect(this, SIGNAL(mainWindowClosed()), printDocs->printform, SLOT(close())); + delete printDocs; + } + delete d; +} +//--------------------utech--------------------utech--------------------utech-------------------- +void UForm_AParkDocumentsView_PlanovyiViddil::action_printZvedenaVidomistPoDorojnihLystahZaMisyac_activated() +{ + UDialog_AParkMarshrutTypeDateFilter *d = new UDialog_AParkMarshrutTypeDateFilter(ui.dateEdit_filtr->date(), "Äàòà äëÿ â³äîìîñò³", "MM.yyyy"); + if (d->exec()){ + UPrintDocs_APark *printDocs = new UPrintDocs_APark(); + printDocs->print_zvedenaVidomistPoDorojnihLystahZaMisyac(d->date(), d->marshrutType()); + connect(this, SIGNAL(mainWindowClosed()), printDocs->printform, SLOT(close())); + delete printDocs; + } + delete d; +} +//--------------------utech--------------------utech--------------------utech-------------------- +void UForm_AParkDocumentsView_PlanovyiViddil::action_printZvedenaVidomistPoTupahMarshrutivZaMisyac_activated() +{ + UDialog_AParkDateFilter *d = new UDialog_AParkDateFilter(ui.dateEdit_filtr->date(), "Äàòà äëÿ â³äîìîñò³", "MM.yyyy"); + if (d->exec()){ + UPrintDocs_APark *printDocs = new UPrintDocs_APark(); + printDocs->print_zvedenaVidomistPoTupahMarshrutivZaMisyac(d->date()); + connect(this, SIGNAL(mainWindowClosed()), printDocs->printform, SLOT(close())); + delete printDocs; + } + delete d; +} +//--------------------utech--------------------utech--------------------utech-------------------- +void UForm_AParkDocumentsView_PlanovyiViddil::action_printZvitProZdanuVyruchkuGotivkoyu_activated() +{ + UDialog_AParkDateFilter *d = new UDialog_AParkDateFilter(ui.dateEdit_filtr->date(), "Äàòà äëÿ â³äîìîñò³", "MM.yyyy"); + if (d->exec()){ + UPrintDocs_APark *printDocs = new UPrintDocs_APark(); + printDocs->print_zvitProZdanuVyruchkuGotivkoyuZaMisyac(d->date()); + connect(this, SIGNAL(mainWindowClosed()), printDocs->printform, SLOT(close())); + delete printDocs; + } + delete d; +} +//--------------------utech--------------------utech--------------------utech-------------------- +void UForm_AParkDocumentsView_PlanovyiViddil::action_printZvitProPerevezPilgPasajyriv_activated() +{ + UDialog_AParkDateFilter *d = new UDialog_AParkDateFilter(ui.dateEdit_filtr->date(), "Äàòà äëÿ â³äîìîñò³", "MM.yyyy"); + if (d->exec()){ + UPrintDocs_APark *printDocs = new UPrintDocs_APark(); + printDocs->print_zvitProPerevezPilgPasajyriv(d->date()); + connect(this, SIGNAL(mainWindowClosed()), printDocs->printform, SLOT(close())); + delete printDocs; + } + delete d; +} +//--------------------utech--------------------utech--------------------utech-------------------- + +void UForm_AParkDocumentsView_PlanovyiViddil::action_print_perelik_pracivnykiv_activated() +{ + UPrintDocs *printDocs = new UPrintDocs(); + printDocs->perelik_pracivnykiv(0, false); + connect(this, SIGNAL(closeLoginSignal()), printDocs->printform, SLOT(close())); + connect(this, SIGNAL(mainWindowClosed()), printDocs->printform, SLOT(close())); + delete printDocs; +} +//--------------------utech--------------------utech--------------------utech-------------------- diff --git a/pool/shard001/C++/0023587_node.cc b/pool/shard001/C++/0023587_node.cc new file mode 100644 index 0000000000000000000000000000000000000000..0a22a9cfbc50a204719fdd8786cbcbdf1e97f4c5 --- /dev/null +++ b/pool/shard001/C++/0023587_node.cc @@ -0,0 +1,169 @@ +/* + * scrm is an implementation of the Sequential-Coalescent-with-Recombination Model. + * + * Copyright (C) 2013, 2014 Paul R. Staab, Sha (Joe) Zhu, Dirk Metzler and Gerton Lunter + * + * This file is part of scrm. + * + * scrm 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 "node.h" +#include +#include +#include +#include + + +Node::Node() { init(); } +Node::Node(double height) { init(height); } +Node::Node(double height, size_t label) { init(height, label); } +Node::~Node() {} + +void Node::init(double height, size_t label) { + this->set_last_update(0); + this->set_population(0); + + this->set_height(height); + this->set_label(label); + if (label == 0) this->set_samples_below(1); + else this->set_samples_below(0); + this->set_length_below(0); + this->set_last_change(0); + + this->set_parent(NULL); + this->set_second_child(NULL); + this->set_first_child(NULL); + this->set_previous(NULL); + this->set_next(NULL); +} + + +void Node::change_child(Node* from, Node* to) { + if ( this->first_child() == from ) { + if (to != NULL) this->set_first_child(to); + else { + set_first_child(second_child()); + set_second_child(NULL); + } + } + else if ( this->second_child() == from ) + this->set_second_child(to); + else { + dout << "Error when changing child of " << this << " form " + << from << " to " << to << std::endl; + dout << "Children are " << this->first_child() << " and " + << this->second_child() << std::endl; + throw std::invalid_argument("Can't find child node to replace"); + } +} + +void Node::remove_child(Node* child) { + if ( this->first_child() == child ) { + this->set_first_child(this->second_child()); + this->set_second_child(NULL); + return; + } + + if ( this->second_child() == child ) { + this->set_second_child(NULL); + return; + } + + throw std::invalid_argument("Can't find child to delete"); +} + +/** + * @brief Returns is the parent of this node on the local tree. + * + * This should only be executed on local nodes! + * + * @return The node that is this node's parent on the local tree. + */ +Node* Node::getLocalParent() const { + assert( this->local() ); + assert( !this->is_root()); + assert( this->parent()->countChildren() > 0 ); + if (parent()->countChildren(true) == 2) return parent(); + return parent()->getLocalParent(); +} + +/** + * @brief Returns one child of this node when looking + * only at the local tree. + * + * The up to two children of a node are in basically + * arbitrary order. The only difference between child_1 and + * child_2 is that if a node has only one child, than + * it is always child_1. + * + * This should only be executed on local nodes! + * + * @return NULL if this node has no children on the local tree, + * or a pointer to the child otherwise. + */ +Node* Node::getLocalChild1() const { + if (first_child() == NULL || !first_child()->local()) return NULL; + if (first_child()->countChildren(true) == 1) { + if (first_child()->first_child()->local()) return first_child()->getLocalChild1(); + else return first_child()->getLocalChild2(); + } + // Child has 0 or 2 local children => it is part of local tree + return first_child(); +} + +/** + * @brief Returns one child of this node when looking + * only at the local tree. + * + * The up to two children of a node are in basically + * arbitrary order. The only difference between child_1 and + * child_2 is that if a node has only one child, than + * it is always child_1. + * + * This should only be executed on local nodes! + * + * @return NULL if this node has less than two children on the local tree, + * or a pointer to the child otherwise. + */ +Node* Node::getLocalChild2() const { + if (second_child() == NULL || !second_child()->local()) return NULL; + if (second_child()->countChildren(true) == 1) { + if (second_child()->first_child()->local()) return second_child()->getLocalChild1(); + else return second_child()->getLocalChild2(); + } + // Child has 0 or 2 local children => it is part of local tree + return second_child(); +} + + +void Node::extract_bl_and_label ( std::string::iterator in_it ){ + // Going backwards, extract branch length first, then the node label + std::string::iterator bl_start = in_it; + //for (; (*(bl_start-1)) != ':'; --bl_start ){ } + while ((*(bl_start-1)) != ':') + --bl_start; + double bl = strtod( &(*bl_start), NULL ); + this->set_bl ( bl ); + + std::string::iterator label_start = (bl_start-2); + + while ( (*(label_start)) != ',' && ( *(label_start)) != '(' && (*(label_start)) != ')' ) + --label_start; + + this->set_label ( ( (*(label_start)) == ')' ? 0 /*! Label internal nodes */ + : strtol ( &(*(label_start+1)), NULL , 10)) ); /*! Label tip nodes */ +} + diff --git a/pool/shard001/C++/0023592_adhoc-wifi-mac.cc b/pool/shard001/C++/0023592_adhoc-wifi-mac.cc new file mode 100644 index 0000000000000000000000000000000000000000..b1fe60210dfcb78e07ac45ee0cd953b72e1cf011 --- /dev/null +++ b/pool/shard001/C++/0023592_adhoc-wifi-mac.cc @@ -0,0 +1,194 @@ +/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ +/* + * Copyright (c) 2006, 2009 INRIA + * Copyright (c) 2009 MIRKO BANCHI + * + * 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 + * Author: Mirko Banchi + */ +#include "adhoc-wifi-mac.h" + +#include "ns3/pointer.h" +#include "ns3/log.h" +#include "ns3/string.h" +#include "ns3/boolean.h" +#include "ns3/trace-source-accessor.h" +#include "ns3/abort.h" + +#include "qos-tag.h" +#include "mac-low.h" +#include "dcf-manager.h" +#include "mac-rx-middle.h" +#include "mac-tx-middle.h" +#include "msdu-aggregator.h" +#include "amsdu-subframe-header.h" +#include "mgt-headers.h" + +NS_LOG_COMPONENT_DEFINE ("AdhocWifiMac"); + +namespace ns3 { + +NS_OBJECT_ENSURE_REGISTERED (AdhocWifiMac); + +TypeId +AdhocWifiMac::GetTypeId (void) +{ + static TypeId tid = TypeId ("ns3::AdhocWifiMac") + .SetParent () + .AddConstructor () + ; + return tid; +} + +AdhocWifiMac::AdhocWifiMac () +{ + NS_LOG_FUNCTION (this); + + // Let the lower layers know that we are acting in an IBSS + SetTypeOfStation (ADHOC_STA); +} + +AdhocWifiMac::~AdhocWifiMac () +{ + NS_LOG_FUNCTION (this); +} + +void +AdhocWifiMac::SetAddress (Mac48Address address) +{ + NS_LOG_FUNCTION (this << address); + // In an IBSS, the BSSID is supposed to be generated per Section + // 11.1.3 of IEEE 802.11. We don't currently do this - instead we + // make an IBSS STA a bit like an AP, with the BSSID for frames + // transmitted by each STA set to that STA's address. + // + // This is why we're overriding this method. + RegularWifiMac::SetAddress (address); + RegularWifiMac::SetBssid (address); +} + +void +AdhocWifiMac::Enqueue (Ptr packet, Mac48Address to) +{ + NS_LOG_FUNCTION (this << packet << to); + if (m_stationManager->IsBrandNew (to)) + { + // In ad hoc mode, we assume that every destination supports all + // the rates we support. + for (uint32_t i = 0; i < m_phy->GetNModes (); i++) + { + m_stationManager->AddSupportedMode (to, m_phy->GetMode (i)); + } + m_stationManager->RecordDisassociated (to); + } + + WifiMacHeader hdr; + + // If we are not a QoS STA then we definitely want to use AC_BE to + // transmit the packet. A TID of zero will map to AC_BE (through \c + // QosUtilsMapTidToAc()), so we use that as our default here. + uint8_t tid = 0; + + // For now, a STA that supports QoS does not support non-QoS + // associations, and vice versa. In future the STA model should fall + // back to non-QoS if talking to a peer that is also non-QoS. At + // that point there will need to be per-station QoS state maintained + // by the association state machine, and consulted here. + if (m_qosSupported) + { + hdr.SetType (WIFI_MAC_QOSDATA); + hdr.SetQosAckPolicy (WifiMacHeader::NORMAL_ACK); + hdr.SetQosNoEosp (); + hdr.SetQosNoAmsdu (); + // Transmission of multiple frames in the same TXOP is not + // supported for now + hdr.SetQosTxopLimit (0); + + // Fill in the QoS control field in the MAC header + tid = QosUtilsGetTidForPacket (packet); + // Any value greater than 7 is invalid and likely indicates that + // the packet had no QoS tag, so we revert to zero, which'll + // mean that AC_BE is used. + if (tid >= 7) + { + tid = 0; + } + hdr.SetQosTid (tid); + } + else + { + hdr.SetTypeData (); + } + + hdr.SetAddr1 (to); + hdr.SetAddr2 (m_low->GetAddress ()); + hdr.SetAddr3 (GetBssid ()); + hdr.SetDsNotFrom (); + hdr.SetDsNotTo (); + + if (m_qosSupported) + { + NS_ABORT_MSG("mm do not suport QoS"); + // Sanity check that the TID is valid + NS_ASSERT (tid < 8); + m_edca[QosUtilsMapTidToAc (tid)]->Queue (packet, hdr); + } + else + { + m_dca->Queue (packet, hdr); + } +} + +void +AdhocWifiMac::SetLinkUpCallback (Callback linkUp) +{ + NS_LOG_FUNCTION (this << &linkUp); + RegularWifiMac::SetLinkUpCallback (linkUp); + + // The approach taken here is that, from the point of view of a STA + // in IBSS mode, the link is always up, so we immediately invoke the + // callback if one is set + linkUp (); +} + +void +AdhocWifiMac::Receive (Ptr packet, const WifiMacHeader *hdr) +{ + NS_LOG_FUNCTION (this << packet << hdr); + NS_ASSERT (!hdr->IsCtl ()); + Mac48Address from = hdr->GetAddr2 (); + Mac48Address to = hdr->GetAddr1 (); + if (hdr->IsData ()) + { + if (hdr->IsQosData () && hdr->IsQosAmsdu ()) + { + NS_LOG_DEBUG ("Received A-MSDU from" << from); + DeaggregateAmsduAndForward (packet, hdr); + } + else + { + ForwardUp (packet, from, to); + } + return; + } + + // Invoke the receive handler of our parent class to deal with any + // other frames. Specifically, this will handle Block Ack-related + // Management Action frames. + RegularWifiMac::Receive (packet, hdr); +} + +} // namespace ns3 diff --git a/pool/shard001/C++/0023599_simple_single.cpp b/pool/shard001/C++/0023599_simple_single.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b1a131cff2287d2dedd0248f7a5878743366cc9c --- /dev/null +++ b/pool/shard001/C++/0023599_simple_single.cpp @@ -0,0 +1,273 @@ +/***************************** +Copyright 2011 Rafael Muñoz Salinas. 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 Rafael Muñoz Salinas ''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 Rafael Muñoz Salinas 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. + +The views and conclusions contained in the software and documentation are those of the +authors and should not be interpreted as representing official policies, either expressed +or implied, of Rafael Muñoz Salinas. +********************************/ +/** +* @file simple_single.cpp +* @author Bence Magyar +* @date June 2012 +* @version 0.1 +* @brief ROS version of the example named "simple" in the Aruco software package. +*/ + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace aruco; + +class ArucoSimple +{ +private: + cv::Mat inImage; + aruco::CameraParameters camParam; + tf::StampedTransform rightToLeft; + bool useRectifiedImages; + MarkerDetector mDetector; + vector markers; + ros::Subscriber cam_info_sub; + bool cam_info_received; + image_transport::Publisher image_pub; + image_transport::Publisher debug_pub; + ros::Publisher pose_pub; + ros::Publisher transform_pub; + ros::Publisher position_pub; + std::string marker_frame; + std::string camera_frame; + std::string reference_frame; + + double marker_size; + int marker_id; + + ros::NodeHandle nh; + image_transport::ImageTransport it; + image_transport::Subscriber image_sub; + + tf::TransformListener _tfListener; + +public: + ArucoSimple() + : cam_info_received(false), + nh("~"), + it(nh) + { + image_sub = it.subscribe("/image", 1, &ArucoSimple::image_callback, this); + cam_info_sub = nh.subscribe("/camera_info", 1, &ArucoSimple::cam_info_callback, this); + + image_pub = it.advertise("result", 1); + debug_pub = it.advertise("debug", 1); + pose_pub = nh.advertise("pose", 100); + transform_pub = nh.advertise("transform", 100); + position_pub = nh.advertise("position", 100); + + nh.param("marker_size", marker_size, 0.05); + nh.param("marker_id", marker_id, 300); + nh.param("reference_frame", reference_frame, ""); + nh.param("camera_frame", camera_frame, ""); + nh.param("marker_frame", marker_frame, ""); + nh.param("image_is_rectified", useRectifiedImages, true); + + ROS_ASSERT(camera_frame != "" && marker_frame != ""); + + if ( reference_frame.empty() ) + reference_frame = camera_frame; + + ROS_INFO("Aruco node started with marker size of %f m and marker id to track: %d", + marker_size, marker_id); + ROS_INFO("Aruco node will publish pose to TF with %s as parent and %s as child.", + reference_frame.c_str(), marker_frame.c_str()); + } + + bool getTransform(const std::string& refFrame, + const std::string& childFrame, + tf::StampedTransform& transform) + { + std::string errMsg; + + if ( !_tfListener.waitForTransform(refFrame, + childFrame, + ros::Time(0), + ros::Duration(0.5), + ros::Duration(0.01), + &errMsg) + ) + { + ROS_ERROR_STREAM("Unable to get pose from TF: " << errMsg); + return false; + } + else + { + try + { + _tfListener.lookupTransform( refFrame, childFrame, + ros::Time(0), //get latest available + transform); + } + catch ( const tf::TransformException& e) + { + ROS_ERROR_STREAM("Error in lookupTransform of " << childFrame << " in " << refFrame); + return false; + } + + } + return true; + } + + + void image_callback(const sensor_msgs::ImageConstPtr& msg) + { + static tf::TransformBroadcaster br; + if(cam_info_received) + { + ros::Time curr_stamp(ros::Time::now()); + cv_bridge::CvImagePtr cv_ptr; + try + { + cv_ptr = cv_bridge::toCvCopy(msg, sensor_msgs::image_encodings::RGB8); + inImage = cv_ptr->image; + + //detection results will go into "markers" + markers.clear(); + //Ok, let's detect + mDetector.detect(inImage, markers, camParam, marker_size, false); + //for each marker, draw info and its boundaries in the image + for(size_t i=0; i(cameraToReference) + * static_cast(rightToLeft) + * transform; + + tf::StampedTransform stampedTransform(transform, curr_stamp, + reference_frame, marker_frame); + br.sendTransform(stampedTransform); + geometry_msgs::PoseStamped poseMsg; + tf::poseTFToMsg(transform, poseMsg.pose); + poseMsg.header.frame_id = reference_frame; + poseMsg.header.stamp = curr_stamp; + pose_pub.publish(poseMsg); + + geometry_msgs::TransformStamped transformMsg; + tf::transformStampedTFToMsg(stampedTransform, transformMsg); + transform_pub.publish(transformMsg); + + geometry_msgs::Vector3Stamped positionMsg; + positionMsg.header = transformMsg.header; + positionMsg.vector = transformMsg.transform.translation; + position_pub.publish(positionMsg); + } + // but drawing all the detected markers + markers[i].draw(inImage,cv::Scalar(0,0,255),2); + } + + //draw a 3d cube in each marker if there is 3d info + if(camParam.isValid() && marker_size!=-1) + { + for(size_t i=0; i 0) + { + //show input with augmented information + cv_bridge::CvImage out_msg; + out_msg.header.stamp = curr_stamp; + out_msg.encoding = sensor_msgs::image_encodings::RGB8; + out_msg.image = inImage; + image_pub.publish(out_msg.toImageMsg()); + } + + if(debug_pub.getNumSubscribers() > 0) + { + //show also the internal image resulting from the threshold operation + cv_bridge::CvImage debug_msg; + debug_msg.header.stamp = curr_stamp; + debug_msg.encoding = sensor_msgs::image_encodings::MONO8; + debug_msg.image = mDetector.getThresholdedImage(); + debug_pub.publish(debug_msg.toImageMsg()); + } + } + catch (cv_bridge::Exception& e) + { + ROS_ERROR("cv_bridge exception: %s", e.what()); + return; + } + } + } + + // wait for one camerainfo, then shut down that subscriber + void cam_info_callback(const sensor_msgs::CameraInfo &msg) + { + camParam = aruco_ros::rosCameraInfo2ArucoCamParams(msg, useRectifiedImages); + + // handle cartesian offset between stereo pairs + // see the sensor_msgs/CamaraInfo documentation for details + rightToLeft.setIdentity(); + rightToLeft.setOrigin( + tf::Vector3( + -msg.P[3]/msg.P[0], + -msg.P[7]/msg.P[5], + 0.0)); + + cam_info_received = true; + cam_info_sub.shutdown(); + } +}; + + +int main(int argc,char **argv) +{ + ros::init(argc, argv, "aruco_simple"); + + ArucoSimple node; + + ros::spin(); +} diff --git a/pool/shard001/C++/0023600_Widget.cpp b/pool/shard001/C++/0023600_Widget.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ba81474cb77b5228dd9dc5791af639ce5e3e578c --- /dev/null +++ b/pool/shard001/C++/0023600_Widget.cpp @@ -0,0 +1,48 @@ +#ifdef OCGUI_IMPLEMENTATION__ + +#include + +namespace OCGui +{ + + static Widget* m_childBeingDragged = NULL; + + bool Widget::HandleEvents(Vec2&& position, Vec2&& size) + { + if (ImGui::IsItemHovered()) { + if (ImGui::IsMouseClicked(0)) { + OnMouseClick(MouseEvent()); + return true; + } + else if (ImGui::IsMouseDown(0)) { + OnMouseDown(MouseEvent()); + return true; + } + else if (ImGui::IsMouseReleased(0)) + { + OnMouseRelease(MouseEvent()); + return true; + } + + // Check for drop event + if(m_childBeingDragged) + { + if (m_childBeingDragged != this) + OnDrop(DropEvent(m_childBeingDragged)); + m_childBeingDragged = NULL; + } + + } + + if (ImGui::IsItemActive() && ImGui::IsMouseDragging()) { + OnDrag(DragEvent(ImGui::GetMouseDragDelta())); + m_childBeingDragged = this; + return true; + } + + return false; + } + +} /* OCGui */ + +#endif diff --git a/pool/shard001/C++/0023603_ProgrammerBase.cpp b/pool/shard001/C++/0023603_ProgrammerBase.cpp new file mode 100644 index 0000000000000000000000000000000000000000..070116b06f43f291a67fc283c83c08757a09f867 --- /dev/null +++ b/pool/shard001/C++/0023603_ProgrammerBase.cpp @@ -0,0 +1,62 @@ +#include "ProgrammerBase.h" +#include "IDeviceCommunicator.h" +#include "OutputCollector.h" + +namespace { + +/** + * Functions passed to Cypress Bootloader API. + * Need to be global variables so that the Read and Write C functions can see + * the open USB device and the verbosity. + */ +IDeviceCommunicator * psocDevice; +extern "C" int openConnection () +{ + return psocDevice->openConnection(); +} +extern "C" int closeConnection () +{ + return psocDevice->closeConnection(); +} +extern "C" int readData (char unsigned * buffer, int length) +{ + return psocDevice->readData(buffer,length); +} +extern "C" int writeData (char unsigned * buffer, int length) +{ + return psocDevice->writeData(buffer,length); +} +extern "C" void progressUpdate (char unsigned arrayId, int unsigned short rowNr) +{ + psocDevice->progressUpdate(arrayId,rowNr); +} + +} // namespace { + +ProgrammerBase::ProgrammerBase (QFileInfo & fileInfo, IDeviceCommunicator * device_) +: file(fileInfo) +, device(device_) +{ + psocDevice = device.get(); +} + +void ProgrammerBase::setOutput (OutputCollector * output) +{ + this->output = output; +} + +CyBtldr_CommunicationsData ProgrammerBase::getCybtldrCommPack () const +{ + static CyBtldr_CommunicationsData bundle; + bundle.OpenConnection = openConnection; + bundle.CloseConnection = closeConnection; + bundle.ReadData = readData; + bundle.WriteData = writeData; + bundle.MaxTransferSize = psocDevice->getBufferSize(); + return bundle; +} + +CyBtldr_ProgressUpdate * ProgrammerBase::getCybtldrProgressUpdate () const +{ + return progressUpdate; +} diff --git a/pool/shard001/C++/0023605_MAX31855.cpp b/pool/shard001/C++/0023605_MAX31855.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5c8bef42179af5180449bcadf21ac3a6387accf7 --- /dev/null +++ b/pool/shard001/C++/0023605_MAX31855.cpp @@ -0,0 +1,230 @@ +/******************************************************************************* +* MAX31855 Library +* Version: 1.10 +* Date: 24-07-2012 +* Company: Rocket Scream Electronics +* Website: www.rocketscream.com +* +* This is a MAX31855 library for Arduino. Please check our wiki +* (www.rocketscream.com/wiki) for more information on using this piece of +* library. +* +* This library is licensed under Creative Commons Attribution-ShareAlike 3.0 +* Unported License. +* +* Revision Description +* ======== =========== +* 1.10 Added negative temperature support for both junction & thermocouple. +* 1.00 Initial public release. +* +*******************************************************************************/ +#include "MAX31855_local.h" + +MAX31855::MAX31855(unsigned char SO, unsigned char CS, unsigned char SCK) +{ + so = SO; + cs = CS; + sck = SCK; + + // MAX31855 data output pin + pinMode(so, INPUT); + // MAX31855 chip select input pin + pinMode(cs, OUTPUT); + // MAX31855 clock input pin + pinMode(sck, OUTPUT); + + // Default output pins state + digitalWrite(cs, HIGH); + digitalWrite(sck, LOW); +} + +/******************************************************************************* +* Name: readThermocouple +* Description: Read the thermocouple temperature either in Degree Celsius or +* Fahrenheit. Internally, the conversion takes place in the +* background within 100 ms. Values are updated only when the CS +* line is high. +* +* Argument Description +* ========= =========== +* 1. unit Unit of temperature required: CELSIUS or FAHRENHEIT +* +* Return Description +* ========= =========== +* temperature Temperature of the thermocouple either in Degree Celsius or +* Fahrenheit. If fault is detected, FAULT_OPEN, FAULT_SHORT_GND or +* FAULT_SHORT_VCC will be returned. These fault values are outside +* of the temperature range the MAX31855 is capable of. +*******************************************************************************/ +double MAX31855::readThermocouple(unit_t unit) +{ + unsigned long data; + double temperature; + + // Initialize temperature + temperature = 0; + + // Shift in 32-bit of data from MAX31855 + data = readData(); + + // If fault is detected + if (data & 0x00010000) + { + // Check for fault type (3 LSB) + switch (data & 0x00000007) + { + // Open circuit + case 0x01: + temperature = FAULT_OPEN; + break; + + // Thermocouple short to GND + case 0x02: + temperature = FAULT_SHORT_GND; + break; + + // Thermocouple short to VCC + case 0x04: + temperature = FAULT_SHORT_VCC; + break; + } + } + // No fault detected + else + { + // Retrieve thermocouple temperature data and strip redundant data + data = data >> 18; + // Bit-14 is the sign + temperature = (data & 0x00001FFF); + + // Check for negative temperature + if (data & 0x00002000) + { + // 2's complement operation + // Invert + data = ~data; + // Ensure operation involves lower 13-bit only + temperature = data & 0x00001FFF; + // Add 1 to obtain the positive number + temperature += 1; + // Make temperature negative + temperature *= -1; + } + + // Convert to Degree Celsius + temperature *= 0.25; + + // If temperature unit in Fahrenheit is desired + if (unit == FAHRENHEIT) + { + // Convert Degree Celsius to Fahrenheit + temperature = (temperature * 9.0/5.0)+ 32; + } + } + return (temperature); +} + +/******************************************************************************* +* Name: readJunction +* Description: Read the thermocouple temperature either in Degree Celsius or +* Fahrenheit. Internally, the conversion takes place in the +* background within 100 ms. Values are updated only when the CS +* line is high. +* +* Argument Description +* ========= =========== +* 1. unit Unit of temperature required: CELSIUS or FAHRENHEIT +* +* Return Description +* ========= =========== +* temperature Temperature of the cold junction either in Degree Celsius or +* Fahrenheit. +* +*******************************************************************************/ +double MAX31855::readJunction(unit_t unit) +{ + double temperature; + unsigned long data; + + // Shift in 32-bit of data from MAX31855 + data = readData(); + + // Strip fault data bits & reserved bit + data = data >> 4; + // Bit-12 is the sign + temperature = (data & 0x000007FF); + + // Check for negative temperature + if (data & 0x00000800) + { + // 2's complement operation + // Invert + data = ~data; + // Ensure operation involves lower 11-bit only + temperature = data & 0x000007FF; + // Add 1 to obtain the positive number + temperature += 1; + // Make temperature negative + temperature *= -1; + } + + // Convert to Degree Celsius + temperature *= 0.0625; + + // If temperature unit in Fahrenheit is desired + if (unit == FAHRENHEIT) + { + // Convert Degree Celsius to Fahrenheit + temperature = (temperature * 9.0/5.0)+ 32; + } + + // Return the temperature + return (temperature); +} + +/******************************************************************************* +* Name: readData +* Description: Shift in 32-bit of data from MAX31855 chip. Minimum clock pulse +* width is 100 ns. No delay is required in this case. +* +* Argument Description +* ========= =========== +* 1. NIL +* +* Return Description +* ========= =========== +* data 32-bit of data acquired from the MAX31855 chip. +* +*******************************************************************************/ +unsigned long MAX31855::readData() +{ + int bitCount; + unsigned long data; + + // Clear data + data = 0; + + // Select the MAX31855 chip + digitalWrite(cs, LOW); + + // Shift in 32-bit of data + for (bitCount = 31; bitCount >= 0; bitCount--) + { + digitalWrite(sck, HIGH); + + // If data bit is high + if (digitalRead(so)) + { + // Need to type cast data type to unsigned long, else compiler will + // truncate to 16-bit + data |= ((unsigned long)1 << bitCount); + } + + digitalWrite(sck, LOW); + } + + // Deselect MAX31855 chip + digitalWrite(cs, HIGH); + + return(data); +} \ No newline at end of file diff --git a/pool/shard001/C++/0023611_main.cpp b/pool/shard001/C++/0023611_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f6831b3404c6f27b4f54321f3e4d6145d965d30e --- /dev/null +++ b/pool/shard001/C++/0023611_main.cpp @@ -0,0 +1,83 @@ +/** + * Copyright (C) 2001-2015 Klaralvdalens Datakonsult AB. All rights reserved. + * + * This file is part of the KD Chart library. + * + * 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 . + */ + +#include +#include +#include +#include +#include + +using namespace KChart; + +int main( int argc, char** argv ) { + QApplication app( argc, argv ); + + Widget widget; + widget.resize( 600, 600 ); + + QVector< QPair > vec0; + QVector< qreal > vec1, vec2; + + vec1 << 25 << 16 << 9 << 4 << 1 << 0 + << 1 << 4 << 9 << 16 << 25; + + // assign your datasets + // while setting the legend + // items text + widget.setDataset( 0, vec1, "vec1" ); + + + // add and position + widget.addLegend(Position::North); + + // configure the axes + CartesianAxis *xAxis = new CartesianAxis( widget.lineDiagram() ); + CartesianAxis *yAxis = new CartesianAxis (widget.lineDiagram() ); + xAxis->setPosition ( CartesianAxis::Bottom ); + yAxis->setPosition ( CartesianAxis::Left ); + xAxis->setTitleText ( "Abscissa bottom position" ); + yAxis->setTitleText ( "Ordinate left position" ); + + // configure Xaxis labels + // no need to re-write labels it iterates until all + // labels are written + QStringList daysOfWeek; + daysOfWeek << "Monday" << "Tuesday" << "Wednesday"; + QStringList shortDays; + shortDays << "Mon" << "Tue" << "Wed"; + + // set user configured x axis labels + xAxis->setLabels( daysOfWeek ); + xAxis->setShortLabels( shortDays ); + + widget.lineDiagram()->addAxis( xAxis ); + widget.lineDiagram()->addAxis( yAxis ); + + // show data values + DataValueAttributes a( widget.lineDiagram()->dataValueAttributes() ); + a.setVisible( true ); + widget.lineDiagram()->setDataValueAttributes( a ); + + // make sure data values are displayed at the borders + widget.setGlobalLeading( 20, 20, 20, 20 ); + + widget.show(); + + return app.exec(); +} diff --git a/pool/shard001/C++/0023612_scc.cpp b/pool/shard001/C++/0023612_scc.cpp new file mode 100644 index 0000000000000000000000000000000000000000..24e2564ca52804ab621df0b0fae3b278adbe618e --- /dev/null +++ b/pool/shard001/C++/0023612_scc.cpp @@ -0,0 +1,120 @@ +/* + * Copyright 2017-2018 Tom van Dijk, Johannes Kepler University Linz + * + * 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 // for memset +#include "oink.hpp" + +namespace pg { + +/** + * Tarjan's SCC algorithm, modified to only compute the bottom SCC and avoid disabled nodes. + */ +void +Oink::tarjan(int n, std::vector &res, bool nonempty) +{ + // initialize + unsigned n_nodes = game->nodecount(); + int *low = new int[n_nodes]; + memset(low, 0, sizeof(int[n_nodes])); // TODO: move this array outside the method + int pre = 0; + + // search stack "st" + std::stack st; + st.push(n); + + while (!st.empty()) { // st is never empty + int idx = st.top(); + if (low[idx] == 0) { + // first time we see it + low[idx] = ++pre; + res.push_back(idx); + } + int min = low[idx]; + bool pushed = false; + auto curedge = game->outedges() + game->firstout(idx); + for (int to_idx = *curedge; to_idx != -1; to_idx = *++curedge) { + if (disabled[to_idx]) continue; + if (low[to_idx] == 0) { + // not visited + st.push(to_idx); + pushed = true; + break; + } else { + // visited it, update min + if (low[to_idx] < min) min = low[to_idx]; + } + } + if (pushed) continue; // we pushed... + + if (min < low[idx]) { + low[idx] = min; + st.pop(); + continue; + } + + /** + * At this point, we found a bottom SCC. Now check if it is empty. + * A SCC is "empty" if it contains no edges, i.e., consists of 1 node without self-loops. + */ + + if (nonempty) { + if (res.back() == idx and !game->has_edge(idx, idx)) { + // it has no edges! + res.pop_back(); + st.pop(); + if (st.empty()) break; + continue; + } + } + + // found bottom SCC; remove nodes not in the bottom SCC... + if (res.front() != idx) res.erase(res.begin(), std::find(res.begin(), res.end(), idx)); + break; + } + + delete[] low; +} + +/** + * Find a bottom SCC starting from the first unsolved node. + */ +void +Oink::getBottomSCC(std::vector &scc, bool nonempty) +{ + scc.clear(); + for (int i=0; inodecount(); i++) { + if (!disabled[i]) { + tarjan(i, scc, nonempty); + return; + } + } +} + +/** + * Find a bottom SCC starting from the given node. + */ +void +Oink::getBottomSCC(int start, std::vector &scc, bool nonempty) +{ + scc.clear(); + tarjan(start, scc, nonempty); +} + +} diff --git a/pool/shard001/C++/0023615_javascript_app_modal_dialog_android.cc b/pool/shard001/C++/0023615_javascript_app_modal_dialog_android.cc new file mode 100644 index 0000000000000000000000000000000000000000..5d6242c5552b6770e7fb62a5ed450cc722b81f26 --- /dev/null +++ b/pool/shard001/C++/0023615_javascript_app_modal_dialog_android.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 "chrome/browser/ui/android/javascript_app_modal_dialog_android.h" + +#include "base/android/jni_android.h" +#include "base/android/jni_string.h" +#include "base/strings/utf_string_conversions.h" + +#include "chrome/browser/browser_process.h" +#include "chrome/browser/ui/app_modal_dialogs/app_modal_dialog_queue.h" +#include "chrome/browser/ui/app_modal_dialogs/javascript_app_modal_dialog.h" +#include "content/public/browser/browser_thread.h" +#include "content/public/browser/web_contents.h" +#include "content/public/common/javascript_message_type.h" +#include "jni/JavascriptAppModalDialog_jni.h" +#include "ui/android/window_android.h" + +using base::android::AttachCurrentThread; +using base::android::ConvertUTF16ToJavaString; +using base::android::ScopedJavaGlobalRef; +using base::android::ScopedJavaLocalRef; +using content::BrowserThread; + +// static +NativeAppModalDialog* NativeAppModalDialog::CreateNativeJavaScriptPrompt( + JavaScriptAppModalDialog* dialog, + gfx::NativeWindow parent_window) { + return new JavascriptAppModalDialogAndroid(AttachCurrentThread(), + dialog, parent_window); +} + +JavascriptAppModalDialogAndroid::JavascriptAppModalDialogAndroid( + JNIEnv* env, + JavaScriptAppModalDialog* dialog, + gfx::NativeWindow parent) + : dialog_(dialog), + parent_jobject_weak_ref_(env, parent->GetJavaObject().obj()) { +} + +int JavascriptAppModalDialogAndroid::GetAppModalDialogButtons() const { + NOTIMPLEMENTED(); + return 0; +} + +void JavascriptAppModalDialogAndroid::ShowAppModalDialog() { + DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); + + JNIEnv* env = AttachCurrentThread(); + // Keep a strong ref to the parent window while we make the call to java to + // display the dialog. + ScopedJavaLocalRef parent_jobj = parent_jobject_weak_ref_.get(env); + if (parent_jobj.is_null()) { + CancelAppModalDialog(); + return; + } + + ScopedJavaLocalRef dialog_object; + ScopedJavaLocalRef title = + ConvertUTF16ToJavaString(env, dialog_->title()); + ScopedJavaLocalRef message = + ConvertUTF16ToJavaString(env, dialog_->message_text()); + + switch (dialog_->javascript_message_type()) { + case content::JAVASCRIPT_MESSAGE_TYPE_ALERT: { + dialog_object = Java_JavascriptAppModalDialog_createAlertDialog(env, + title.obj(), message.obj(), + dialog_->display_suppress_checkbox()); + break; + } + case content::JAVASCRIPT_MESSAGE_TYPE_CONFIRM: { + if (dialog_->is_before_unload_dialog()) { + dialog_object = Java_JavascriptAppModalDialog_createBeforeUnloadDialog( + env, title.obj(), message.obj(), dialog_->is_reload(), + dialog_->display_suppress_checkbox()); + } else { + dialog_object = Java_JavascriptAppModalDialog_createConfirmDialog(env, + title.obj(), message.obj(), + dialog_->display_suppress_checkbox()); + } + break; + } + case content::JAVASCRIPT_MESSAGE_TYPE_PROMPT: { + ScopedJavaLocalRef default_prompt_text = + ConvertUTF16ToJavaString(env, dialog_->default_prompt_text()); + dialog_object = Java_JavascriptAppModalDialog_createPromptDialog(env, + title.obj(), message.obj(), + dialog_->display_suppress_checkbox(), default_prompt_text.obj()); + break; + } + default: + NOTREACHED(); + } + + // Keep a ref to the java side object until we get a confirm or cancel. + dialog_jobject_.Reset(dialog_object); + + Java_JavascriptAppModalDialog_showJavascriptAppModalDialog(env, + dialog_object.obj(), parent_jobj.obj(), + reinterpret_cast(this)); +} + +void JavascriptAppModalDialogAndroid::ActivateAppModalDialog() { + ShowAppModalDialog(); +} + +void JavascriptAppModalDialogAndroid::CloseAppModalDialog() { + CancelAppModalDialog(); +} + +void JavascriptAppModalDialogAndroid::AcceptAppModalDialog() { + string16 prompt_text; + dialog_->OnAccept(prompt_text, false); + delete this; +} + +void JavascriptAppModalDialogAndroid::DidAcceptAppModalDialog( + JNIEnv* env, jobject, jstring prompt, bool should_suppress_js_dialogs) { + string16 prompt_text = base::android::ConvertJavaStringToUTF16(env, prompt); + dialog_->OnAccept(prompt_text, should_suppress_js_dialogs); + delete this; +} + +void JavascriptAppModalDialogAndroid::CancelAppModalDialog() { + dialog_->OnCancel(false); + delete this; +} + +void JavascriptAppModalDialogAndroid::DidCancelAppModalDialog( + JNIEnv* env, jobject, bool should_suppress_js_dialogs) { + dialog_->OnCancel(should_suppress_js_dialogs); + delete this; +} + +const ScopedJavaGlobalRef& + JavascriptAppModalDialogAndroid::GetDialogObject() const { + return dialog_jobject_; +} + +// static +jobject GetCurrentModalDialog(JNIEnv* env, jclass clazz) { + AppModalDialog* dialog = AppModalDialogQueue::GetInstance()->active_dialog(); + if (!dialog || !dialog->native_dialog()) + return NULL; + + JavascriptAppModalDialogAndroid* js_dialog = + static_cast(dialog->native_dialog()); + return js_dialog->GetDialogObject().obj(); +} + +// static +bool JavascriptAppModalDialogAndroid::RegisterJavascriptAppModalDialog( + JNIEnv* env) { + return RegisterNativesImpl(env); +} + +JavascriptAppModalDialogAndroid::~JavascriptAppModalDialogAndroid() { + JNIEnv* env = AttachCurrentThread(); + // In case the dialog is still displaying, tell it to close itself. + // This can happen if you trigger a dialog but close the Tab before it's + // shown, and then accept the dialog. + if (!dialog_jobject_.is_null()) + Java_JavascriptAppModalDialog_dismiss(env, dialog_jobject_.obj()); +} diff --git a/pool/shard001/C++/0023628_DAGISelEmitter.cpp b/pool/shard001/C++/0023628_DAGISelEmitter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d8e78ce55c7b660382630cd998421a2ce7b8746b --- /dev/null +++ b/pool/shard001/C++/0023628_DAGISelEmitter.cpp @@ -0,0 +1,189 @@ +//===- DAGISelEmitter.cpp - Generate an instruction selector --------------===// +// +// 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 tablegen backend emits a DAG instruction selector. +// +//===----------------------------------------------------------------------===// + +#include "CodeGenDAGPatterns.h" +#include "DAGISelMatcher.h" +#include "llvm/Support/Debug.h" +#include "llvm/TableGen/Record.h" +#include "llvm/TableGen/TableGenBackend.h" +using namespace llvm; + +#define DEBUG_TYPE "dag-isel-emitter" + +namespace { +/// DAGISelEmitter - The top-level class which coordinates construction +/// and emission of the instruction selector. +class DAGISelEmitter { + CodeGenDAGPatterns CGP; +public: + explicit DAGISelEmitter(RecordKeeper &R) : CGP(R) {} + void run(raw_ostream &OS); +}; +} // End anonymous namespace + +//===----------------------------------------------------------------------===// +// DAGISelEmitter Helper methods +// + +/// getResultPatternCost - Compute the number of instructions for this pattern. +/// This is a temporary hack. We should really include the instruction +/// latencies in this calculation. +static unsigned getResultPatternCost(TreePatternNode *P, + CodeGenDAGPatterns &CGP) { + if (P->isLeaf()) return 0; + + unsigned Cost = 0; + Record *Op = P->getOperator(); + if (Op->isSubClassOf("Instruction")) { + Cost++; + CodeGenInstruction &II = CGP.getTargetInfo().getInstruction(Op); + if (II.usesCustomInserter) + Cost += 10; + } + for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) + Cost += getResultPatternCost(P->getChild(i), CGP); + return Cost; +} + +/// getResultPatternCodeSize - Compute the code size of instructions for this +/// pattern. +static unsigned getResultPatternSize(TreePatternNode *P, + CodeGenDAGPatterns &CGP) { + if (P->isLeaf()) return 0; + + unsigned Cost = 0; + Record *Op = P->getOperator(); + if (Op->isSubClassOf("Instruction")) { + Cost += Op->getValueAsInt("CodeSize"); + } + for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) + Cost += getResultPatternSize(P->getChild(i), CGP); + return Cost; +} + +namespace { +// PatternSortingPredicate - return true if we prefer to match LHS before RHS. +// In particular, we want to match maximal patterns first and lowest cost within +// a particular complexity first. +struct PatternSortingPredicate { + PatternSortingPredicate(CodeGenDAGPatterns &cgp) : CGP(cgp) {} + CodeGenDAGPatterns &CGP; + + bool operator()(const PatternToMatch *LHS, const PatternToMatch *RHS) { + const TreePatternNode *LT = LHS->getSrcPattern(); + const TreePatternNode *RT = RHS->getSrcPattern(); + + MVT LHSVT = LT->getNumTypes() != 0 ? LT->getSimpleType(0) : MVT::Other; + MVT RHSVT = RT->getNumTypes() != 0 ? RT->getSimpleType(0) : MVT::Other; + if (LHSVT.isVector() != RHSVT.isVector()) + return RHSVT.isVector(); + + if (LHSVT.isFloatingPoint() != RHSVT.isFloatingPoint()) + return RHSVT.isFloatingPoint(); + + // Otherwise, if the patterns might both match, sort based on complexity, + // which means that we prefer to match patterns that cover more nodes in the + // input over nodes that cover fewer. + int LHSSize = LHS->getPatternComplexity(CGP); + int RHSSize = RHS->getPatternComplexity(CGP); + if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost + if (LHSSize < RHSSize) return false; + + // If the patterns have equal complexity, compare generated instruction cost + unsigned LHSCost = getResultPatternCost(LHS->getDstPattern(), CGP); + unsigned RHSCost = getResultPatternCost(RHS->getDstPattern(), CGP); + if (LHSCost < RHSCost) return true; + if (LHSCost > RHSCost) return false; + + unsigned LHSPatSize = getResultPatternSize(LHS->getDstPattern(), CGP); + unsigned RHSPatSize = getResultPatternSize(RHS->getDstPattern(), CGP); + if (LHSPatSize < RHSPatSize) return true; + if (LHSPatSize > RHSPatSize) return false; + + // Sort based on the UID of the pattern, to reflect source order. + // Note that this is not guaranteed to be unique, since a single source + // pattern may have been resolved into multiple match patterns due to + // alternative fragments. To ensure deterministic output, always use + // std::stable_sort with this predicate. + return LHS->ID < RHS->ID; + } +}; +} // End anonymous namespace + + +void DAGISelEmitter::run(raw_ostream &OS) { + emitSourceFileHeader("DAG Instruction Selector for the " + + CGP.getTargetInfo().getName().str() + " target", OS); + + OS << "// *** NOTE: This file is #included into the middle of the target\n" + << "// *** instruction selector class. These functions are really " + << "methods.\n\n"; + + OS << "// If GET_DAGISEL_DECL is #defined with any value, only function\n" + "// declarations will be included when this file is included.\n" + "// If GET_DAGISEL_BODY is #defined, its value should be the name of\n" + "// the instruction selector class. Function bodies will be emitted\n" + "// and each function's name will be qualified with the name of the\n" + "// class.\n" + "//\n" + "// When neither of the GET_DAGISEL* macros is defined, the functions\n" + "// are emitted inline.\n\n"; + + LLVM_DEBUG(errs() << "\n\nALL PATTERNS TO MATCH:\n\n"; + for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(), + E = CGP.ptm_end(); + I != E; ++I) { + errs() << "PATTERN: "; + I->getSrcPattern()->dump(); + errs() << "\nRESULT: "; + I->getDstPattern()->dump(); + errs() << "\n"; + }); + + // Add all the patterns to a temporary list so we can sort them. + std::vector Patterns; + for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(), E = CGP.ptm_end(); + I != E; ++I) + Patterns.push_back(&*I); + + // We want to process the matches in order of minimal cost. Sort the patterns + // so the least cost one is at the start. + std::stable_sort(Patterns.begin(), Patterns.end(), + PatternSortingPredicate(CGP)); + + + // Convert each variant of each pattern into a Matcher. + std::vector PatternMatchers; + for (unsigned i = 0, e = Patterns.size(); i != e; ++i) { + for (unsigned Variant = 0; ; ++Variant) { + if (Matcher *M = ConvertPatternToMatcher(*Patterns[i], Variant, CGP)) + PatternMatchers.push_back(M); + else + break; + } + } + + std::unique_ptr TheMatcher = + std::make_unique(PatternMatchers); + + OptimizeMatcher(TheMatcher, CGP); + //Matcher->dump(); + EmitMatcherTable(TheMatcher.get(), CGP, OS); +} + +namespace llvm { + +void EmitDAGISel(RecordKeeper &RK, raw_ostream &OS) { + DAGISelEmitter(RK).run(OS); +} + +} // End llvm namespace diff --git a/pool/shard001/C++/0023634_squares_of_sorted_array.cpp b/pool/shard001/C++/0023634_squares_of_sorted_array.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8e96d9ea52452ea3152ae0c2d4caa7f06d025158 --- /dev/null +++ b/pool/shard001/C++/0023634_squares_of_sorted_array.cpp @@ -0,0 +1,46 @@ +#include "common_header.h" + + +namespace { + +using ArrayType = std::vector; + +/** Squares of a Sorted Array + * + * @reference https://leetcode.com/problems/squares-of-a-sorted-array/ + * + * Given an integer array nums sorted in non-decreasing order, return an array of the + * squares of each number sorted in non-decreasing order. + * Follow up: Squaring each element and sorting the new array is very trivial, could you + * find an O(n) solution using a different approach? + */ +auto SortedSquares(const ArrayType &nums) { + ArrayType result(nums.size(), 0); + int left = 0, right = nums.size() - 1; + while (left <= right) { + if (std::abs(nums[left]) <= std::abs(nums[right])) { + result[right - left] = nums[right] * nums[right]; + --right; + } else { + result[right - left] = nums[left] * nums[left]; + ++left; + } + } + + return result; +} + +}//namespace + + +const ArrayType SAMPLE1 = {-4, -1, 0, 3, 10}; +const ArrayType EXPECTED1 = {0, 1, 9, 16, 100}; + +const ArrayType SAMPLE2 = {-7, -3, 2, 3, 11}; +const ArrayType EXPECTED2 = {4, 9, 9, 49, 121}; + + +THE_BENCHMARK(SortedSquares, SAMPLE1); + +SIMPLE_TEST(SortedSquares, TestSAMPLE1, EXPECTED1, SAMPLE1); +SIMPLE_TEST(SortedSquares, TestSAMPLE2, EXPECTED2, SAMPLE2); diff --git a/pool/shard001/C++/0023638_jsp-mm.cpp b/pool/shard001/C++/0023638_jsp-mm.cpp new file mode 100644 index 0000000000000000000000000000000000000000..47967576fc54aa540ab9590133598393d20b7a65 --- /dev/null +++ b/pool/shard001/C++/0023638_jsp-mm.cpp @@ -0,0 +1,170 @@ +/* Copyright 2015 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. + */ + +#include "jrt.h" +#include "jsp-mm.h" +#include "mem-allocator.h" +#include "mem-heap.h" + +/** \addtogroup jsparser ECMAScript parser + * @{ + * + * \addtogroup managedmem Managed memory allocation + * @{ + */ + +/** + * Header of a managed block, allocated by parser + */ +typedef struct +{ + mem_cpointer_t prev_block_cp; /**< previous managed block */ + mem_cpointer_t next_block_cp; /**< next managed block */ + + uint32_t padding; /**< padding for alignment */ +} jsp_mm_header_t; + +/** + * Check that alignment of jsp_mm_header_t is MEM_ALIGNMENT + */ +JERRY_STATIC_ASSERT ((sizeof (jsp_mm_header_t) % MEM_ALIGNMENT) == 0); + +/** + * List used for tracking memory blocks + */ +jsp_mm_header_t *jsp_mm_blocks_p = NULL; + +/** + * Initialize managed memory allocator + */ +void +jsp_mm_init (void) +{ + JERRY_ASSERT (jsp_mm_blocks_p == NULL); +} /* jsp_mm_init */ + +/** + * Finalize managed memory allocator + */ +void +jsp_mm_finalize (void) +{ + JERRY_ASSERT (jsp_mm_blocks_p == NULL); +} /* jsp_mm_finalize */ + +/** + * Recommend allocation size + * + * Note: + * The interface is used by collection allocators + * for storage of data that takes the specified + * amount of bytes upon allocation, but probably + * would require more. + * + * To reduce probability of reallocation in future, + * the allocators can request more space in first + * allocation request. + * + * The interface helps to choose appropriate space + * to allocate, considering amount of heap space, + * that would be waste if allocation size + * would not be increased. + * + * @return recommended allocation size + */ +size_t +jsp_mm_recommend_size (size_t minimum_size) /**< minimum required size */ +{ + size_t block_and_header_size = mem_heap_recommend_allocation_size (minimum_size + sizeof (jsp_mm_header_t)); + return block_and_header_size - sizeof (jsp_mm_header_t); +} /* jsp_mm_recommend_size */ + +/** + * Allocate a managed memory block of specified size + * + * @return pointer to data space of allocated block + */ +void* +jsp_mm_alloc (size_t size) /**< size of block to allocate */ +{ + void *ptr_p = mem_heap_alloc_block (size + sizeof (jsp_mm_header_t), MEM_HEAP_ALLOC_SHORT_TERM); + + jsp_mm_header_t *tmem_header_p = (jsp_mm_header_t*) ptr_p; + + tmem_header_p->prev_block_cp = MEM_CP_NULL; + MEM_CP_SET_POINTER (tmem_header_p->next_block_cp, jsp_mm_blocks_p); + + if (jsp_mm_blocks_p != NULL) + { + MEM_CP_SET_POINTER (jsp_mm_blocks_p->prev_block_cp, tmem_header_p); + } + + jsp_mm_blocks_p = tmem_header_p; + + return (void *) (tmem_header_p + 1); +} /* jsp_mm_alloc */ + +/** + * Free a managed memory block + */ +void +jsp_mm_free (void *ptr) /**< pointer to data space of allocated block */ +{ + jsp_mm_header_t *tmem_header_p = ((jsp_mm_header_t *) ptr) - 1; + + jsp_mm_header_t *prev_block_p = MEM_CP_GET_POINTER (jsp_mm_header_t, + tmem_header_p->prev_block_cp); + jsp_mm_header_t *next_block_p = MEM_CP_GET_POINTER (jsp_mm_header_t, + tmem_header_p->next_block_cp); + + if (prev_block_p != NULL) + { + prev_block_p->next_block_cp = tmem_header_p->next_block_cp; + } + else + { + JERRY_ASSERT (jsp_mm_blocks_p == tmem_header_p); + jsp_mm_blocks_p = next_block_p; + } + + if (next_block_p != NULL) + { + next_block_p->prev_block_cp = tmem_header_p->prev_block_cp; + } + + mem_heap_free_block (tmem_header_p); +} /* jsp_mm_free */ + +/** + * Free all currently allocated managed memory blocks + */ +void +jsp_mm_free_all (void) +{ + while (jsp_mm_blocks_p != NULL) + { + jsp_mm_header_t *next_block_p = MEM_CP_GET_POINTER (jsp_mm_header_t, + jsp_mm_blocks_p->next_block_cp); + + mem_heap_free_block (jsp_mm_blocks_p); + + jsp_mm_blocks_p = next_block_p; + } +} /* jsp_mm_free_all */ + +/** + * @} + * @} + */ diff --git a/pool/shard001/C++/0023640_testibqt.cpp b/pool/shard001/C++/0023640_testibqt.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f7bbe8c55beae6af46149d50993eb9d384447042 --- /dev/null +++ b/pool/shard001/C++/0023640_testibqt.cpp @@ -0,0 +1,48 @@ +#include "testibqt.h" +#include + +TestIbQt::TestIbQt(QObject *parent) : QObject(parent) +{ + connect(&ib, SIGNAL(twsConnected()), this, SLOT(onTwsConnected())); + connect(&ib, SIGNAL(managedAccounts(QByteArray)), this, SLOT(onManagedAccounts(QByteArray))); + connect(&ib, SIGNAL(contractDetails(int,ContractDetails)), this, SLOT(onContractDetails(int,ContractDetails))); + connect(&ib, SIGNAL(contractDetailsEnd(int)), this, SLOT(onContractDetailsEnd(int))); +} + +void TestIbQt::run() +{ + ib.connectToTWS(); + reqContractDetails(); +} + +void TestIbQt::onTwsConnected() +{ + qDebug() << "TWS Connected"; +} + +void TestIbQt::onManagedAccounts(const QByteArray &accountsList) +{ + qDebug() << "Managed Accounts:" << accountsList; +} + +void TestIbQt::onContractDetails(int reqId, const ContractDetails &contractDetails) +{ + Q_UNUSED(reqId) + qDebug() << "Sym:" << contractDetails.summary.symbol << "Exp:" << contractDetails.summary.expiry; +} + +void TestIbQt::onContractDetailsEnd(int reqId) +{ + qDebug() << "onContractDetailsEnd:" << reqId; +} + +void TestIbQt::reqContractDetails() +{ + Contract c; + c.symbol = QByteArray("MSFT"); + c.secType = QByteArray("OPT"); + c.exchange = QByteArray("SMART"); + c.currency = QByteArray("USD"); + + ib.reqContractDetails(ib.getTickerId(), c); +} diff --git a/pool/shard001/C++/0023646_InventoryGUI.cpp b/pool/shard001/C++/0023646_InventoryGUI.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c7c5352f6c7f38f86ee9745339d695f6d295db8a --- /dev/null +++ b/pool/shard001/C++/0023646_InventoryGUI.cpp @@ -0,0 +1,96 @@ +#include "InventoryGUI.hpp" + +InventoryGUI::InventoryGUI(size_t itemCount) : items(itemCount) { + InventoryGUI::itemCells = std::vector(); + +} + +void InventoryGUI::addCell(Vec2 pos) { + InventoryGUI::itemCells.push_back(pos); +} + +Vec2 &InventoryGUI::getCell(size_t i) { + return InventoryGUI::itemCells.at(i); +} + +bool InventoryGUI::intersectsCell(size_t i, Vec2 pos, Vec2 offset) { + const Vec2 itemPos = InventoryGUI::getCell(i) + offset; + if (pos.x >= itemPos.x && pos.y >= itemPos.y) { + if (pos.x <= itemPos.x + 32.0 && pos.y <= itemPos.y + 32.0) { + return true; + } + } + + return false; +} + +size_t InventoryGUI::getSize() { + return InventoryGUI::itemCells.size(); +} + +Inventory &InventoryGUI::getItems() { + return InventoryGUI::items; +} + +InventoryStack &InventoryGUI::getSelectedItem() { + return InventoryGUI::selectedItemStack; +} + +void InventoryGUI::render(sf::RenderWindow &target, Vec2 guiOffset, BitmapFont &font) { + Vec2 mousePos(sf::Mouse::getPosition(target).x, sf::Mouse::getPosition(target).y); + + for (size_t i = 0; i < InventoryGUI::itemCells.size(); ++i) { + + /* Try selecting an item */ + if (Input::isMouseClicked(sf::Mouse::Left) && InventoryGUI::intersectsCell(i, mousePos, guiOffset)) { + /* Check if we can stack items of the same type... */ + if (InventoryGUI::items.at(i) == InventoryGUI::selectedItemStack) { + size_t leftover = InventoryGUI::items.at(i).add(InventoryGUI::selectedItemStack.count); + InventoryGUI::selectedItemStack = InventoryStack(leftover, InventoryGUI::items.at(i).type, InventoryGUI::items.at(i).size); + } else { /* ...or swap them */ + InventoryStack lastSelected = InventoryGUI::selectedItemStack; + InventoryGUI::selectedItemStack = InventoryGUI::items.at(i); + InventoryGUI::items.at(i) = lastSelected; + } + } + + if (Input::isMouseClicked(sf::Mouse::Right) && InventoryGUI::intersectsCell(i, mousePos, guiOffset)) { + /* Check if currently an itemstack is selected */ + if (InventoryGUI::selectedItemStack.isFree()) { + size_t items_count = floor(InventoryGUI::items.at(i).count / 2.0); + blockid items_type = InventoryGUI::items.at(i).type; + size_t items_max = InventoryGUI::items.at(i).size; + + InventoryGUI::items.at(i).count -= items_count; + InventoryGUI::selectedItemStack = InventoryStack(items_count, items_type, items_max); + } else { + blockid oneItem = InventoryGUI::selectedItemStack.get(); + if (oneItem < 0) + continue; + + /* If right click with selected item(s) on free cell, place one item in it */ + if (InventoryGUI::items.at(i).isFree()) { + InventoryGUI::selectedItemStack.take(); + InventoryGUI::items.at(i).count = 1; + InventoryGUI::items.at(i).type = oneItem; + } else { /* Right click on already occupied cell, check if same, space left and increase its count by one */ + if (InventoryGUI::items.at(i) == InventoryGUI::selectedItemStack && InventoryGUI::items.at(i).spaceLeft() > 0) { + InventoryGUI::selectedItemStack.take(); + InventoryGUI::items.at(i).count += 1; + } + } + } + } + + + if (InventoryGUI::items.at(i).get() < 0) + continue; + + Vec2 finalPos = InventoryGUI::itemCells.at(i) + guiOffset; + items.at(i).render(target, font, finalPos); + } + + if (!InventoryGUI::selectedItemStack.isFree()) { + InventoryGUI::selectedItemStack.render(target, font, mousePos); + } +} \ No newline at end of file diff --git a/pool/shard001/C++/0023648_OperationCallerC.cpp b/pool/shard001/C++/0023648_OperationCallerC.cpp new file mode 100644 index 0000000000000000000000000000000000000000..89e4e97beba51566c444c7697332ba739e5119b2 --- /dev/null +++ b/pool/shard001/C++/0023648_OperationCallerC.cpp @@ -0,0 +1,281 @@ +/*************************************************************************** + tag: Peter Soetens Wed Jan 18 14:11:40 CET 2006 OperationCallerC.cxx + + OperationCallerC.cxx - description + ------------------- + begin : Wed January 18 2006 + copyright : (C) 2006 Peter Soetens + email : peter.soetens@mech.kuleuven.be + + *************************************************************************** + * 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; * + * version 2 of the License. * + * * + * As a special exception, you may use this file as part of a free * + * software library without restriction. Specifically, if other files * + * instantiate templates or use macros or inline functions from this * + * file, or you compile this file and link it with other files to * + * produce an executable, this file does not by itself cause the * + * resulting executable to be covered by the GNU General Public * + * License. This exception does not however invalidate any other * + * reasons why the executable file might be covered by the GNU General * + * Public 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 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 * + * * + ***************************************************************************/ + + +#include "OperationCallerC.hpp" +#include "../FactoryExceptions.hpp" +#include "DataSourceCommand.hpp" +#include "../Service.hpp" +#include "../Logger.hpp" +#include "Exceptions.hpp" +#include + +namespace RTT { + using namespace detail; + + + class OperationCallerC::D + { + public: + OperationInterfacePart* ofp; + ExecutionEngine* caller; + std::string mname; + std::vector args; + DataSourceBase::shared_ptr rta; + DataSourceBase::shared_ptr m; + DataSourceBase::shared_ptr s; + + void checkAndCreate() { + Logger::In in("OperationCallerC"); + if ( ofp ) { + size_t sz = ofp->arity(); + if ( sz == args.size() ) { + // may throw or return nill + m = ofp->produce(args, caller ); + try { + s = ofp->produceSend(args, caller ); + } catch( no_asynchronous_operation_exception const& /*e*/) { + // leave s empty. + } + args.clear(); + if ( !m ) + return; + if (rta) + try { + m = new DataSourceCommand( rta->updateAction( m.get() ) ); + } catch( bad_assignment& /*ba*/ ) { + log(Error) << "Error in OperationCallerC::ret : can not convert return value of type "<< m->getType() << " to given type "<< rta->getType()<args.push_back( na ); + this->checkAndCreate(); + } + + void ret(AttributeBase* r) + { + this->rta = r->getDataSource(); + } + + void ret(DataSourceBase::shared_ptr d) + { + this->rta = d; + } + + D( OperationInterfacePart* mr, const std::string& name, ExecutionEngine* caller) + : ofp(mr), caller(caller), mname(name), rta(), m(), s() + { + this->checkAndCreate(); + } + + D(const D& other) + : ofp(other.ofp), caller(other.caller), mname(other.mname), + args( other.args ), rta( other.rta ), m( other.m ), s(other.s) + { + } + + ~D() + { + } + + }; + + OperationCallerC::OperationCallerC() + : d(0), m() + { + } + + OperationCallerC::OperationCallerC(OperationInterfacePart* mr, const std::string& name, ExecutionEngine* caller) + : d( mr ? new D( mr, name, caller) : 0 ), m(), ofp(mr), mname(name) + { + if ( d && d->m ) { + this->m = d->m; + this->s = d->s; + delete d; + d = 0; + } else { + if (mr == 0) + log(Error) <<"Can not construct OperationCallerC for '"<newarg( a ); + else { + Logger::log() <m ) { + this->m = d->m; + this->s = d->s; + delete d; + d = 0; + } + return *this; + } + + OperationCallerC& OperationCallerC::ret( AttributeBase* r ) + { + if (d) + d->ret( r ); + else { + if (m) { + try { + m = new DataSourceCommand(r->getDataSource()->updateAction( m.get() ) ); + } catch( bad_assignment& /*ba*/ ) { + log(Error) << "Error in OperationCallerC::ret : can not convert return value of type "<< m->getType() << " to given type "<< r->getDataSource()->getType()<ret( r ); + else { + // no d, store manually: + if (m) + m = new DataSourceCommand(r->updateAction( m.get() ) ); + else + log(Error) <<"Can not add return argument to invalid OperationCallerC."<evaluate(); + else { + Logger::log() <ofp->arity(); + Logger::log() <mname+"'"<args.size() <ofp) + DataSourceBase::shared_ptr dummy = d->ofp->produce( d->args, d->caller ); + else + throw name_not_found_exception( d->mname ); + } + } + + SendHandleC OperationCallerC::send() { + DataSourceBase::shared_ptr h; + try { + h = ofp->produceHandle(); + } catch( no_asynchronous_operation_exception const& nao) { + log(Error) <<"OperationCallerC::send(): Can not send the '" << ofp->getName() << "' operation:" << nao.what() << endlog(); + return SendHandleC(); + } + if (s) { + // evaluate and copy result of s to handle and pass handle to SendHandleC. +#ifndef NDEBUG + bool result = +#endif + h->update( s.get() ); + assert( result ); + return SendHandleC( s, h, ofp, mname ); + } + else { + Logger::log() <ofp->arity(); + Logger::log() <mname+"'"<args.size() < scopedEventQueue; + return scopedEventQueue; +} + +void ScopedEventQueue::enqueueEvent(PassRefPtr event) +{ + if (m_scopingLevel) + m_queuedEvents.append(event); + else + dispatchEvent(event); +} + +void ScopedEventQueue::dispatchEvent(PassRefPtr event) const +{ + ASSERT(event->target()); + // Store the target in a local variable to avoid possibly dereferencing a nullified PassRefPtr after it's passed on. + Node* node = event->target()->toNode(); + EventDispatcher::dispatchEvent(node, event); +} + +void ScopedEventQueue::dispatchAllEvents() +{ + Vector> queuedEvents = std::move(m_queuedEvents); + for (size_t i = 0; i < queuedEvents.size(); i++) + dispatchEvent(queuedEvents[i].release()); +} + +void ScopedEventQueue::incrementScopingLevel() +{ + m_scopingLevel++; +} + +void ScopedEventQueue::decrementScopingLevel() +{ + ASSERT(m_scopingLevel); + m_scopingLevel--; + if (!m_scopingLevel) + dispatchAllEvents(); +} + +} diff --git a/pool/shard001/C++/0023665_nopout.cpp b/pool/shard001/C++/0023665_nopout.cpp new file mode 100644 index 0000000000000000000000000000000000000000..92d6d040fd9bf684c71c586e2bba452e4f2e51e5 --- /dev/null +++ b/pool/shard001/C++/0023665_nopout.cpp @@ -0,0 +1,92 @@ +/** + @file nopout.cpp + @brief iSCSI Nop-Out handler + @author Eiji Sugiura + @version $Id: nopout.cpp 277 2007-08-14 14:44:47Z sugiura $ + */ + +#include "common.h" +#include "session.h" +#include "logger.h" +#include "iscsi/nopout.h" +#include "iscsi/nopin.h" + +bool NopOutParser::valid() const +{ + /** Check OpCode */ + if(getOpCode() != iSCSI_OP_NOOP_OUT){ + LOG4CXX_ERROR(logger, "Invalid OpCode"); + return false; + } + /** Check Final flag */ + if(!(isFinal())){ + LOG4CXX_ERROR(logger, "Initiator MUST set final bit"); + return false; + } + /** Check ITT */ + if(getITT() == ISCSI_RSVD_TASK_TAG){ + LOG4CXX_ERROR(logger, "NopOut : Invalid ITT"); + return false; + } + /** Check TTT */ + if(getTTT() != ISCSI_RSVD_TASK_TAG){ + /** @todo : Only Ping Nop-Out request is supported */ + LOG4CXX_ERROR(logger, "NopOut as ping echo is not supported"); + return false; + } + /** Check ping data length */ + if(getDlength() > 0){ + /** @todo : Support ping data */ + LOG4CXX_ERROR(logger, "Ping data not supported, yet"); + return false; + } + + /** @todo : Check SN */ + + return true; +} + +bool NopOutHandler::handle(iSCSISessionPtr parent, const socket_t fd) +{ + LOG4CXX_DEBUG(logger, "NopOut"); + NopOutHeader *bhs = reinterpret_cast(parent->frontToken()); + NopOutParser req(bhs); + if(!req.valid()){ + LOG4CXX_ERROR(logger, "Invalid Nop-Out request"); + return false; + } + + /** update CMDSN */ + if(!req.isImmediateCmd()) + parent->advanceCMDSNs(); + + NopInGenerator reply; + reply.setITT(req.getITT()); + /** ...then, set Reserved Task Tag, too */ + reply.setTTT(ISCSI_RSVD_TASK_TAG); + + /** update STATSN */ + iSCSIConnectionPtr conn = parent->connection.find(fd); + reply.setSTATSN(conn->getSTATSN()); + conn->advanceSTATSN(); + + reply.setEXPCMDSN(parent->getEXPCMDSN()); + reply.setMAXCMDSN(parent->getMAXCMDSN()); + + /** convert reply -> send task */ + parent->sendtask.push(SendTaskPtr(new SendTask(parent, fd, reply.serialize()))); + return true; +} + +NopOutGenerator::NopOutGenerator() +{ + cbuf = CommonBufPtr(new CommonBuf()); + bhs = reinterpret_cast(cbuf->cur()); + cbuf->stepForwardTail(sizeof(*bhs)); +#ifdef BHS_DEBUG + LOG4CXX_DEBUG(logger, "Reply BHS at " + + boost::lexical_cast(bhs)); +#endif + bhs->opcode = iSCSI_OP_NOOP_OUT; + bhs->flags = ISCSI_FLAG_FINAL; +} diff --git a/pool/shard001/C++/0023673_write_batch_test.cc b/pool/shard001/C++/0023673_write_batch_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..ff7aff8366277ef33e29101e8a39c85fbc1eea69 --- /dev/null +++ b/pool/shard001/C++/0023673_write_batch_test.cc @@ -0,0 +1,148 @@ +// Copyright (c) 2014, Facebook, Inc. All rights reserved. +// This source code is licensed under the BSD-style license found in the +// LICENSE file in the root directory of this source tree. An additional grant +// of patent rights can be found in the PATENTS file in the same directory. +// +// This file implements the "bridge" between Java and C++ and enables +// calling c++ rocksdb::WriteBatch methods testing from Java side. +#include + +#include "db/memtable.h" +#include "db/write_batch_internal.h" +#include "db/writebuffer.h" +#include "include/org_rocksdb_WriteBatch.h" +#include "include/org_rocksdb_WriteBatch_Handler.h" +#include "include/org_rocksdb_WriteBatchTest.h" +#include "include/org_rocksdb_WriteBatchTestInternalHelper.h" +#include "rocksdb/db.h" +#include "rocksdb/env.h" +#include "rocksdb/immutable_options.h" +#include "rocksdb/memtablerep.h" +#include "rocksdb/status.h" +#include "rocksdb/write_batch.h" +#include "rocksjni/portal.h" +#include "util/logging.h" +#include "util/scoped_arena_iterator.h" +#include "util/testharness.h" + +/* + * Class: org_rocksdb_WriteBatchTest + * Method: getContents + * Signature: (Lorg/rocksdb/WriteBatch;)[B + */ +jbyteArray Java_org_rocksdb_WriteBatchTest_getContents( + JNIEnv* env, jclass jclazz, jobject jobj) { + rocksdb::WriteBatch* b = rocksdb::WriteBatchJni::getHandle(env, jobj); + assert(b != nullptr); + + // todo: Currently the following code is directly copied from + // db/write_bench_test.cc. It could be implemented in java once + // all the necessary components can be accessed via jni api. + + rocksdb::InternalKeyComparator cmp(rocksdb::BytewiseComparator()); + auto factory = std::make_shared(); + rocksdb::Options options; + rocksdb::WriteBuffer wb(options.db_write_buffer_size); + options.memtable_factory = factory; + rocksdb::MemTable* mem = new rocksdb::MemTable( + cmp, rocksdb::ImmutableCFOptions(options), + rocksdb::MutableCFOptions(options, rocksdb::ImmutableCFOptions(options)), + &wb); + mem->Ref(); + std::string state; + rocksdb::ColumnFamilyMemTablesDefault cf_mems_default(mem); + rocksdb::Status s = + rocksdb::WriteBatchInternal::InsertInto(b, &cf_mems_default); + int count = 0; + rocksdb::Arena arena; + rocksdb::ScopedArenaIterator iter(mem->NewIterator( + rocksdb::ReadOptions(), &arena)); + for (iter->SeekToFirst(); iter->Valid(); iter->Next()) { + rocksdb::ParsedInternalKey ikey; + memset(reinterpret_cast(&ikey), 0, sizeof(ikey)); + assert(rocksdb::ParseInternalKey(iter->key(), &ikey)); + switch (ikey.type) { + case rocksdb::kTypeValue: + state.append("Put("); + state.append(ikey.user_key.ToString()); + state.append(", "); + state.append(iter->value().ToString()); + state.append(")"); + count++; + break; + case rocksdb::kTypeMerge: + state.append("Merge("); + state.append(ikey.user_key.ToString()); + state.append(", "); + state.append(iter->value().ToString()); + state.append(")"); + count++; + break; + case rocksdb::kTypeDeletion: + state.append("Delete("); + state.append(ikey.user_key.ToString()); + state.append(")"); + count++; + break; + default: + assert(false); + break; + } + state.append("@"); + state.append(rocksdb::NumberToString(ikey.sequence)); + } + if (!s.ok()) { + state.append(s.ToString()); + } else if (count != rocksdb::WriteBatchInternal::Count(b)) { + state.append("CountMismatch()"); + } + delete mem->Unref(); + + jbyteArray jstate = env->NewByteArray(static_cast(state.size())); + env->SetByteArrayRegion(jstate, 0, static_cast(state.size()), + reinterpret_cast(state.c_str())); + + return jstate; +} + +/* + * Class: org_rocksdb_WriteBatchTestInternalHelper + * Method: setSequence + * Signature: (Lorg/rocksdb/WriteBatch;J)V + */ +void Java_org_rocksdb_WriteBatchTestInternalHelper_setSequence( + JNIEnv* env, jclass jclazz, jobject jobj, jlong jsn) { + rocksdb::WriteBatch* wb = rocksdb::WriteBatchJni::getHandle(env, jobj); + assert(wb != nullptr); + + rocksdb::WriteBatchInternal::SetSequence( + wb, static_cast(jsn)); +} + +/* + * Class: org_rocksdb_WriteBatchTestInternalHelper + * Method: sequence + * Signature: (Lorg/rocksdb/WriteBatch;)J + */ +jlong Java_org_rocksdb_WriteBatchTestInternalHelper_sequence( + JNIEnv* env, jclass jclazz, jobject jobj) { + rocksdb::WriteBatch* wb = rocksdb::WriteBatchJni::getHandle(env, jobj); + assert(wb != nullptr); + + return static_cast(rocksdb::WriteBatchInternal::Sequence(wb)); +} + +/* + * Class: org_rocksdb_WriteBatchTestInternalHelper + * Method: append + * Signature: (Lorg/rocksdb/WriteBatch;Lorg/rocksdb/WriteBatch;)V + */ +void Java_org_rocksdb_WriteBatchTestInternalHelper_append( + JNIEnv* env, jclass jclazz, jobject jwb1, jobject jwb2) { + rocksdb::WriteBatch* wb1 = rocksdb::WriteBatchJni::getHandle(env, jwb1); + assert(wb1 != nullptr); + rocksdb::WriteBatch* wb2 = rocksdb::WriteBatchJni::getHandle(env, jwb2); + assert(wb2 != nullptr); + + rocksdb::WriteBatchInternal::Append(wb1, wb2); +} diff --git a/pool/shard001/C++/0023684_macos.cpp b/pool/shard001/C++/0023684_macos.cpp new file mode 100644 index 0000000000000000000000000000000000000000..087b421b2010c0850ac521048d53d99592470fa7 --- /dev/null +++ b/pool/shard001/C++/0023684_macos.cpp @@ -0,0 +1,60 @@ +#include "macos.hpp" + +#ifdef __MACOS__ + +#include + + +namespace tuttle { +namespace common { + +std::string CFStringContainer::toString( CFStringRef cfString ) +{ + CFIndex length = CFStringGetLength( cfString ); + CFIndex size = CFStringGetMaximumSizeForEncoding(length, kCFStringEncodingUTF8); + char *buffer = new char[size]; + Boolean worked = CFStringGetCString( cfString, buffer, size, kCFStringEncodingUTF8 ); + if( worked ) { + std::string result( buffer ); + delete [] buffer; + return result; + } + delete [] buffer; + return std::string(); +} + +CFStringContainer::operator std::string() const +{ + return str(); +} + +const std::string& CFStringContainer::str() const +{ + if( _string.empty() && _type ) + const_cast(this)->_string = toString(_type); + return _string; +} + +CFStringRef CFStringContainer::toCFStringRef( const std::string& s ) +{ + return CFStringCreateWithCString(kCFAllocatorDefault, s.c_str(), kCFStringEncodingUTF8); +} + +CFStringContainer::operator CFStringRef() const +{ + if( !_type ) + { + const_cast ( this )->_type = + CFStringCreateWithCharactersNoCopy( 0, + reinterpret_cast ( _string.c_str() ), + _string.size(), + kCFAllocatorNull ); + } + return _type; +} + + +} +} + +#endif diff --git a/pool/shard001/C++/0023686_corevideosource.cpp b/pool/shard001/C++/0023686_corevideosource.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0a71b9b14d9794077b1a0e8838b79b5cb9611527 --- /dev/null +++ b/pool/shard001/C++/0023686_corevideosource.cpp @@ -0,0 +1,120 @@ +/* + Copyright © 2015 by The qTox Project + + This file is part of qTox, a Qt-based graphical interface for Tox. + + qTox is libre 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. + + qTox 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 qTox. If not, see . +*/ + + +extern "C" { +#include +} +#include "corevideosource.h" +#include "videoframe.h" + +CoreVideoSource::CoreVideoSource() + : subscribers{0}, deleteOnClose{false}, + stopped{false} +{ +} + +void CoreVideoSource::pushFrame(const vpx_image_t* vpxframe) +{ + if (stopped) + return; + + QMutexLocker locker(&biglock); + + std::shared_ptr vframe; + AVFrame* avframe; + uint8_t* buf; + int width = vpxframe->d_w, height = vpxframe->d_h; + int dstStride, srcStride, minStride; + + if (subscribers <= 0) + return; + + avframe = av_frame_alloc(); + if (!avframe) + return; + avframe->width = width; + avframe->height = height; + avframe->format = AV_PIX_FMT_YUV420P; + + buf = (uint8_t*)av_malloc(avpicture_get_size(AV_PIX_FMT_YUV420P, width, height)); + if (!buf) + { + av_frame_free(&avframe); + return; + } + avframe->opaque = buf; + + avpicture_fill((AVPicture*)avframe, buf, AV_PIX_FMT_YUV420P, width, height); + + dstStride=avframe->linesize[0], srcStride=vpxframe->stride[0], minStride=std::min(dstStride, srcStride); + for (int i=0; idata[0]+dstStride*i, vpxframe->planes[0]+srcStride*i, minStride); + dstStride=avframe->linesize[1], srcStride=vpxframe->stride[1], minStride=std::min(dstStride, srcStride); + for (int i=0; idata[1]+dstStride*i, vpxframe->planes[1]+srcStride*i, minStride); + dstStride=avframe->linesize[2], srcStride=vpxframe->stride[2], minStride=std::min(dstStride, srcStride); + for (int i=0; idata[2]+dstStride*i, vpxframe->planes[2]+srcStride*i, minStride); + + vframe = std::make_shared(avframe); + emit frameAvailable(vframe); +} + +bool CoreVideoSource::subscribe() +{ + QMutexLocker locker(&biglock); + ++subscribers; + return true; +} + +void CoreVideoSource::unsubscribe() +{ + biglock.lock(); + if (--subscribers == 0) + { + if (deleteOnClose) + { + biglock.unlock(); + // DANGEROUS: No member access after this point, that's why we manually unlock + delete this; + return; + } + } + biglock.unlock(); +} + +void CoreVideoSource::setDeleteOnClose(bool newstate) +{ + QMutexLocker locker(&biglock); + deleteOnClose = newstate; +} + +void CoreVideoSource::stopSource() +{ + QMutexLocker locker(&biglock); + stopped = true; + emit sourceStopped(); +} + +void CoreVideoSource::restartSource() +{ + QMutexLocker locker(&biglock); + stopped = false; +} diff --git a/pool/shard001/C++/0023687_ForceEngine.cpp b/pool/shard001/C++/0023687_ForceEngine.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cc11ab29dfea69752faf7e441088ecbce3b90043 --- /dev/null +++ b/pool/shard001/C++/0023687_ForceEngine.cpp @@ -0,0 +1,79 @@ +// 2004 © Janek Kozicki +// 2009 © Václav Šmilauer + + +#include"ForceEngine.hpp" +#include +#include +#include +#include + +#include +#include + +YADE_PLUGIN((ForceEngine)(InterpolatingDirectedForceEngine)(RadialForceEngine)(DragEngine)(LinearDragEngine)); + +void ForceEngine::action(){ + FOREACH(Body::id_t id, ids){ + if (!(scene->bodies->exists(id))) continue; + scene->forces.addForce(id,force); + } +} + +void InterpolatingDirectedForceEngine::action(){ + Real virtTime=wrap ? Shop::periodicWrap(scene->time,*times.begin(),*times.rbegin()) : scene->time; + direction.normalize(); + force=linearInterpolate(virtTime,times,magnitudes,_pos)*direction; + ForceEngine::action(); +} + +void RadialForceEngine::postLoad(RadialForceEngine&){ axisDir.normalize(); } + +void RadialForceEngine::action(){ + FOREACH(Body::id_t id, ids){ + if (!(scene->bodies->exists(id))) continue; + const Vector3r& pos=Body::byId(id,scene)->state->pos; + Vector3r radial=(pos - (axisPt+axisDir * /* t */ ((pos-axisPt).dot(axisDir)))).normalized(); + if(radial.squaredNorm()==0) continue; + scene->forces.addForce(id,fNorm*radial); + } +} + +void DragEngine::action(){ + FOREACH(Body::id_t id, ids){ + Body* b=Body::byId(id,scene).get(); + if (!b) continue; + if (!(scene->bodies->exists(id))) continue; + const Sphere* sphere = dynamic_cast(b->shape.get()); + if (sphere){ + Real A = sphere->radius*sphere->radius*Mathr::PI; //Crossection of the sphere + Vector3r velSphTemp = b->state->vel; + Vector3r dragForce = Vector3r::Zero(); + + if (velSphTemp != Vector3r::Zero()) { + dragForce = -0.5*Rho*A*Cd*velSphTemp.squaredNorm()*velSphTemp.normalized(); + } + scene->forces.addForce(id,dragForce); + } + } +} + +void LinearDragEngine::action(){ + FOREACH(Body::id_t id, ids){ + Body* b=Body::byId(id,scene).get(); + if (!b) continue; + if (!(scene->bodies->exists(id))) continue; + const Sphere* sphere = dynamic_cast(b->shape.get()); + if (sphere){ + Vector3r velSphTemp = b->state->vel; + Vector3r dragForce = Vector3r::Zero(); + + Real b = 6*Mathr::PI*nu*sphere->radius; + + if (velSphTemp != Vector3r::Zero()) { + dragForce = -b*velSphTemp; + } + scene->forces.addForce(id,dragForce); + } + } +} diff --git a/pool/shard001/C++/0023688_Scramble.cc b/pool/shard001/C++/0023688_Scramble.cc new file mode 100644 index 0000000000000000000000000000000000000000..4aa56f66465fbaad0e2948ea41e825e13fb61411 --- /dev/null +++ b/pool/shard001/C++/0023688_Scramble.cc @@ -0,0 +1,31 @@ +/* ======================================== + * Points : + * Total : 300 + * Status : + ==========================================*/ + +#include +using namespace std; + +#define FOR(I,A,B) for(int I = (A); I < (B); ++I) +#define REP(I,N) FOR(I,0,N) +#define ALL(A) (A).begin(), (A).end() +#define MSG(a) cout << #a << " == " << a << endl; + + +class Scramble { +public: + string scrambleWord(string text) { + int n = text.size(); + string remove = text.substr(1,n-2); + sort(ALL(remove)); + string result = text; + int a = 1, b = n-2, pos; + REP(i,n-2) { + pos = (i % 2) ? b-- : a++; + result[pos] = remove[i]; + } + + return result; + } +}; diff --git a/pool/shard001/C++/0023692_HitTestLocation.cpp b/pool/shard001/C++/0023692_HitTestLocation.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ca2afd44518ad1dd508558759701bc8e4b3639f0 --- /dev/null +++ b/pool/shard001/C++/0023692_HitTestLocation.cpp @@ -0,0 +1,172 @@ +/* + * Copyright (C) 2006, 2008, 2011 Apple Inc. All rights reserved. + * Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies) + * + * 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 "sky/engine/core/rendering/HitTestLocation.h" + +namespace blink { + +HitTestLocation::HitTestLocation() + : m_isRectBased(false) + , m_isRectilinear(true) +{ +} + +HitTestLocation::HitTestLocation(const LayoutPoint& point) + : m_point(point) + , m_boundingBox(rectForPoint(point, 0, 0, 0, 0)) + , m_transformedPoint(point) + , m_transformedRect(m_boundingBox) + , m_isRectBased(false) + , m_isRectilinear(true) +{ +} + +HitTestLocation::HitTestLocation(const FloatPoint& point) + : m_point(flooredLayoutPoint(point)) + , m_boundingBox(rectForPoint(m_point, 0, 0, 0, 0)) + , m_transformedPoint(point) + , m_transformedRect(m_boundingBox) + , m_isRectBased(false) + , m_isRectilinear(true) +{ +} + +HitTestLocation::HitTestLocation(const FloatPoint& point, const FloatQuad& quad) + : m_transformedPoint(point) + , m_transformedRect(quad) + , m_isRectBased(true) +{ + m_point = flooredLayoutPoint(point); + m_boundingBox = enclosingIntRect(quad.boundingBox()); + m_isRectilinear = quad.isRectilinear(); +} + +HitTestLocation::HitTestLocation(const LayoutPoint& centerPoint, unsigned topPadding, unsigned rightPadding, unsigned bottomPadding, unsigned leftPadding) + : m_point(centerPoint) + , m_boundingBox(rectForPoint(centerPoint, topPadding, rightPadding, bottomPadding, leftPadding)) + , m_transformedPoint(centerPoint) + , m_isRectBased(topPadding || rightPadding || bottomPadding || leftPadding) + , m_isRectilinear(true) +{ + m_transformedRect = FloatQuad(m_boundingBox); +} + +HitTestLocation::HitTestLocation(const HitTestLocation& other, const LayoutSize& offset) + : m_point(other.m_point) + , m_boundingBox(other.m_boundingBox) + , m_transformedPoint(other.m_transformedPoint) + , m_transformedRect(other.m_transformedRect) + , m_isRectBased(other.m_isRectBased) + , m_isRectilinear(other.m_isRectilinear) +{ + move(offset); +} + +HitTestLocation::HitTestLocation(const HitTestLocation& other) + : m_point(other.m_point) + , m_boundingBox(other.m_boundingBox) + , m_transformedPoint(other.m_transformedPoint) + , m_transformedRect(other.m_transformedRect) + , m_isRectBased(other.m_isRectBased) + , m_isRectilinear(other.m_isRectilinear) +{ +} + +HitTestLocation::~HitTestLocation() +{ +} + +HitTestLocation& HitTestLocation::operator=(const HitTestLocation& other) +{ + m_point = other.m_point; + m_boundingBox = other.m_boundingBox; + m_transformedPoint = other.m_transformedPoint; + m_transformedRect = other.m_transformedRect; + m_isRectBased = other.m_isRectBased; + m_isRectilinear = other.m_isRectilinear; + + return *this; +} + +void HitTestLocation::move(const LayoutSize& offset) +{ + m_point.move(offset); + m_transformedPoint.move(offset); + m_transformedRect.move(offset); + m_boundingBox = enclosingIntRect(m_transformedRect.boundingBox()); +} + +template +bool HitTestLocation::intersectsRect(const RectType& rect) const +{ + // FIXME: When the hit test is not rect based we should use rect.contains(m_point). + // That does change some corner case tests though. + + // First check if rect even intersects our bounding box. + if (!rect.intersects(m_boundingBox)) + return false; + + // If the transformed rect is rectilinear the bounding box intersection was accurate. + if (m_isRectilinear) + return true; + + // If rect fully contains our bounding box, we are also sure of an intersection. + if (rect.contains(m_boundingBox)) + return true; + + // Otherwise we need to do a slower quad based intersection test. + return m_transformedRect.intersectsRect(rect); +} + +bool HitTestLocation::intersects(const LayoutRect& rect) const +{ + return intersectsRect(rect); +} + +bool HitTestLocation::intersects(const FloatRect& rect) const +{ + return intersectsRect(rect); +} + +bool HitTestLocation::intersects(const RoundedRect& rect) const +{ + return rect.intersectsQuad(m_transformedRect); +} + +bool HitTestLocation::containsPoint(const FloatPoint& point) const +{ + return m_transformedRect.containsPoint(point); +} + +IntRect HitTestLocation::rectForPoint(const LayoutPoint& point, unsigned topPadding, unsigned rightPadding, unsigned bottomPadding, unsigned leftPadding) +{ + IntPoint actualPoint(flooredIntPoint(point)); + actualPoint -= IntSize(leftPadding, topPadding); + + IntSize actualPadding(leftPadding + rightPadding, topPadding + bottomPadding); + // As IntRect is left inclusive and right exclusive (seeing IntRect::contains(x, y)), adding "1". + // FIXME: Remove this once non-rect based hit-detection stops using IntRect:intersects. + actualPadding += IntSize(1, 1); + + return IntRect(actualPoint, actualPadding); +} + +} // namespace blink diff --git a/pool/shard001/C++/0023693_kmeans_iter_mex.cc b/pool/shard001/C++/0023693_kmeans_iter_mex.cc new file mode 100644 index 0000000000000000000000000000000000000000..c261282729a31b444e2a79b2cf92265fd139fad1 --- /dev/null +++ b/pool/shard001/C++/0023693_kmeans_iter_mex.cc @@ -0,0 +1,83 @@ +#include +#include "mex.h" +#include + +// One half iteration of k-means in which new centers are computed +// according to a center assignment vector. + +// Inputs -------------------- + +#define mxX prhs[0] // A d*n matrix of data points (n d-dim points) +#define mxI prhs[1] // A n*1 vector encoding the + // assignment of data points to + // cluster centers. Each value should + // be between 1 and h. +#define mxh prhs[2] // Number of cluster centers (h). + +// Outputs -------------------- + +#define mxC plhs[0] // A d*h matrix of centers (h d-dim points) + +void myAssert(int a, const char *b) { + if (!a) + mexErrMsgTxt(b); +} + +void mexFunction(int nlhs, mxArray *plhs[], + int nrhs, const mxArray *prhs[]) +{ + int n, d, h; + const float * X; + const int * I; + float * Cp, * nCp; + + if (nrhs != 3) + mexErrMsgTxt("Thee input arguments expected."); + if (nlhs != 1) + mexErrMsgTxt("One output arguments expected."); + + if (!mxIsSingle(mxX) || + mxIsComplex(mxX) || + mxGetNumberOfDimensions(mxX) != 2) + mexErrMsgTxt("First input argument should be a single " + "precision 2D matrix."); + d = mxGetM(mxX); + n = mxGetN(mxX); + + if (!mxIsInt32(mxI) || + mxIsComplex(mxI) || + mxGetM(mxI) != (unsigned int)n) + mexErrMsgTxt("Second input argument must be an int " + "matrix compatible with first input."); + myAssert(mxGetN(mxI) == 1, "Second input argument must be a column vector"); + + X = (float*) mxGetPr(mxX); + I = (int*) mxGetPr(mxI); + h = (int)(*(double*)mxGetPr(mxh)); + + mxC = mxCreateNumericMatrix (d, h, mxSINGLE_CLASS, mxREAL); + Cp = (float*) mxGetPr(mxC); + memset(Cp, 0, d * h * sizeof(float)); + + // nCp represents a h-dim count vector counting number of data + // points associated with any one of the centers. + nCp = (float*) calloc(h, sizeof(float)); // calloc initializes to zero + const float * px = X; + for (int i = 0; i < n; i++, px += d) { + int c = I[i] - 1; // zero-based. + myAssert(0 <= c && c < h, "Each value in the second input argument should" + " be between 1 and h."); + nCp[c]++; + float * pcxp = Cp + c * d; + for (int k = 0; k < d; k++) + pcxp[k] += px[k]; + } + + float * pcxp = Cp; + for (int j = 0; j < h; j++, pcxp += d) { + if (nCp[j]) + for (int k = 0; k < d; k++) + pcxp[k] /= nCp[j]; + } + free(nCp); +} diff --git a/pool/shard001/C++/0023698_beatcontroller.cpp b/pool/shard001/C++/0023698_beatcontroller.cpp new file mode 100644 index 0000000000000000000000000000000000000000..77c4fc480131bbcce05c8b5b4ceab355e5b74528 --- /dev/null +++ b/pool/shard001/C++/0023698_beatcontroller.cpp @@ -0,0 +1,95 @@ +/* + This file is part of libbeat - a lightweight beat detection library + Copyright (c) 2011 by Maximilian Güntner + + 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 "beatcontroller.h" + +namespace libbeat +{ + +BeatController::BeatController(QObject *parent, uint16_t recordSize, uint32_t sampleRate, uint16_t m_bandCount) : QObject(parent) +{ + m_Buffer = new SoundBuffer(recordSize); + m_Analyser = new BeatAnalyser(m_bandCount,sampleRate,recordSize); +#ifdef USE_ALSA + dynamic_cast(m_Recorder); + m_Recorder = new AlsaRecorder(sampleRate,2,m_Buffer,recordSize); +#endif +#ifdef USE_PULSE + dynamic_cast(m_Recorder); + m_Recorder = new PulseRecorder(sampleRate,2,m_Buffer,recordSize); +#endif + m_FFT = new FFT(recordSize); + m_FFT->setSoundBuffer(m_Buffer); + m_Analyser->setFFT(m_FFT); + m_enabled=false; +} +BeatController::~BeatController() +{ + delete m_FFT; + delete m_Recorder; + delete m_Buffer; + delete m_Analyser; +} +void BeatController::start() +{ + if(!m_enabled) + { + m_Recorder->start(); + m_enabled=true; + //Connect SoundRecorder::newDataIsReady to processNewData() + connect(m_Recorder,SIGNAL(newDataIsReady()),this, SLOT(processNewData())); + } +} + +void BeatController::stop() +{ + if(m_enabled) + { + m_Recorder->stop(); + m_enabled=false; + } +} +bool BeatController::getEnabled() +{ + return m_enabled; +} + +void BeatController::processNewData() +{ + if(m_enabled) + { + m_FFT->processData(); + m_Analyser->processData(); + emit processingDone(); + if(m_Analyser->getDrumBeat()) + emit beatDrum(); + if(m_Analyser->getSnareBeat()) + emit beatSnare(); + //Check for a beat for every frequency in our list + QSet myBeats; + QSetIterator i(m_customBeats); + while(i.hasNext()) + { + if(m_Analyser->getBeatFrequency(i.peekNext())) + myBeats.insert(i.peekNext()); + i.next(); + } + if(!myBeats.empty()) + emit beatCustom(myBeats); + } +} +} //namespace libbeat diff --git a/pool/shard001/C++/0023701_surface_hittest_test_helpers.cc b/pool/shard001/C++/0023701_surface_hittest_test_helpers.cc new file mode 100644 index 0000000000000000000000000000000000000000..4183242a0d8ad98f79b6f2cc383122ab7a3f22b1 --- /dev/null +++ b/pool/shard001/C++/0023701_surface_hittest_test_helpers.cc @@ -0,0 +1,145 @@ +// 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 "cc/test/surface_hittest_test_helpers.h" + +#include "cc/output/compositor_frame.h" +#include "cc/output/delegated_frame_data.h" +#include "cc/quads/render_pass_draw_quad.h" +#include "cc/quads/shared_quad_state.h" +#include "cc/quads/solid_color_draw_quad.h" +#include "cc/quads/surface_draw_quad.h" + +namespace cc { +namespace test { + +void CreateSharedQuadState(RenderPass* pass, + const gfx::Transform& transform, + const gfx::Rect& root_rect) { + SharedQuadState* child_shared_state = pass->CreateAndAppendSharedQuadState(); + child_shared_state->SetAll(transform, root_rect.size(), root_rect, root_rect, + false, 1.0f, SkXfermode::kSrcOver_Mode, 0); +} + +void CreateSolidColorDrawQuad(RenderPass* pass, + const gfx::Transform& transform, + const gfx::Rect& root_rect, + const gfx::Rect& quad_rect) { + CreateSharedQuadState(pass, transform, root_rect); + SolidColorDrawQuad* color_quad = + pass->CreateAndAppendDrawQuad(); + color_quad->SetNew(pass->shared_quad_state_list.back(), quad_rect, quad_rect, + SK_ColorYELLOW, false); +} + +void CreateRenderPassDrawQuad(RenderPass* pass, + const gfx::Transform& transform, + const gfx::Rect& root_rect, + const gfx::Rect& quad_rect, + const RenderPassId& render_pass_id) { + CreateSharedQuadState(pass, transform, root_rect); + RenderPassDrawQuad* render_pass_quad = + pass->CreateAndAppendDrawQuad(); + render_pass_quad->SetNew(pass->shared_quad_state_list.back(), quad_rect, + quad_rect, render_pass_id, ResourceId(), + gfx::Vector2dF(), gfx::Size(), FilterOperations(), + gfx::Vector2dF(), FilterOperations()); +} + +void CreateSurfaceDrawQuad(RenderPass* pass, + const gfx::Transform& transform, + const gfx::Rect& root_rect, + const gfx::Rect& quad_rect, + SurfaceId surface_id) { + CreateSharedQuadState(pass, transform, root_rect); + SurfaceDrawQuad* surface_quad = + pass->CreateAndAppendDrawQuad(); + surface_quad->SetNew(pass->shared_quad_state_list.back(), quad_rect, + quad_rect, surface_id); +} + +void CreateRenderPass(const RenderPassId& render_pass_id, + const gfx::Rect& rect, + const gfx::Transform& transform_to_root_target, + RenderPassList* render_pass_list) { + std::unique_ptr render_pass = RenderPass::Create(); + render_pass->SetNew(render_pass_id, rect, rect, transform_to_root_target); + render_pass_list->push_back(std::move(render_pass)); +} + +std::unique_ptr CreateCompositorFrameWithRenderPassList( + RenderPassList* render_pass_list) { + std::unique_ptr root_delegated_frame_data( + new DelegatedFrameData); + root_delegated_frame_data->render_pass_list.swap(*render_pass_list); + std::unique_ptr root_frame(new CompositorFrame); + root_frame->delegated_frame_data = std::move(root_delegated_frame_data); + return root_frame; +} + +std::unique_ptr CreateCompositorFrame( + const gfx::Rect& root_rect, + RenderPass** render_pass) { + RenderPassList render_pass_list; + RenderPassId root_id(1, 1); + CreateRenderPass(root_id, root_rect, gfx::Transform(), &render_pass_list); + + std::unique_ptr root_frame = + CreateCompositorFrameWithRenderPassList(&render_pass_list); + + *render_pass = + root_frame->delegated_frame_data->render_pass_list.back().get(); + return root_frame; +} + +TestSurfaceHittestDelegate::TestSurfaceHittestDelegate() + : reject_target_overrides_(0), accept_target_overrides_(0) {} + +TestSurfaceHittestDelegate::~TestSurfaceHittestDelegate() {} + +void TestSurfaceHittestDelegate::AddInsetsForRejectSurface( + const SurfaceId& surface_id, + const gfx::Insets& inset) { + insets_for_reject_.insert(std::make_pair(surface_id, inset)); +} + +void TestSurfaceHittestDelegate::AddInsetsForAcceptSurface( + const SurfaceId& surface_id, + const gfx::Insets& inset) { + insets_for_accept_.insert(std::make_pair(surface_id, inset)); +} + +bool TestSurfaceHittestDelegate::RejectHitTarget( + const SurfaceDrawQuad* surface_quad, + const gfx::Point& point_in_quad_space) { + if (!insets_for_reject_.count(surface_quad->surface_id)) + return false; + gfx::Rect bounds(surface_quad->rect); + bounds.Inset(insets_for_reject_[surface_quad->surface_id]); + // If the point provided falls outside the inset, then we skip this surface. + if (!bounds.Contains(point_in_quad_space)) { + if (surface_quad->rect.Contains(point_in_quad_space)) + ++reject_target_overrides_; + return true; + } + return false; +} + +bool TestSurfaceHittestDelegate::AcceptHitTarget( + const SurfaceDrawQuad* surface_quad, + const gfx::Point& point_in_quad_space) { + if (!insets_for_accept_.count(surface_quad->surface_id)) + return false; + gfx::Rect bounds(surface_quad->rect); + bounds.Inset(insets_for_accept_[surface_quad->surface_id]); + // If the point provided falls outside the inset, then we accept this surface. + if (!bounds.Contains(point_in_quad_space)) { + ++accept_target_overrides_; + return true; + } + return false; +} + +} // namespace test +} // namespace cc diff --git a/pool/shard001/C++/0023702_summary-util.cc b/pool/shard001/C++/0023702_summary-util.cc new file mode 100644 index 0000000000000000000000000000000000000000..bf6d44912faa347c36d707c4c084491f61f99d64 --- /dev/null +++ b/pool/shard001/C++/0023702_summary-util.cc @@ -0,0 +1,129 @@ +// Copyright 2012 Cloudera 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 "util/summary-util.h" + +#include +#include + +#include "common/logging.h" +#include "util/debug-util.h" +#include "util/table-printer.h" + +using namespace boost; +using namespace impala; +using namespace std; + +// Helper function for PrintExecSummary() that walks the exec summary recursively. +// Output for this node is appended to *result. Each value in *result should contain +// the statistics for a single exec summary node. +// node_idx is an in/out parameter. It is called with the idx (into exec_summary_.nodes) +// for the current node and on return, will contain the id of the next node. +void PrintExecSummary(const TExecSummary& exec_summary, int indent_level, + int new_indent_level, int* node_idx, + vector >* result) { + DCHECK_LT(*node_idx, exec_summary.nodes.size()); + const TPlanNodeExecSummary& node = exec_summary.nodes[*node_idx]; + const TExecStats& est_stats = node.estimated_stats; + + TExecStats agg_stats; + TExecStats max_stats; + +#define COMPUTE_MAX_SUM_STATS(NAME)\ + agg_stats.NAME += node.exec_stats[i].NAME;\ + max_stats.NAME = max(max_stats.NAME, node.exec_stats[i].NAME) + + // Compute avg and max of each used stat (cpu_time_ns is unused in the summary output). + for (int i = 0; i < node.exec_stats.size(); ++i) { + COMPUTE_MAX_SUM_STATS(latency_ns); + COMPUTE_MAX_SUM_STATS(cardinality); + COMPUTE_MAX_SUM_STATS(memory_used); + } +#undef COMPUTE_MAX_SUM_STATS + + int64_t avg_time = node.exec_stats.size() == 0 ? 0 : + agg_stats.latency_ns / node.exec_stats.size(); + + // Print the level to indicate nesting with "|--" + stringstream label_ss; + if (indent_level != 0) { + label_ss << "|"; + for (int i = 0; i < indent_level - 1; ++i) { + label_ss << " |"; + } + label_ss << (new_indent_level ? "--" : " "); + } + + label_ss << node.label; + + vector row; + row.push_back(label_ss.str()); + row.push_back(lexical_cast(node.exec_stats.size())); // Num instances + row.push_back(PrettyPrinter::Print(avg_time, TCounterType::TIME_NS)); + row.push_back(PrettyPrinter::Print(max_stats.latency_ns, TCounterType::TIME_NS)); + row.push_back(PrettyPrinter::Print( + node.is_broadcast ? max_stats.cardinality : agg_stats.cardinality, + TCounterType::UNIT)); + row.push_back(PrettyPrinter::Print(est_stats.cardinality, TCounterType::UNIT)); + row.push_back(PrettyPrinter::Print(max_stats.memory_used, TCounterType::BYTES)); + row.push_back(PrettyPrinter::Print(est_stats.memory_used, TCounterType::BYTES)); + row.push_back(node.label_detail); + result->push_back(row); + + map::const_iterator child_fragment_idx_it = + exec_summary.exch_to_sender_map.find(*node_idx); + if (child_fragment_idx_it != exec_summary.exch_to_sender_map.end()) { + DCHECK_EQ(node.num_children, 0); + int child_fragment_id = child_fragment_idx_it->second; + PrintExecSummary(exec_summary, indent_level, false, &child_fragment_id, result); + } + ++*node_idx; + if (node.num_children == 0) return; + + // Print the non-left children to the stream first. + vector > child0_result; + PrintExecSummary(exec_summary, indent_level, false, node_idx, &child0_result); + + for (int i = 1; i < node.num_children; ++i) { + PrintExecSummary(exec_summary, indent_level + 1, true, node_idx, result); + } + for (int i = 0; i < child0_result.size(); ++i) { + result->push_back(child0_result[i]); + } +} + +string impala::PrintExecSummary(const TExecSummary& exec_summary) { + // Bail if Coordinator::InitExecProfile() has not been called. + if (!exec_summary.__isset.nodes) return ""; + + TablePrinter printer; + printer.set_max_output_width(30); + printer.AddColumn("Operator", true); + printer.AddColumn("#Hosts", false); + printer.AddColumn("Avg Time", false); + printer.AddColumn("Max Time", false); + printer.AddColumn("#Rows", false); + printer.AddColumn("Est. #Rows", false); + printer.AddColumn("Peak Mem", false); + printer.AddColumn("Est. Peak Mem", false); + printer.AddColumn("Detail", true); + + vector > rows; + int node_idx = 0; + ::PrintExecSummary(exec_summary, 0, false, &node_idx, &rows); + for (int i = 0; i < rows.size(); ++i) { + printer.AddRow(rows[i]); + } + return printer.ToString("\n"); +} diff --git a/pool/shard001/C++/0023704_cpp_plugin_unittest.cc b/pool/shard001/C++/0023704_cpp_plugin_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..7233121428421ad29d3c32e3bf0bb41ccc982417 --- /dev/null +++ b/pool/shard001/C++/0023704_cpp_plugin_unittest.cc @@ -0,0 +1,120 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// http://code.google.com/p/protobuf/ +// +// 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. + +// +// TODO: Share code with the versions of this test in other languages? +// It seemed like parameterizing it would add more complexity than it is +// worth. + +#include +#include +#include +#include + +#include +#include +#include + +namespace google { +namespace protobuf { +namespace compiler { +namespace cpp { +namespace { + +class TestGenerator : public CodeGenerator { + public: + TestGenerator() {} + ~TestGenerator() {} + + virtual bool Generate(const FileDescriptor* file, + const string& parameter, + GeneratorContext* context, + string* error) const { + TryInsert("test.pb.h", "includes", context); + TryInsert("test.pb.h", "namespace_scope", context); + TryInsert("test.pb.h", "global_scope", context); + TryInsert("test.pb.h", "class_scope:foo.Bar", context); + TryInsert("test.pb.h", "class_scope:foo.Bar.Baz", context); + + TryInsert("test.pb.cc", "includes", context); + TryInsert("test.pb.cc", "namespace_scope", context); + TryInsert("test.pb.cc", "global_scope", context); + return true; + } + + void TryInsert(const string& filename, const string& insertion_point, + GeneratorContext* context) const { + scoped_ptr output( + context->OpenForInsert(filename, insertion_point)); + io::Printer printer(output.get(), '$'); + printer.Print("// inserted $name$\n", "name", insertion_point); + } +}; + +// This test verifies that all the expected insertion points exist. It does +// not verify that they are correctly-placed; that would require actually +// compiling the output which is a bit more than I care to do for this test. +TEST(CppPluginTest, PluginTest) { + File::WriteStringToFileOrDie( + "syntax = \"proto2\";\n" + "package foo;\n" + "message Bar {\n" + " message Baz {}\n" + "}\n", + TestTempDir() + "/test.proto"); + + google::protobuf::compiler::CommandLineInterface cli; + cli.SetInputsAreProtoPathRelative(true); + + CppGenerator cpp_generator; + TestGenerator test_generator; + cli.RegisterGenerator("--cpp_out", &cpp_generator, ""); + cli.RegisterGenerator("--test_out", &test_generator, ""); + + string proto_path = "-I" + TestTempDir(); + string cpp_out = "--cpp_out=" + TestTempDir(); + string test_out = "--test_out=" + TestTempDir(); + + const char* argv[] = { + "protoc", + proto_path.c_str(), + cpp_out.c_str(), + test_out.c_str(), + "test.proto" + }; + + EXPECT_EQ(0, cli.Run(5, argv)); +} + +} // namespace +} // namespace cpp +} // namespace compiler +} // namespace protobuf +} // namespace google diff --git a/pool/shard001/C++/0023715_CCBSequence.cpp b/pool/shard001/C++/0023715_CCBSequence.cpp new file mode 100644 index 0000000000000000000000000000000000000000..07e8d961891ded8110dc1f898ab6d407ca2ec079 --- /dev/null +++ b/pool/shard001/C++/0023715_CCBSequence.cpp @@ -0,0 +1,89 @@ +#include "CCBSequence.h" + +using namespace cocos2d; +using namespace std; + + +NS_CC_EXT_BEGIN + +CCBSequence::CCBSequence() +: _duration(0.0f) +, _name("") +, mSequenceId(0) +, mChainedSequenceId(0) +, mCallbackChannel(NULL) +, mSoundChannel(NULL) +{} + +CCBSequence::~CCBSequence() { + CC_SAFE_RELEASE(mCallbackChannel); + CC_SAFE_RELEASE(mSoundChannel); +} + +float CCBSequence::getDuration() +{ + return _duration; +} + +void CCBSequence::setDuration(float fDuration) +{ + _duration = fDuration; +} + +const char* CCBSequence::getName() +{ + return _name.c_str(); +} + +void CCBSequence::setName(const char *pName) +{ + _name = pName; +} + +int CCBSequence::getSequenceId() +{ + return mSequenceId; +} + +void CCBSequence::setSequenceId(int nSequenceId) +{ + mSequenceId = nSequenceId; +} + +CCBSequenceProperty* CCBSequence::getCallbackChannel() +{ + return mCallbackChannel; +} + +void CCBSequence::setCallbackChannel(CCBSequenceProperty* callbackChannel) +{ + CC_SAFE_RELEASE(mCallbackChannel); + mCallbackChannel = callbackChannel; + CC_SAFE_RETAIN(mCallbackChannel); +} + + +CCBSequenceProperty* CCBSequence::getSoundChannel() +{ + return mSoundChannel; +} + +void CCBSequence::setSoundChannel(CCBSequenceProperty* soundChannel) +{ + CC_SAFE_RELEASE(mSoundChannel); + mSoundChannel = soundChannel; + CC_SAFE_RETAIN(mSoundChannel); +} + + +int CCBSequence::getChainedSequenceId() +{ + return mChainedSequenceId; +} + +void CCBSequence::setChainedSequenceId(int nChainedSequenceId) +{ + mChainedSequenceId = nChainedSequenceId; +} + +NS_CC_EXT_END \ No newline at end of file diff --git a/pool/shard001/C++/0023720_child_process_service_impl.cc b/pool/shard001/C++/0023720_child_process_service_impl.cc new file mode 100644 index 0000000000000000000000000000000000000000..083c3209a62c0107afde08c80aaefcb7c9e9889e --- /dev/null +++ b/pool/shard001/C++/0023720_child_process_service_impl.cc @@ -0,0 +1,201 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "content/app/android/child_process_service_impl.h" + +#include +#include + +#include "base/android/jni_array.h" +#include "base/android/library_loader/library_loader_hooks.h" +#include "base/android/memory_pressure_listener_android.h" +#include "base/logging.h" +#include "base/macros.h" +#include "base/posix/global_descriptors.h" +#include "base/unguessable_token.h" +#include "content/child/child_thread_impl.h" +#include "content/public/common/content_descriptors.h" +#include "gpu/ipc/common/android/scoped_surface_request_conduit.h" +#include "gpu/ipc/common/android/surface_texture_manager.h" +#include "gpu/ipc/common/android/surface_texture_peer.h" +#include "gpu/ipc/common/gpu_surface_lookup.h" +#include "ipc/ipc_descriptors.h" +#include "jni/ChildProcessServiceImpl_jni.h" +#include "ui/gl/android/scoped_java_surface.h" + +using base::android::AttachCurrentThread; +using base::android::CheckException; +using base::android::JavaIntArrayToIntVector; +using base::android::JavaParamRef; + +namespace content { + +namespace { + +// TODO(sievers): Use two different implementations of this depending on if +// we're in a renderer or gpu process. +class SurfaceTextureManagerImpl : public gpu::SurfaceTextureManager, + public gpu::SurfaceTexturePeer, + public gpu::ScopedSurfaceRequestConduit, + public gpu::GpuSurfaceLookup { + public: + // |service impl| is the instance of + // org.chromium.content.app.ChildProcessServiceImpl. + explicit SurfaceTextureManagerImpl( + const base::android::JavaRef& service_impl) + : service_impl_(service_impl) { + SurfaceTexturePeer::InitInstance(this); + gpu::GpuSurfaceLookup::InitInstance(this); + gpu::ScopedSurfaceRequestConduit::SetInstance(this); + } + ~SurfaceTextureManagerImpl() override { + SurfaceTexturePeer::InitInstance(NULL); + gpu::GpuSurfaceLookup::InitInstance(NULL); + gpu::ScopedSurfaceRequestConduit::SetInstance(nullptr); + } + + // Overridden from SurfaceTextureManager: + void RegisterSurfaceTexture(int surface_texture_id, + int client_id, + gl::SurfaceTexture* surface_texture) override { + JNIEnv* env = base::android::AttachCurrentThread(); + Java_ChildProcessServiceImpl_createSurfaceTextureSurface( + env, service_impl_, surface_texture_id, client_id, + surface_texture->j_surface_texture()); + } + void UnregisterSurfaceTexture(int surface_texture_id, + int client_id) override { + JNIEnv* env = base::android::AttachCurrentThread(); + Java_ChildProcessServiceImpl_destroySurfaceTextureSurface( + env, service_impl_, surface_texture_id, client_id); + } + gfx::AcceleratedWidget AcquireNativeWidgetForSurfaceTexture( + int surface_texture_id) override { + JNIEnv* env = base::android::AttachCurrentThread(); + gl::ScopedJavaSurface surface( + Java_ChildProcessServiceImpl_getSurfaceTextureSurface( + env, service_impl_, surface_texture_id)); + + if (surface.j_surface().is_null()) + return NULL; + + // Note: This ensures that any local references used by + // ANativeWindow_fromSurface are released immediately. This is needed as a + // workaround for https://code.google.com/p/android/issues/detail?id=68174 + base::android::ScopedJavaLocalFrame scoped_local_reference_frame(env); + ANativeWindow* native_window = + ANativeWindow_fromSurface(env, surface.j_surface().obj()); + + return native_window; + } + + // Overridden from SurfaceTexturePeer: + void EstablishSurfaceTexturePeer( + base::ProcessHandle pid, + scoped_refptr surface_texture, + int primary_id, + int secondary_id) override { + JNIEnv* env = base::android::AttachCurrentThread(); + content::Java_ChildProcessServiceImpl_establishSurfaceTexturePeer( + env, service_impl_, pid, surface_texture->j_surface_texture(), + primary_id, secondary_id); + } + + // Overriden from ScopedSurfaceRequestConduit: + void ForwardSurfaceTextureForSurfaceRequest( + const base::UnguessableToken& request_token, + const gl::SurfaceTexture* surface_texture) override { + JNIEnv* env = base::android::AttachCurrentThread(); + + content:: + Java_ChildProcessServiceImpl_forwardSurfaceTextureForSurfaceRequest( + env, service_impl_, request_token.GetHighForSerialization(), + request_token.GetLowForSerialization(), + surface_texture->j_surface_texture()); + } + + // Overridden from GpuSurfaceLookup: + gfx::AcceleratedWidget AcquireNativeWidget(int surface_id) override { + JNIEnv* env = base::android::AttachCurrentThread(); + gl::ScopedJavaSurface surface( + content::Java_ChildProcessServiceImpl_getViewSurface(env, service_impl_, + surface_id)); + + if (surface.j_surface().is_null()) + return NULL; + + // Note: This ensures that any local references used by + // ANativeWindow_fromSurface are released immediately. This is needed as a + // workaround for https://code.google.com/p/android/issues/detail?id=68174 + base::android::ScopedJavaLocalFrame scoped_local_reference_frame(env); + ANativeWindow* native_window = + ANativeWindow_fromSurface(env, surface.j_surface().obj()); + + return native_window; + } + + // Overridden from GpuSurfaceLookup: + gl::ScopedJavaSurface AcquireJavaSurface(int surface_id) override { + JNIEnv* env = base::android::AttachCurrentThread(); + return gl::ScopedJavaSurface( + content::Java_ChildProcessServiceImpl_getViewSurface(env, service_impl_, + surface_id)); + } + + private: + // The instance of org.chromium.content.app.ChildProcessServiceImpl. + base::android::ScopedJavaGlobalRef service_impl_; + + DISALLOW_COPY_AND_ASSIGN(SurfaceTextureManagerImpl); +}; + +// Chrome actually uses the renderer code path for all of its child +// processes such as renderers, plugins, etc. +void InternalInitChildProcessImpl(JNIEnv* env, + const JavaParamRef& service_impl, + jint cpu_count, + jlong cpu_features) { + // Set the CPU properties. + android_setCpu(cpu_count, cpu_features); + gpu::SurfaceTextureManager::SetInstance( + new SurfaceTextureManagerImpl(service_impl)); + + base::android::MemoryPressureListenerAndroid::RegisterSystemCallback(env); +} + +} // namespace + +void RegisterGlobalFileDescriptor(JNIEnv* env, + const JavaParamRef& clazz, + jint id, + jint fd, + jlong offset, + jlong size) { + base::MemoryMappedFile::Region region = {offset, size}; + base::GlobalDescriptors::GetInstance()->Set(id, fd, region); +} + +void InitChildProcessImpl(JNIEnv* env, + const JavaParamRef& clazz, + const JavaParamRef& service_impl, + jint cpu_count, + jlong cpu_features) { + InternalInitChildProcessImpl(env, service_impl, cpu_count, cpu_features); +} + +void ExitChildProcess(JNIEnv* env, const JavaParamRef& clazz) { + VLOG(0) << "ChildProcessServiceImpl: Exiting child process."; + base::android::LibraryLoaderExitHook(); + _exit(0); +} + +bool RegisterChildProcessServiceImpl(JNIEnv* env) { + return RegisterNativesImpl(env); +} + +void ShutdownMainThread(JNIEnv* env, const JavaParamRef& obj) { + ChildThreadImpl::ShutdownThread(); +} + +} // namespace content diff --git a/pool/shard001/C++/0023723_main.cpp b/pool/shard001/C++/0023723_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c09d3ae8922f306620114513eaa9ad27abab66d6 --- /dev/null +++ b/pool/shard001/C++/0023723_main.cpp @@ -0,0 +1,53 @@ +/* + * Copyright (C) 2014 MediaSift 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 + +/* form_data example + * + * This example demonstrates how you might specify and validate a form endpoint. + */ +int main(int, char const**) +{ + served::multiplexer mux; + mux.handle("/form_post") + .post([&](served::response & res, const served::request & req) { + // check headers for the correct content type + if ( req.header("content-type") != "application/x-www-form-urlencoded" ) + { + // return 400 bad request if the content type is wrong for this example. + served::response::stock_reply(400, res); + } + else + { + res << "Body data: " << req.body(); + } + }); + + std::cout << "Try this example with:" << std::endl; + std::cout << " curl http://localhost:8123/form_post -d \"hello world!\"" << std::endl; + + served::net::server server("0.0.0.0", "8123", mux); + server.run(10); + + return (EXIT_SUCCESS); +} diff --git a/pool/shard001/C++/0023730_network_data_local.cpp b/pool/shard001/C++/0023730_network_data_local.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4fc6ca9061f9f36dd6624ae3f517b63ede53c205 --- /dev/null +++ b/pool/shard001/C++/0023730_network_data_local.cpp @@ -0,0 +1,247 @@ +/* + * Copyright (c) 2016, The OpenThread Authors. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holder nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * @file + * This file implements the local Thread Network Data. + */ + +#include +#include +#include +#include +#include +#include + +namespace Thread { +namespace NetworkData { + +Local::Local(ThreadNetif &aThreadNetif): + NetworkData(aThreadNetif, true), + mOldRloc(Mac::kShortAddrInvalid) +{ +} + +ThreadError Local::AddOnMeshPrefix(const uint8_t *aPrefix, uint8_t aPrefixLength, int8_t aPrf, + uint8_t aFlags, bool aStable) +{ + PrefixTlv *prefixTlv; + BorderRouterTlv *brTlv; + + RemoveOnMeshPrefix(aPrefix, aPrefixLength); + + prefixTlv = reinterpret_cast(mTlvs + mLength); + Insert(reinterpret_cast(prefixTlv), + sizeof(PrefixTlv) + BitVectorBytes(aPrefixLength) + sizeof(BorderRouterTlv) + sizeof(BorderRouterEntry)); + prefixTlv->Init(0, aPrefixLength, aPrefix); + prefixTlv->SetSubTlvsLength(sizeof(BorderRouterTlv) + sizeof(BorderRouterEntry)); + + brTlv = static_cast(prefixTlv->GetSubTlvs()); + brTlv->Init(); + brTlv->SetLength(brTlv->GetLength() + sizeof(BorderRouterEntry)); + brTlv->GetEntry(0)->Init(); + brTlv->GetEntry(0)->SetPreference(aPrf); + brTlv->GetEntry(0)->SetFlags(aFlags); + + if (aStable) + { + prefixTlv->SetStable(); + brTlv->SetStable(); + } + + ClearResubmitDelayTimer(); + + otDumpDebgNetData(GetInstance(), "add prefix done", mTlvs, mLength); + return kThreadError_None; +} + +ThreadError Local::RemoveOnMeshPrefix(const uint8_t *aPrefix, uint8_t aPrefixLength) +{ + ThreadError error = kThreadError_None; + PrefixTlv *tlv; + + VerifyOrExit((tlv = FindPrefix(aPrefix, aPrefixLength)) != NULL, error = kThreadError_Error); + VerifyOrExit(FindBorderRouter(*tlv) != NULL, error = kThreadError_Error); + Remove(reinterpret_cast(tlv), sizeof(NetworkDataTlv) + tlv->GetLength()); + ClearResubmitDelayTimer(); + +exit: + otDumpDebgNetData(GetInstance(), "remove done", mTlvs, mLength); + return error; +} + +ThreadError Local::AddHasRoutePrefix(const uint8_t *aPrefix, uint8_t aPrefixLength, int8_t aPrf, bool aStable) +{ + PrefixTlv *prefixTlv; + HasRouteTlv *hasRouteTlv; + + RemoveHasRoutePrefix(aPrefix, aPrefixLength); + + prefixTlv = reinterpret_cast(mTlvs + mLength); + Insert(reinterpret_cast(prefixTlv), + sizeof(PrefixTlv) + BitVectorBytes(aPrefixLength) + sizeof(HasRouteTlv) + sizeof(HasRouteEntry)); + prefixTlv->Init(0, aPrefixLength, aPrefix); + prefixTlv->SetSubTlvsLength(sizeof(HasRouteTlv) + sizeof(HasRouteEntry)); + + hasRouteTlv = static_cast(prefixTlv->GetSubTlvs()); + hasRouteTlv->Init(); + hasRouteTlv->SetLength(hasRouteTlv->GetLength() + sizeof(HasRouteEntry)); + hasRouteTlv->GetEntry(0)->Init(); + hasRouteTlv->GetEntry(0)->SetPreference(aPrf); + + if (aStable) + { + prefixTlv->SetStable(); + hasRouteTlv->SetStable(); + } + + ClearResubmitDelayTimer(); + + otDumpDebgNetData(GetInstance(), "add route done", mTlvs, mLength); + return kThreadError_None; +} + +ThreadError Local::RemoveHasRoutePrefix(const uint8_t *aPrefix, uint8_t aPrefixLength) +{ + ThreadError error = kThreadError_None; + PrefixTlv *tlv; + + VerifyOrExit((tlv = FindPrefix(aPrefix, aPrefixLength)) != NULL, error = kThreadError_Error); + VerifyOrExit(FindHasRoute(*tlv) != NULL, error = kThreadError_Error); + Remove(reinterpret_cast(tlv), sizeof(NetworkDataTlv) + tlv->GetLength()); + ClearResubmitDelayTimer(); + +exit: + otDumpDebgNetData(GetInstance(), "remove done", mTlvs, mLength); + return error; +} + +ThreadError Local::UpdateRloc(void) +{ + for (NetworkDataTlv *cur = reinterpret_cast(mTlvs); + cur < reinterpret_cast(mTlvs + mLength); + cur = cur->GetNext()) + { + switch (cur->GetType()) + { + case NetworkDataTlv::kTypePrefix: + UpdateRloc(*static_cast(cur)); + break; + + default: + assert(false); + break; + } + } + + ClearResubmitDelayTimer(); + + return kThreadError_None; +} + +ThreadError Local::UpdateRloc(PrefixTlv &aPrefix) +{ + for (NetworkDataTlv *cur = aPrefix.GetSubTlvs(); cur < aPrefix.GetNext(); cur = cur->GetNext()) + { + switch (cur->GetType()) + { + case NetworkDataTlv::kTypeHasRoute: + UpdateRloc(*static_cast(cur)); + break; + + case NetworkDataTlv::kTypeBorderRouter: + UpdateRloc(*static_cast(cur)); + break; + + default: + assert(false); + break; + } + } + + return kThreadError_None; +} + +ThreadError Local::UpdateRloc(HasRouteTlv &aHasRoute) +{ + HasRouteEntry *entry = aHasRoute.GetEntry(0); + entry->SetRloc(mNetif.GetMle().GetRloc16()); + return kThreadError_None; +} + +ThreadError Local::UpdateRloc(BorderRouterTlv &aBorderRouter) +{ + BorderRouterEntry *entry = aBorderRouter.GetEntry(0); + entry->SetRloc(mNetif.GetMle().GetRloc16()); + return kThreadError_None; +} + +bool Local::IsOnMeshPrefixConsistent(void) +{ + return (mNetif.GetNetworkDataLeader().ContainsOnMeshPrefixes(*this, mNetif.GetMle().GetRloc16()) && + ContainsOnMeshPrefixes(mNetif.GetNetworkDataLeader(), mNetif.GetMle().GetRloc16())); +} + +bool Local::IsExternalRouteConsistent(void) +{ + return (mNetif.GetNetworkDataLeader().ContainsExternalRoutes(*this, mNetif.GetMle().GetRloc16()) && + ContainsExternalRoutes(mNetif.GetNetworkDataLeader(), mNetif.GetMle().GetRloc16())); +} + +ThreadError Local::SendServerDataNotification(void) +{ + ThreadError error = kThreadError_None; + uint16_t rloc = mNetif.GetMle().GetRloc16(); + + if ((mNetif.GetMle().GetDeviceMode() & Mle::ModeTlv::kModeFFD) != 0 && + (mNetif.GetMle().IsRouterRoleEnabled()) && + (mNetif.GetMle().GetDeviceState() < Mle::kDeviceStateRouter) && + (mNetif.GetMle().GetActiveRouterCount() < mNetif.GetMle().GetRouterUpgradeThreshold())) + { + ExitNow(error = kThreadError_InvalidState); + } + + UpdateRloc(); + + VerifyOrExit(!IsOnMeshPrefixConsistent() || !IsExternalRouteConsistent(), ClearResubmitDelayTimer()); + + if (mOldRloc == rloc) + { + mOldRloc = Mac::kShortAddrInvalid; + } + + SuccessOrExit(error = NetworkData::SendServerDataNotification(mOldRloc)); + mOldRloc = rloc; + +exit: + return error; +} + +} // namespace NetworkData +} // namespace Thread + diff --git a/pool/shard001/C++/0023735_msgout.cpp b/pool/shard001/C++/0023735_msgout.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ebeed13be03ef76b9ac3e379f7dd12a4785a2625 --- /dev/null +++ b/pool/shard001/C++/0023735_msgout.cpp @@ -0,0 +1,222 @@ +///////////////////////////////////////////////////////////////////////////// +// Name: src/common/msgout.cpp +// Purpose: wxMessageOutput implementation +// Author: Mattia Barbon +// Modified by: +// Created: 17.07.02 +// RCS-ID: $Id: msgout.cpp 38920 2006-04-26 08:21:31Z ABX $ +// Copyright: (c) the wxWidgets team +// Licence: wxWindows licence +///////////////////////////////////////////////////////////////////////////// + +// ============================================================================ +// declarations +// ============================================================================ + +// --------------------------------------------------------------------------- +// headers +// --------------------------------------------------------------------------- + +// For compilers that support precompilation, includes "wx.h". +#include "wx/wxprec.h" + +#if defined(__BORLANDC__) + #pragma hdrstop +#endif + +#ifndef WX_PRECOMP + #include "wx/string.h" + #include "wx/ffile.h" + #include "wx/app.h" + #include "wx/intl.h" + #include "wx/log.h" + #if wxUSE_GUI + #include "wx/msgdlg.h" + #endif // wxUSE_GUI +#endif + +#include "wx/msgout.h" +#include "wx/apptrait.h" +#include +#include + +#if defined(__WINDOWS__) + #include "wx/msw/private.h" +#endif +#ifdef __WXMAC__ + #include "wx/mac/private.h" +#endif + +// =========================================================================== +// implementation +// =========================================================================== + +#if wxUSE_BASE + +// ---------------------------------------------------------------------------- +// wxMessageOutput +// ---------------------------------------------------------------------------- + +wxMessageOutput* wxMessageOutput::ms_msgOut = 0; + +wxMessageOutput* wxMessageOutput::Get() +{ + if ( !ms_msgOut && wxTheApp ) + { + ms_msgOut = wxTheApp->GetTraits()->CreateMessageOutput(); + } + + return ms_msgOut; +} + +wxMessageOutput* wxMessageOutput::Set(wxMessageOutput* msgout) +{ + wxMessageOutput* old = ms_msgOut; + ms_msgOut = msgout; + return old; +} + +// ---------------------------------------------------------------------------- +// wxMessageOutputBest +// ---------------------------------------------------------------------------- + +#ifdef __WINDOWS__ + +// check if we're running in a console under Windows +static inline bool IsInConsole() +{ +#ifdef __WXWINCE__ + return false; +#else // !__WXWINCE__ + HANDLE hStdErr = ::GetStdHandle(STD_ERROR_HANDLE); + return hStdErr && hStdErr != INVALID_HANDLE_VALUE; +#endif // __WXWINCE__/!__WXWINCE__ +} + +#endif // __WINDOWS__ + +void wxMessageOutputBest::Printf(const wxChar* format, ...) +{ + va_list args; + va_start(args, format); + wxString out; + + out.PrintfV(format, args); + va_end(args); + +#ifdef __WINDOWS__ + if ( !IsInConsole() ) + { + ::MessageBox(NULL, out, _T("wxWidgets"), MB_ICONINFORMATION | MB_OK); + } + else +#endif // __WINDOWS__/!__WINDOWS__ + { + fprintf(stderr, "%s", (const char*) out.mb_str()); + } +} + +// ---------------------------------------------------------------------------- +// wxMessageOutputStderr +// ---------------------------------------------------------------------------- + +void wxMessageOutputStderr::Printf(const wxChar* format, ...) +{ + va_list args; + va_start(args, format); + wxString out; + + out.PrintfV(format, args); + va_end(args); + + fprintf(stderr, "%s", (const char*) out.mb_str()); +} + +// ---------------------------------------------------------------------------- +// wxMessageOutputDebug +// ---------------------------------------------------------------------------- + +void wxMessageOutputDebug::Printf(const wxChar* format, ...) +{ + wxString out; + + va_list args; + va_start(args, format); + + out.PrintfV(format, args); + va_end(args); + +#if defined(__WXMSW__) && !defined(__WXMICROWIN__) + out.Replace(wxT("\t"), wxT(" ")); + out.Replace(wxT("\n"), wxT("\r\n")); + ::OutputDebugString(out); +#elif defined(__WXMAC__) && !defined(__DARWIN__) + if ( wxIsDebuggerRunning() ) + { + Str255 pstr; + wxString output = out + wxT(";g") ; + wxMacStringToPascal(output.c_str(), pstr); + + #ifdef __powerc + DebugStr(pstr); + #else + SysBreakStr(pstr); + #endif + } +#else + wxFputs( out , stderr ) ; + if ( out.Right(1) != wxT("\n") ) + wxFputs( wxT("\n") , stderr ) ; + fflush( stderr ) ; +#endif // platform +} + +// ---------------------------------------------------------------------------- +// wxMessageOutputLog +// ---------------------------------------------------------------------------- + +void wxMessageOutputLog::Printf(const wxChar* format, ...) +{ + wxString out; + + va_list args; + va_start(args, format); + + out.PrintfV(format, args); + va_end(args); + + out.Replace(wxT("\t"), wxT(" ")); + + ::wxLogMessage(wxT("%s"), out.c_str()); +} + +#endif // wxUSE_BASE + +// ---------------------------------------------------------------------------- +// wxMessageOutputMessageBox +// ---------------------------------------------------------------------------- + +#if wxUSE_GUI + +void wxMessageOutputMessageBox::Printf(const wxChar* format, ...) +{ + va_list args; + va_start(args, format); + wxString out; + + out.PrintfV(format, args); + va_end(args); + + // the native MSW msg box understands the TABs, others don't +#ifndef __WXMSW__ + out.Replace(wxT("\t"), wxT(" ")); +#endif + + wxString title; + if ( wxTheApp ) + title.Printf(_("%s message"), wxTheApp->GetAppName().c_str()); + + ::wxMessageBox(out, title); +} + +#endif // wxUSE_GUI diff --git a/pool/shard001/C++/0023737_parms.cc b/pool/shard001/C++/0023737_parms.cc new file mode 100644 index 0000000000000000000000000000000000000000..865efd1ac6269e53a28687f5c9f05a31af048e2a --- /dev/null +++ b/pool/shard001/C++/0023737_parms.cc @@ -0,0 +1,44 @@ +// { dg-options "-std=gnu++11" } +// { dg-require-cstdint "" } +// +// 2008-11-24 Edward M. Smith-Rowland <3dw4rd@verizon.net> +// 2013-03-02 Ulrich Drepper +// +// Copyright (C) 2013-2014 Free Software Foundation, Inc. +// +// This file is part of the GNU ISO C++ Library. This library is free +// software; you can redistribute it and/or modify it under the +// terms of the GNU General Public License as published by the +// Free Software Foundation; either version 3, or (at your option) +// any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this library; see the file COPYING3. If not see +// . + +#include +#include + +void +test01() +{ + bool test __attribute__((unused)) = true; + + __gnu_cxx::triangular_distribution<> u(1.5, 3.0, 3.5); + VERIFY( u.a() == 1.5 ); + VERIFY( u.b() == 3.0 ); + VERIFY( u.c() == 3.5 ); + VERIFY( u.min() == 1.5 ); + VERIFY( u.max() == 3.5 ); +} + +int main() +{ + test01(); + return 0; +} diff --git a/pool/shard001/C++/0023742_escape.cpp b/pool/shard001/C++/0023742_escape.cpp new file mode 100644 index 0000000000000000000000000000000000000000..95c07767e28b6cb7a63c59a0f681cb25c0fcf0b2 --- /dev/null +++ b/pool/shard001/C++/0023742_escape.cpp @@ -0,0 +1,57 @@ +/******************************************************************************* +* yacurlw * +* Copyright (C) 2017 Etienne Schmitt * +* 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.0 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. * +* * +* Web site: https://github.com/etienneschmitt/yacurlw * +* * +*******************************************************************************/ + +#include "escape.h" +#include "easyinit.h" +#include +#include +#include +#include +#include + +namespace yacurlw +{ + +std::string escape(const std::string& url) +{ + internal::EasyInit easy; + boost::shared_ptr p( + curl_escape(url.c_str(), static_cast(url.size())), + boost::lambda::bind(curl_free, boost::lambda::_1)); + if(!p) + throw std::runtime_error("unable to escape the string"); + + return std::string(p.get()); +} + +std::string unescape(const std::string& str) +{ + internal::EasyInit easy; + boost::shared_ptr p( + curl_easy_unescape(NULL, str.c_str(), static_cast(str.size()), NULL), + boost::lambda::bind(curl_free, boost::lambda::_1)); + if(!p) + throw std::runtime_error("unable to unescape the string"); + + return std::string(p.get()); +} + +} // namespace yacurlw diff --git a/pool/shard001/C++/0023744_HttpGet.cpp b/pool/shard001/C++/0023744_HttpGet.cpp new file mode 100644 index 0000000000000000000000000000000000000000..60733abd30ff2c4ff6af51333af0702f548b3e41 --- /dev/null +++ b/pool/shard001/C++/0023744_HttpGet.cpp @@ -0,0 +1,61 @@ +//------------------------------------------------------------------------------ +// +// Copyright (C) Streamlet. All rights reserved. +// +// File Name: HttpGet.cpp +// Author: Streamlet +// Create Time: 2010-10-29 +// Description: +// +// Version history: +// +// +// +//------------------------------------------------------------------------------ + + +#include "HttpGet.h" +#include "HttpIO.h" + +HttpGet::HttpGet(LPCTSTR lpAgent /* = NULL */) + : m_strAgent(lpAgent) +{ + +} + +HttpGet::~HttpGet() +{ + +} + +bool HttpGet::SendRequest(LPCTSTR lpUrl, HANDLE hEventCancel, xl::Array *pContent) +{ + URL_COMPONENTS urlComp = { sizeof(URL_COMPONENTS) }; + + urlComp.dwHostNameLength = (DWORD)-1; + urlComp.dwUrlPathLength = (DWORD)-1; + urlComp.dwExtraInfoLength = (DWORD)-1; + + if (!WinHttpCrackUrl(lpUrl, 0, 0, &urlComp)) + { + return false; + } + + xl::String strHostName = xl::String(urlComp.lpszHostName, urlComp.dwHostNameLength); + xl::String strPagePath = xl::String(urlComp.lpszUrlPath, urlComp.dwUrlPathLength) + + xl::String(urlComp.lpszExtraInfo, urlComp.dwExtraInfoLength); + + HttpIO http(m_strAgent); + + if (!http.Connect(strHostName)) + { + return false; + } + + if (!http.SendRequest(L"GET", strPagePath, NULL, NULL, 0, hEventCancel, pContent)) + { + return false; + } + + return true; +} diff --git a/pool/shard001/C++/0023747_ms_check.cpp b/pool/shard001/C++/0023747_ms_check.cpp new file mode 100644 index 0000000000000000000000000000000000000000..707da95cdff0b07b5adb4ef0e056acb52d5873a0 --- /dev/null +++ b/pool/shard001/C++/0023747_ms_check.cpp @@ -0,0 +1,87 @@ +/* MemoServ core functions + * + * (C) 2003-2016 Anope Team + * Contact us at team@anope.org + * + * Please read COPYING and README for further details. + * + * Based on the original code of Epona by Lara. + * Based on the original code of Services by Andy Church. + */ + +#include "module.h" + +class CommandMSCheck : public Command +{ + public: + CommandMSCheck(Module *creator) : Command(creator, "memoserv/check", 1, 1) + { + this->SetDesc(_("Checks if last memo to a nick was read")); + this->SetSyntax(_("\037nick\037")); + } + + void Execute(CommandSource &source, const std::vector ¶ms) anope_override + { + + const Anope::string &recipient = params[0]; + + bool found = false; + + const NickAlias *na = NickAlias::Find(recipient); + if (!na) + { + source.Reply(NICK_X_NOT_REGISTERED, recipient.c_str()); + return; + } + + MemoInfo *mi = &na->nc->memos; + + /* Okay, I know this looks strange but we want to get the LAST memo, so we + have to loop backwards */ + + for (unsigned i = mi->memos->size(); i > 0; --i) + { + Memo *m = mi->GetMemo(i - 1); + NickAlias *na2 = NickAlias::Find(m->sender); + + if (na2 != NULL && na2->nc == source.GetAccount()) + { + found = true; /* Yes, we've found the memo */ + + if (m->unread) + source.Reply(_("The last memo you sent to %s (sent on %s) has not yet been read."), na->nick.c_str(), Anope::strftime(m->time, source.GetAccount()).c_str()); + else + source.Reply(_("The last memo you sent to %s (sent on %s) has been read."), na->nick.c_str(), Anope::strftime(m->time, source.GetAccount()).c_str()); + break; + } + } + + if (!found) + source.Reply(_("Nick %s doesn't have a memo from you."), na->nick.c_str()); + + return; + } + + bool OnHelp(CommandSource &source, const Anope::string &subcommand) anope_override + { + this->SendSyntax(source); + source.Reply(" "); + source.Reply(_("Checks whether the _last_ memo you sent to \037nick\037 has been read\n" + "or not. Note that this only works with nicks, not with channels.")); + return true; + } +}; + +class MSCheck : public Module +{ + CommandMSCheck commandmscheck; + + public: + MSCheck(const Anope::string &modname, const Anope::string &creator) : Module(modname, creator, VENDOR), + commandmscheck(this) + { + + } +}; + +MODULE_INIT(MSCheck) diff --git a/pool/shard001/C++/0023748_usr0sess.cc b/pool/shard001/C++/0023748_usr0sess.cc new file mode 100644 index 0000000000000000000000000000000000000000..f50ab6c36f0696f5e951f260b6e9ca4dcbffdd22 --- /dev/null +++ b/pool/shard001/C++/0023748_usr0sess.cc @@ -0,0 +1,70 @@ +/***************************************************************************** + +Copyright (c) 1996, 2014, 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 Street, Suite 500, Boston, MA 02110-1335 USA + +*****************************************************************************/ + +/**************************************************//** +@file usr/usr0sess.cc +Sessions + +Created 6/25/1996 Heikki Tuuri +*******************************************************/ + +#include "usr0sess.h" + +#ifdef UNIV_NONINL +#include "usr0sess.ic" +#endif + +#include "trx0trx.h" + +/*********************************************************************//** +Opens a session. +@return own: session object */ +sess_t* +sess_open(void) +/*===========*/ +{ + sess_t* sess; + + sess = static_cast(ut_zalloc_nokey(sizeof(*sess))); + + sess->state = SESS_ACTIVE; + + sess->trx = trx_allocate_for_background(); + sess->trx->sess = sess; + + return(sess); +} + +/*********************************************************************//** +Closes a session, freeing the memory occupied by it. */ +void +sess_close( +/*=======*/ + sess_t* sess) /*!< in, own: session object */ +{ + trx_free_for_background(sess->trx); + ut_free(sess); +} diff --git a/pool/shard001/C++/0023756_Search_BST_for_first_occurrence_recursive.cc b/pool/shard001/C++/0023756_Search_BST_for_first_occurrence_recursive.cc new file mode 100644 index 0000000000000000000000000000000000000000..11d459a0b1a2efa6822e6c4fb64f793edba0bd65 --- /dev/null +++ b/pool/shard001/C++/0023756_Search_BST_for_first_occurrence_recursive.cc @@ -0,0 +1,53 @@ +// Copyright (c) 2013 Elements of Programming Interviews. All rights reserved. + +#include +#include + +#include "./BST_prototype.h" + +using std::unique_ptr; + +// @include +BSTNode* FindFirstEqualK(const unique_ptr>& tree, int k) { + if (!tree) { + return nullptr; // No match. + } else if (tree->data == k) { + // Recursively search the left subtree for first node containing k. + auto* node = FindFirstEqualK(tree->left, k); + return node ? node : tree.get(); + } + // Search the left or right subtree based on relative values of tree->data + // and k. + return FindFirstEqualK(tree->data < k ? tree->right : tree->left, k); +} +// @exclude + +int main(int argc, char* argv[]) { + // 3 + // 2 6 + // 1 4 6 + auto root = unique_ptr>(new BSTNode{3}); + root->left = unique_ptr>(new BSTNode{2}); + root->left->left = unique_ptr>(new BSTNode{1}); + root->right = unique_ptr>(new BSTNode{6}); + root->right->left = unique_ptr>(new BSTNode{4}); + root->right->right = unique_ptr>(new BSTNode{6}); + assert(!FindFirstEqualK(root, 7)); + assert(FindFirstEqualK(root, 6)->data == 6 && + FindFirstEqualK(root, 6)->right->data == 6); + + // 3 + // 3 5 + // 2 5 6 + root = unique_ptr>(new BSTNode{3}); + root->left = unique_ptr>(new BSTNode{3}); + root->left->left = unique_ptr>(new BSTNode{2}); + root->right = unique_ptr>(new BSTNode{5}); + root->right->left = unique_ptr>(new BSTNode{5}); + root->right->right = unique_ptr>(new BSTNode{6}); + assert(!FindFirstEqualK(root, 7)); + assert(FindFirstEqualK(root, 3) == root->left.get()); + assert(FindFirstEqualK(root, 5) == root->right->left.get()); + assert(FindFirstEqualK(root, 6)->data == 6); + return 0; +} diff --git a/pool/shard001/C++/0023759_tcp-tx-buffer.cc b/pool/shard001/C++/0023759_tcp-tx-buffer.cc new file mode 100644 index 0000000000000000000000000000000000000000..7ea1d308d3ed9ba688afe36dbf677e3b070b3c16 --- /dev/null +++ b/pool/shard001/C++/0023759_tcp-tx-buffer.cc @@ -0,0 +1,250 @@ +/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ +/* + * Copyright (c) 2010 Adrian Sai-wah Tam + * + * 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: Adrian Sai-wah Tam + */ + +#include +#include +#include +#include "ns3/packet.h" +#include "ns3/fatal-error.h" +#include "ns3/log.h" +#include "tcp-tx-buffer.h" + +NS_LOG_COMPONENT_DEFINE ("TcpTxBuffer"); + +namespace ns3 { + +TypeId +TcpTxBuffer::GetTypeId (void) +{ + static TypeId tid = TypeId ("ns3::TcpTxBuffer") + .SetParent () + .AddConstructor () + .AddTraceSource ("UnackSequence", + "First unacknowledged sequence number (SND.UNA)", + MakeTraceSourceAccessor (&TcpTxBuffer::m_firstByteSeq)) + ; + return tid; +} + +/* A user is supposed to create a TcpSocket through a factory. In TcpSocket, + * there are attributes SndBufSize and RcvBufSize to control the default Tx and + * Rx window sizes respectively, with default of 128 KiByte. The attribute + * SndBufSize is passed to TcpTxBuffer by TcpSocketBase::SetSndBufSize() and in + * turn, TcpTxBuffer:SetMaxBufferSize(). Therefore, the m_maxBuffer value + * initialized below is insignificant. + */ +TcpTxBuffer::TcpTxBuffer (uint32_t n) + : m_firstByteSeq(n), m_size (0), m_maxBuffer(32768), m_data (0) +{ +} + +TcpTxBuffer::~TcpTxBuffer (void) +{ +} + +SequenceNumber32 +TcpTxBuffer::HeadSequence (void) const +{ + return m_firstByteSeq; +} + +SequenceNumber32 +TcpTxBuffer::TailSequence (void) const +{ + return m_firstByteSeq + SequenceNumber32 (m_size); +} + +uint32_t +TcpTxBuffer::Size (void) const +{ + return m_size; +} + +uint32_t +TcpTxBuffer::MaxBufferSize (void) const +{ + return m_maxBuffer; +} + +void +TcpTxBuffer::SetMaxBufferSize (uint32_t n) +{ + m_maxBuffer = n; +} + +uint32_t +TcpTxBuffer::Available (void) const +{ + return m_maxBuffer - m_size; +} + +bool +TcpTxBuffer::Add (Ptr p) +{ + NS_LOG_FUNCTION (this << p); + NS_LOG_LOGIC ("Packet of size " << p->GetSize () << " appending to window starting at " + << m_firstByteSeq << ", availSize="<< Available ()); + if (p->GetSize () <= Available ()) + { + if (p->GetSize () > 0) + { + m_data.push_back (p); + m_size += p->GetSize (); + NS_LOG_LOGIC ("Updated size=" << m_size << ", lastSeq=" << m_firstByteSeq + SequenceNumber32 (m_size)); + } + return true; + } + NS_LOG_LOGIC ("Rejected. Not enough room to buffer packet."); + return false; +} + +uint32_t +TcpTxBuffer::SizeFromSequence (const SequenceNumber32& seq) const +{ + NS_LOG_FUNCTION (this << seq); + // Sequence of last byte in buffer + SequenceNumber32 lastSeq = m_firstByteSeq + SequenceNumber32 (m_size); + // Non-negative size + NS_LOG_LOGIC ("HeadSeq=" << m_firstByteSeq << ", lastSeq=" << lastSeq << ", size=" << m_size << + ", returns " << lastSeq - seq); + return lastSeq - seq; +} + +Ptr +TcpTxBuffer::CopyFromSequence (uint32_t numBytes, const SequenceNumber32& seq) +{ + NS_LOG_FUNCTION (this << numBytes << seq); + uint32_t s = std::min (numBytes, SizeFromSequence (seq)); // Real size to extract. Insure not beyond end of data + if (s == 0) + { + return Create (); // Empty packet returned + } + if (m_data.size () == 0) + { // No actual data, just return dummy-data packet of correct size + return Create (s); + } + + // Extract data from the buffer and return + uint32_t offset = seq - m_firstByteSeq.Get (); + uint32_t count = 0; // Offset of the first byte of a packet in the buffer + uint32_t pktSize = 0; + bool beginFound = false; + int pktCount = 0; + Ptr outPacket; + NS_LOG_LOGIC ("There are " << m_data.size () << " number of packets in buffer"); + for (BufIterator i = m_data.begin (); i != m_data.end (); ++i) + { + pktCount++; + pktSize = (*i)->GetSize (); + if (!beginFound) + { // Look for first fragment + if (count + pktSize > offset) + { + NS_LOG_LOGIC ("First byte found in packet #" << pktCount << " at buffer offset " << count + << ", packet len=" << pktSize); + beginFound = true; + uint32_t packetOffset = offset - count; + uint32_t fragmentLength = count + pktSize - offset; + if (fragmentLength >= s) + { // Data to be copied falls entirely in this packet + return (*i)->CreateFragment (packetOffset, s); + } + else + { // This packet only fulfills part of the request + outPacket = (*i)->CreateFragment (packetOffset, fragmentLength); + } + NS_LOG_LOGIC ("Output packet is now of size " << outPacket->GetSize ()); + } + } + else if (count + pktSize >= offset + s) + { // Last packet fragment found + NS_LOG_LOGIC ("Last byte found in packet #" << pktCount << " at buffer offset " << count + << ", packet len=" << pktSize); + uint32_t fragmentLength = offset + s - count; + Ptr endFragment = (*i)->CreateFragment (0, fragmentLength); + outPacket->AddAtEnd (endFragment); + NS_LOG_LOGIC ("Output packet is now of size " << outPacket->GetSize ()); + break; + } + else + { + NS_LOG_LOGIC ("Appending to output the packet #" << pktCount << " of offset " << count << " len=" << pktSize); + outPacket->AddAtEnd (*i); + NS_LOG_LOGIC ("Output packet is now of size " << outPacket->GetSize ()); + } + count += pktSize; + } + NS_ASSERT (outPacket->GetSize () == s); + return outPacket; +} + +void +TcpTxBuffer::SetHeadSequence (const SequenceNumber32& seq) +{ + NS_LOG_FUNCTION (this << seq); + m_firstByteSeq = seq; +} + +void +TcpTxBuffer::DiscardUpTo (const SequenceNumber32& seq) +{ + NS_LOG_FUNCTION (this << seq); + NS_LOG_LOGIC ("current data size=" << m_size << ", headSeq=" << m_firstByteSeq << ", maxBuffer=" << m_maxBuffer + << ", numPkts=" << m_data.size ()); + // Cases do not need to scan the buffer + if (m_firstByteSeq >= seq) return; + + // Scan the buffer and discard packets + uint32_t offset = seq - m_firstByteSeq.Get (); // Number of bytes to remove + uint32_t pktSize; + NS_LOG_LOGIC ("Offset=" << offset); + BufIterator i = m_data.begin (); + while (i != m_data.end ()) + { + if (offset > (*i)->GetSize ()) + { // This packet is behind the seqnum. Remove this packet from the buffer + pktSize = (*i)->GetSize (); + m_size -= pktSize; + offset -= pktSize; + m_firstByteSeq += pktSize; + i = m_data.erase (i); + NS_LOG_LOGIC ("Removed one packet of size " << pktSize << ", offset=" << offset); + } + else if (offset > 0) + { // Part of the packet is behind the seqnum. Fragment + pktSize = (*i)->GetSize () - offset; + *i = (*i)->CreateFragment (offset, pktSize); + m_size -= offset; + m_firstByteSeq += offset; + NS_LOG_LOGIC ("Fragmented one packet by size " << offset << ", new size=" << pktSize); + break; + } + } + // Catching the case of ACKing a FIN + if (m_size == 0) + { + m_firstByteSeq = seq; + } + NS_LOG_LOGIC ("size=" << m_size << " headSeq=" << m_firstByteSeq << " maxBuffer=" << m_maxBuffer + <<" numPkts="<< m_data.size ()); + NS_ASSERT (m_firstByteSeq == seq); +} + +} // namepsace ns3 diff --git a/pool/shard001/C++/0023768_weight.cc b/pool/shard001/C++/0023768_weight.cc new file mode 100644 index 0000000000000000000000000000000000000000..b34dd0a8d193585d741a88bcdaf55f83bdc83429 --- /dev/null +++ b/pool/shard001/C++/0023768_weight.cc @@ -0,0 +1,117 @@ +#include + +DEFINE_string(fst_weight_separator, ",", + "Character separator between printed composite weights; " + "must be a single character"); + +DEFINE_string(fst_weight_parentheses, "", + "Characters enclosing the first weight of a printed composite " + "weight (e.g., pair weight, tuple weight and derived classes) to " + "ensure proper I/O of nested composite weights; " + "must have size 0 (none) or 2 (open and close parenthesis)"); + +namespace fst { + +namespace internal { + +CompositeWeightIO::CompositeWeightIO(char separator, + std::pair parentheses) + : separator_(separator), + open_paren_(parentheses.first), + close_paren_(parentheses.second), + error_(false) { + if ((open_paren_ == 0 || close_paren_ == 0) && open_paren_ != close_paren_) { + FSTERROR() << "Invalid configuration of weight parentheses: " + << static_cast(open_paren_) << " " + << static_cast(close_paren_); + error_ = true; + } +} + +CompositeWeightIO::CompositeWeightIO() + : CompositeWeightIO(FLAGS_fst_weight_separator.empty() + ? 0 + : FLAGS_fst_weight_separator.front(), + {FLAGS_fst_weight_parentheses.empty() + ? 0 + : FLAGS_fst_weight_parentheses[0], + FLAGS_fst_weight_parentheses.size() < 2 + ? 0 + : FLAGS_fst_weight_parentheses[1]}) { + if (FLAGS_fst_weight_separator.size() != 1) { + FSTERROR() << "CompositeWeight: " + << "FLAGS_fst_weight_separator.size() is not equal to 1"; + error_ = true; + } + if (!FLAGS_fst_weight_parentheses.empty() && + FLAGS_fst_weight_parentheses.size() != 2) { + FSTERROR() << "CompositeWeight: " + << "FLAGS_fst_weight_parentheses.size() is not equal to 2"; + error_ = true; + } +} + +} // namespace internal + +CompositeWeightWriter::CompositeWeightWriter(std::ostream &ostrm) + : ostrm_(ostrm) { + if (error()) ostrm.clear(std::ios::badbit); +} + +CompositeWeightWriter::CompositeWeightWriter(std::ostream &ostrm, + char separator, + std::pair parentheses) + : internal::CompositeWeightIO(separator, parentheses), ostrm_(ostrm) { + if (error()) ostrm_.clear(std::ios::badbit); +} + +void CompositeWeightWriter::WriteBegin() { + if (open_paren_ != 0) { + ostrm_ << open_paren_; + } +} + +void CompositeWeightWriter::WriteEnd() { + if (close_paren_ != 0) { + ostrm_ << close_paren_; + } +} + +CompositeWeightReader::CompositeWeightReader(std::istream &istrm) + : istrm_(istrm) { + if (error()) istrm_.clear(std::ios::badbit); +} + +CompositeWeightReader::CompositeWeightReader(std::istream &istrm, + char separator, + std::pair parentheses) + : internal::CompositeWeightIO(separator, parentheses), istrm_(istrm) { + if (error()) istrm_.clear(std::ios::badbit); +} + +void CompositeWeightReader::ReadBegin() { + do { // Skips whitespace. + c_ = istrm_.get(); + } while (std::isspace(c_)); + if (open_paren_ != 0) { + if (c_ != open_paren_) { + FSTERROR() << "CompositeWeightReader: Open paren missing: " + << "fst_weight_parentheses flag set correcty?"; + istrm_.clear(std::ios::badbit); + return; + } + ++depth_; + c_ = istrm_.get(); + } +} + +void CompositeWeightReader::ReadEnd() { + if (c_ != EOF && !std::isspace(c_)) { + FSTERROR() << "CompositeWeightReader: excess character: '" + << static_cast(c_) + << "': fst_weight_parentheses flag set correcty?"; + istrm_.clear(std::ios::badbit); + } +} + +} // namespace fst diff --git a/pool/shard001/C++/0023769_video_capture_impl_manager_unittest.cc b/pool/shard001/C++/0023769_video_capture_impl_manager_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..349a32eca34dd43331fda673b53267c1fae1ed56 --- /dev/null +++ b/pool/shard001/C++/0023769_video_capture_impl_manager_unittest.cc @@ -0,0 +1,168 @@ +// 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 "base/bind.h" +#include "base/callback.h" +#include "base/macros.h" +#include "base/memory/ref_counted.h" +#include "base/message_loop/message_loop.h" +#include "base/run_loop.h" +#include "content/child/child_process.h" +#include "content/renderer/media/video_capture_impl.h" +#include "content/renderer/media/video_capture_impl_manager.h" +#include "content/renderer/media/video_capture_message_filter.h" +#include "media/base/bind_to_current_loop.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" + +using ::testing::_; +using ::testing::DoAll; +using ::testing::SaveArg; +using media::BindToCurrentLoop; + +namespace content { + +ACTION_P(RunClosure, closure) { + closure.Run(); +} + +class MockVideoCaptureImpl : public VideoCaptureImpl { + public: + MockVideoCaptureImpl(media::VideoCaptureSessionId session_id, + VideoCaptureMessageFilter* filter, + base::Closure destruct_callback) + : VideoCaptureImpl(session_id, filter), + destruct_callback_(destruct_callback) { + } + + ~MockVideoCaptureImpl() override { destruct_callback_.Run(); } + + private: + base::Closure destruct_callback_; + + DISALLOW_COPY_AND_ASSIGN(MockVideoCaptureImpl); +}; + +class MockVideoCaptureImplManager : public VideoCaptureImplManager { + public: + explicit MockVideoCaptureImplManager( + base::Closure destruct_video_capture_callback) + : destruct_video_capture_callback_( + destruct_video_capture_callback) {} + ~MockVideoCaptureImplManager() override {} + + protected: + VideoCaptureImpl* CreateVideoCaptureImplForTesting( + media::VideoCaptureSessionId id, + VideoCaptureMessageFilter* filter) const override { + return new MockVideoCaptureImpl(id, + filter, + destruct_video_capture_callback_); + } + + private: + base::Closure destruct_video_capture_callback_; + + DISALLOW_COPY_AND_ASSIGN(MockVideoCaptureImplManager); +}; + +class VideoCaptureImplManagerTest : public ::testing::Test { + public: + VideoCaptureImplManagerTest() + : manager_(new MockVideoCaptureImplManager( + BindToCurrentLoop(cleanup_run_loop_.QuitClosure()))) { + params_.requested_format = media::VideoCaptureFormat( + gfx::Size(176, 144), 30, media::PIXEL_FORMAT_I420); + child_process_.reset(new ChildProcess()); + } + + void FakeChannelSetup() { + scoped_refptr task_runner = + child_process_->io_task_runner(); + if (!task_runner->BelongsToCurrentThread()) { + task_runner->PostTask( + FROM_HERE, base::Bind(&VideoCaptureImplManagerTest::FakeChannelSetup, + base::Unretained(this))); + return; + } + manager_->video_capture_message_filter()->OnFilterAdded(NULL); + } + + protected: + MOCK_METHOD2(OnFrameReady, + void(const scoped_refptr&, + base::TimeTicks estimated_capture_time)); + MOCK_METHOD0(OnStarted, void()); + MOCK_METHOD0(OnStopped, void()); + + void OnStateUpdate(VideoCaptureState state) { + switch (state) { + case VIDEO_CAPTURE_STATE_STARTED: + OnStarted(); + break; + case VIDEO_CAPTURE_STATE_STOPPED: + OnStopped(); + break; + default: + NOTREACHED(); + } + } + + base::Closure StartCapture(const media::VideoCaptureParams& params) { + return manager_->StartCapture( + 0, params, base::Bind(&VideoCaptureImplManagerTest::OnStateUpdate, + base::Unretained(this)), + base::Bind(&VideoCaptureImplManagerTest::OnFrameReady, + base::Unretained(this))); + } + + base::MessageLoop message_loop_; + std::unique_ptr child_process_; + media::VideoCaptureParams params_; + base::RunLoop cleanup_run_loop_; + std::unique_ptr manager_; + + private: + DISALLOW_COPY_AND_ASSIGN(VideoCaptureImplManagerTest); +}; + +// Multiple clients with the same session id. There is only one +// media::VideoCapture object. +TEST_F(VideoCaptureImplManagerTest, MultipleClients) { + base::Closure release_cb1 = manager_->UseDevice(0); + base::Closure release_cb2 = manager_->UseDevice(0); + base::Closure stop_cb1, stop_cb2; + { + base::RunLoop run_loop; + base::Closure quit_closure = BindToCurrentLoop(run_loop.QuitClosure()); + EXPECT_CALL(*this, OnStarted()).WillOnce(RunClosure(quit_closure)); + EXPECT_CALL(*this, OnStarted()).RetiresOnSaturation(); + stop_cb1 = StartCapture(params_); + stop_cb2 = StartCapture(params_); + FakeChannelSetup(); + run_loop.Run(); + } + + { + base::RunLoop run_loop; + base::Closure quit_closure = BindToCurrentLoop(run_loop.QuitClosure()); + EXPECT_CALL(*this, OnStopped()).WillOnce(RunClosure(quit_closure)); + EXPECT_CALL(*this, OnStopped()).RetiresOnSaturation(); + stop_cb1.Run(); + stop_cb2.Run(); + run_loop.Run(); + } + + release_cb1.Run(); + release_cb2.Run(); + cleanup_run_loop_.Run(); +} + +TEST_F(VideoCaptureImplManagerTest, NoLeak) { + manager_->UseDevice(0).Reset(); + manager_.reset(); + cleanup_run_loop_.Run(); +} + +} // namespace content diff --git a/pool/shard001/C++/0023770_DSENTInterface.cc b/pool/shard001/C++/0023770_DSENTInterface.cc new file mode 100644 index 0000000000000000000000000000000000000000..213c04480589a6caac8c0a69cb59875c2949f7db --- /dev/null +++ b/pool/shard001/C++/0023770_DSENTInterface.cc @@ -0,0 +1,163 @@ +#include "DSENTInterface.h" +#include "dsent-core/libutil/LibUtil.h" +#include "dsent-core/DSENT.h" + +#include +#include +#include +#include +#include + +using namespace std; +using namespace LibUtil; + +namespace dsent_contrib +{ + DSENTInterface* DSENTInterface::m_singleton = NULL; + + const String DSENTInterface::el_link_cfg_file_name = "electrical-link.cfg"; + const String DSENTInterface::op_link_cfg_file_name = "photonic-link.cfg"; + const String DSENTInterface::router_cfg_file_name = "router.cfg"; + + DSENTInterface::Overwrite::Overwrite(const String& var_, const String& val_) : + m_var_(var_), m_val_(val_) + {} + + DSENTInterface::Overwrite::~Overwrite() + {} + + void DSENTInterface::allocate(const string& dsent_path_, unsigned int tech_node_) + { + assert(!m_singleton); + m_singleton = new DSENTInterface(String(dsent_path_), tech_node_); + } + + void DSENTInterface::release() + { + assert(m_singleton); + delete m_singleton; + } + + DSENTInterface* DSENTInterface::getSingleton() + { + assert(m_singleton); + return m_singleton; + } + + DSENTInterface::DSENTInterface(const String& dsent_path_, unsigned int tech_node_) + { + m_el_link_cfg_file_path_ = dsent_path_ + "/dsent-core/configs/" + el_link_cfg_file_name; + m_op_link_cfg_file_path_ = dsent_path_ + "/dsent-core/configs/" + op_link_cfg_file_name; + m_router_cfg_file_path_ = dsent_path_ + "/dsent-core/configs/" + router_cfg_file_name; + + // Photonics techfile + m_phot_tech_file_path_ = dsent_path_ + "/dsent-core/tech/tech_models/" + "Photonics.model"; + + // Some hardcoded elements to this, depending on when graphite is able to parametrize the other parts + if (tech_node_ == 45) m_elec_tech_file_path_ = dsent_path_ + "/dsent-core/tech/tech_models/" + "Bulk45LVT.model"; + else if (tech_node_ == 32) m_elec_tech_file_path_ = dsent_path_ + "/dsent-core/tech/tech_models/" + "Bulk32LVT.model"; + else if (tech_node_ == 22) m_elec_tech_file_path_ = dsent_path_ + "/dsent-core/tech/tech_models/" + "Bulk22LVT.model"; + else if (tech_node_ == 11) m_elec_tech_file_path_ = dsent_path_ + "/dsent-core/tech/tech_models/" + "TG11LVT.model"; + else assert(false); + + // Create global tech overwrites + m_overwrites_tech_ = new vector(); + + // Get the database filename & library name + string dsent_libname = dsent_path_ + "/libdsent_contrib.a"; + DBUtils::initialize(m_database, "dsent", dsent_libname); + } + + DSENTInterface::~DSENTInterface() + { + delete m_overwrites_tech_; + } + + void DSENTInterface::add_global_tech_overwrite(const String& var_, const String& val_) + { + m_overwrites_tech_->push_back(Overwrite(var_, val_)); + } + + vector DSENTInterface::run_dsent(const String& cfg_file_path_, const vector& evals_, + const vector& overwrites_, const vector& overwrites_tech_) const + { + // Create String stream to pass to DSENT + ostringstream dsent_ost; + // Create DSENT arguments vector + vector* dsent_args = new vector(); + // Overwrites string + String overwrites_str = ""; + // Tech overwrites string + String overwrites_tech_str = ""; + // DSENT output string + String dsent_out_string; + + // Specify the correct config file path + dsent_args->push_back("-cfg"); + dsent_args->push_back(cfg_file_path_); + + // Clear any queries + dsent_args->push_back("-query"); + dsent_args->push_back(" "); + + // Create evaluate String + if (!evals_.empty()) + { + String eval_str = ""; + for (vector::const_iterator it = evals_.begin(); it != evals_.end(); it++) + eval_str += "print " + *it + ";"; + dsent_args->push_back("-eval"); + dsent_args->push_back(eval_str); + } + + // Begin overwrites + dsent_args->push_back("-overwrite"); + + // Add electrical technology model filename + overwrites_str = "ElectricalTechModelFilename=" + get_elec_tech_file_path() + ";"; + overwrites_str += " PhotonicTechModelFilename=" + get_phot_tech_file_path() + ";"; + // Add other overwrites + for (vector::const_iterator it = overwrites_.begin(); it != overwrites_.end(); it++) + overwrites_str += " " + it->get_string() + ";" ; + + // Append full overwrites string + dsent_args->push_back(overwrites_str); + + // Begin tech overwrites + dsent_args->push_back("-overwrite_tech"); + + // Add global tech overwrites + for (vector::const_iterator it = m_overwrites_tech_->begin(); it != m_overwrites_tech_->end(); it++) + overwrites_tech_str += " " + it->get_string() + ";" ; + // Add local tech overwrites + for (vector::const_iterator it = overwrites_tech_.begin(); it != overwrites_tech_.end(); it++) + overwrites_tech_str += " " + it->get_string() + ";" ; + + // Append full tech overwrites string + dsent_args->push_back(overwrites_tech_str); + + // Convert arguments vector to char** + char** dsent_args_raw = new char*[dsent_args->size()]; + for (unsigned int i = 0; i < dsent_args->size(); i++) + { + // Probably should check this is doing the right things + dsent_args_raw[i] = new char[dsent_args->at(i).size()+1]; + strcpy(dsent_args_raw[i], dsent_args->at(i).c_str()); + } + + // Run DSENT + DSENT::DSENT::run(int(dsent_args->size()), dsent_args_raw, dsent_ost); + + // Get DSENT output into a String + dsent_out_string = dsent_ost.str(); + + // Delete stuff + for (unsigned int i = 0; i < dsent_args->size(); i++) + delete dsent_args_raw[i]; + delete dsent_args_raw; + delete dsent_args; + + // Return split line-by-line outputs + return dsent_out_string.split("\n"); + } +} diff --git a/pool/shard001/C++/0023774_browser_ppb_graphics_2d_rpc_server.cc b/pool/shard001/C++/0023774_browser_ppb_graphics_2d_rpc_server.cc new file mode 100644 index 0000000000000000000000000000000000000000..1e0b8252b0f2f7192832cbc0d45d869ece70ebd4 --- /dev/null +++ b/pool/shard001/C++/0023774_browser_ppb_graphics_2d_rpc_server.cc @@ -0,0 +1,180 @@ +// 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. +// +// SRPC-abstraction wrappers around PPB_Graphics2D functions. + +#include "native_client/src/include/portability.h" +#include "native_client/src/include/nacl_macros.h" +#include "native_client/src/shared/ppapi_proxy/browser_callback.h" +#include "native_client/src/shared/ppapi_proxy/browser_globals.h" +#include "native_client/src/shared/ppapi_proxy/utility.h" +#include "ppapi/c/pp_completion_callback.h" +#include "ppapi/c/pp_errors.h" +#include "ppapi/c/pp_point.h" +#include "ppapi/c/pp_rect.h" +#include "ppapi/c/pp_size.h" +#include "ppapi/c/ppb_graphics_2d.h" +#include "srpcgen/ppb_rpc.h" + +using ppapi_proxy::DebugPrintf; +using ppapi_proxy::PPBGraphics2DInterface; + +namespace { + +// Two functions below use a NULL PP_Rect pointer to indicate that the +// entire image should be updated. +const struct PP_Rect* kEntireImage = NULL; + +} // namespace + +void PpbGraphics2DRpcServer::PPB_Graphics2D_Create(NaClSrpcRpc* rpc, + NaClSrpcClosure* done, + PP_Instance instance, + nacl_abi_size_t size_bytes, + char* size, + int32_t is_always_opaque, + PP_Resource* resource) { + NaClSrpcClosureRunner runner(done); + rpc->result = NACL_SRPC_RESULT_APP_ERROR; + *resource = ppapi_proxy::kInvalidResourceId; + if (size_bytes != sizeof(struct PP_Size)) { + return; + } + *resource = PPBGraphics2DInterface()->Create( + instance, + const_cast( + reinterpret_cast(size)), + PP_FromBool(is_always_opaque)); + DebugPrintf("PPB_Graphics2D::Create: resource=%"NACL_PRId32"\n", *resource); + rpc->result = NACL_SRPC_RESULT_OK; +} + +void PpbGraphics2DRpcServer::PPB_Graphics2D_IsGraphics2D(NaClSrpcRpc* rpc, + NaClSrpcClosure* done, + PP_Resource resource, + int32_t* success) { + NaClSrpcClosureRunner runner(done); + rpc->result = NACL_SRPC_RESULT_APP_ERROR; + *success = 0; + PP_Bool pp_success = PPBGraphics2DInterface()->IsGraphics2D(resource); + *success = PP_ToBool(pp_success); + DebugPrintf("PPB_Graphics2D::IsGraphics2D: success=%d\n", *success); + rpc->result = NACL_SRPC_RESULT_OK; +} + +void PpbGraphics2DRpcServer::PPB_Graphics2D_Describe( + NaClSrpcRpc* rpc, + NaClSrpcClosure* done, + PP_Resource graphics_2d, + nacl_abi_size_t* size_bytes, + char* size, + int32_t* is_always_opaque, + int32_t* success) { + NaClSrpcClosureRunner runner(done); + rpc->result = NACL_SRPC_RESULT_APP_ERROR; + *success = 0; + if (*size_bytes != sizeof(struct PP_Size)) { + return; + } + PP_Bool is_opaque; + PP_Bool pp_success = PPBGraphics2DInterface()->Describe( + graphics_2d, reinterpret_cast(size), &is_opaque); + *is_always_opaque = PP_ToBool(is_opaque); + *success = PP_ToBool(pp_success); + DebugPrintf("PPB_Graphics2D::Describe: success=%d\n", *success); + rpc->result = NACL_SRPC_RESULT_OK; +} + +void PpbGraphics2DRpcServer::PPB_Graphics2D_PaintImageData( + NaClSrpcRpc* rpc, + NaClSrpcClosure* done, + PP_Resource graphics_2d, + PP_Resource image, + nacl_abi_size_t top_left_bytes, + char* top_left, + nacl_abi_size_t src_rect_bytes, + char* src_rect) { + NaClSrpcClosureRunner runner(done); + rpc->result = NACL_SRPC_RESULT_APP_ERROR; + if (top_left_bytes != sizeof(struct PP_Point)) { // NULL top_left is invalid. + return; + } + const struct PP_Rect* rect = kEntireImage; + if (src_rect_bytes == sizeof(struct PP_Rect)) { + rect = const_cast( + reinterpret_cast(src_rect)); + } else if (src_rect_bytes != 0) { + return; + } + PPBGraphics2DInterface()->PaintImageData( + graphics_2d, + image, + const_cast( + reinterpret_cast(top_left)), + rect); + DebugPrintf("PPB_Graphics2D::PaintImageData\n"); + rpc->result = NACL_SRPC_RESULT_OK; +} + +void PpbGraphics2DRpcServer::PPB_Graphics2D_Scroll( + NaClSrpcRpc* rpc, + NaClSrpcClosure* done, + PP_Resource graphics_2d, + nacl_abi_size_t clip_rect_bytes, + char* clip_rect, + nacl_abi_size_t amount_bytes, + char* amount) { + NaClSrpcClosureRunner runner(done); + rpc->result = NACL_SRPC_RESULT_APP_ERROR; + if (amount_bytes != sizeof(struct PP_Point)) { // NULL amount is invalid. + return; + } + const struct PP_Rect* rect = kEntireImage; + if (clip_rect_bytes == sizeof(struct PP_Rect)) { + rect = const_cast( + reinterpret_cast(clip_rect)); + } else if (clip_rect_bytes != 0) { + return; + } + PPBGraphics2DInterface()->Scroll( + graphics_2d, + rect, + const_cast( + reinterpret_cast(amount))); + DebugPrintf("PPB_Graphics2D::Scroll\n"); + rpc->result = NACL_SRPC_RESULT_OK; +} + +void PpbGraphics2DRpcServer::PPB_Graphics2D_ReplaceContents( + NaClSrpcRpc* rpc, + NaClSrpcClosure* done, + PP_Resource graphics_2d, + PP_Resource image) { + NaClSrpcClosureRunner runner(done); + rpc->result = NACL_SRPC_RESULT_APP_ERROR; + PPBGraphics2DInterface()->ReplaceContents(graphics_2d, image); + DebugPrintf("PPB_Graphics2D::ReplaceContents\n"); + rpc->result = NACL_SRPC_RESULT_OK; +} + +void PpbGraphics2DRpcServer::PPB_Graphics2D_Flush( + NaClSrpcRpc* rpc, + NaClSrpcClosure* done, + PP_Resource graphics_2d, + int32_t callback_id, + int32_t* pp_error) { + NaClSrpcClosureRunner runner(done); + rpc->result = NACL_SRPC_RESULT_APP_ERROR; + + PP_CompletionCallback remote_callback = + ppapi_proxy::MakeRemoteCompletionCallback(rpc->channel, callback_id); + if (remote_callback.func == NULL) + return; // Treat this as a generic SRPC error. + + *pp_error = PPBGraphics2DInterface()->Flush(graphics_2d, remote_callback); + if (*pp_error != PP_OK_COMPLETIONPENDING) // Async error. + ppapi_proxy::DeleteRemoteCallbackInfo(remote_callback); + DebugPrintf("PPB_Graphics2D::Flush: pp_error=%"NACL_PRId32"\n", *pp_error); + rpc->result = NACL_SRPC_RESULT_OK; +} diff --git a/pool/shard001/C++/0023778_scattributeitemdelegate.cpp b/pool/shard001/C++/0023778_scattributeitemdelegate.cpp new file mode 100644 index 0000000000000000000000000000000000000000..58edac0896bab581ccd3f042af86d9ad8a403e18 --- /dev/null +++ b/pool/shard001/C++/0023778_scattributeitemdelegate.cpp @@ -0,0 +1,107 @@ +/**************************************************************************** +** +** 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 "scattributeitemdelegate.h" +#include "mytypes.h" +#include +#include +#include + +using namespace ScxmlEditor::PluginInterface; + +SCAttributeItemDelegate::SCAttributeItemDelegate(QObject *parent) + : AttributeItemDelegate(parent) +{ +} + +QWidget *SCAttributeItemDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const +{ + Q_UNUSED(option) + + switch (index.data(DataTypeRole).toInt()) { + case QVariant::StringList: { + auto combo = new QComboBox(parent); + combo->setFocusPolicy(Qt::StrongFocus); + return combo; + } + case QVariant::String: { + if (index.column() == 0) { + auto edit = new QLineEdit(parent); + edit->setFocusPolicy(Qt::StrongFocus); + QRegularExpression rx("^(?!xml)[_a-z][a-z0-9-._]*$"); + rx.setPatternOptions(QRegularExpression::CaseInsensitiveOption); + + edit->setValidator(new QRegularExpressionValidator(rx, parent)); + return edit; + } + } + default: + break; + } + + return QStyledItemDelegate::createEditor(parent, option, index); +} + +void SCAttributeItemDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const +{ + QStyledItemDelegate::updateEditorGeometry(editor, option, index); + if (editor) + editor->setGeometry(option.rect); +} + +void SCAttributeItemDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const +{ + switch (index.data(DataTypeRole).toInt()) { + case QVariant::StringList: { + auto combo = qobject_cast(editor); + if (combo) { + combo->clear(); + QStringList values = index.data(DataRole).toString().split(";"); + + foreach (QString val, values) + combo->addItem(val); + + combo->setCurrentText(index.data().toString()); + return; + } + break; + } + default: + break; + } + + QStyledItemDelegate::setEditorData(editor, index); +} + +void SCAttributeItemDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const +{ + auto combo = qobject_cast(editor); + if (combo) { + model->setData(index, combo->currentText()); + return; + } + + QStyledItemDelegate::setModelData(editor, model, index); +} diff --git a/pool/shard001/C++/0023779_main.cc b/pool/shard001/C++/0023779_main.cc new file mode 100644 index 0000000000000000000000000000000000000000..9b6b3df147670ce8fa85f8a5f20faf43f476386a --- /dev/null +++ b/pool/shard001/C++/0023779_main.cc @@ -0,0 +1,30 @@ +// Copyright 2013-2016 Stanford University +// +// 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 + +extern int32_t p20(int32_t x); + +int main(int argc, char** argv) { + const auto itr = argc > 1 ? atoi(argv[1]) : 1024; + const auto seed = argc > 2 ? atoi(argv[2]) : 0; + + srand(seed); + for (auto i = 0; i < itr; ++i) { + p20(rand()); + } + + return 0; +} diff --git a/pool/shard001/C++/0023781_cloth_recorder.cpp b/pool/shard001/C++/0023781_cloth_recorder.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8cb9b030af8fa865cd35f343b7010cc302e26e29 --- /dev/null +++ b/pool/shard001/C++/0023781_cloth_recorder.cpp @@ -0,0 +1,108 @@ +// Cloth recorder code to record various ros topics +// Depends on using rosbag api +// Author: Nishanth Koganti +// Date: 2015/7/26 + +// general headers +#include + +// ros headers +#include +#include +#include +#include + +// program variables +int count = 0; +int limit = 100; + +class ClothRecorder +{ + private: + // variable for the rosbag + rosbag::Bag bag; + + // rosnode handle parameter + ros::NodeHandle n; + + // sensor message where the message will be stored + sensor_msgs::PointCloud2Ptr x; + + // extracted point cloud subscriber + ros::Subscriber clothCloudSub; + + // rosbag fileName + std::string fileName; + + // public class functions + public: + // class constructor + ClothRecorder(ros::NodeHandle* n, std::string fileName) + { + // obtain ros node handle + this->n = *n; + + // obtain the root file name for the ros handle + this->fileName = fileName; + + // open a new bag file + bag.open(this->fileName, rosbag::bagmode::Write); + + // subscribe to the required ros topics + this->clothCloudSub = this->n.subscribe("/cloth/points", 1, &ClothRecorder::record, this); + } + + // destructor function + ~ClothRecorder() + { + + } + + // callback function for the subscriber + void record(const sensor_msgs::PointCloud2Ptr& msg) + { + // print out the count + std::cout << count << std::endl; + + // write point cloud message to the ros bag file + if(count < limit) + { + bag.write("/cloth/points", ros::Time::now(), *msg); + count++; + } + else + { + bag.close(); + clothCloudSub.shutdown(); + std::cout << "Saving ROS Bag" << std::endl; + } + } +}; + +int main(int argc, char *argv[]) +{ + // initializing ros node + ros::init(argc, argv, "ClothRecorder"); + + // create ros node handle + ros::NodeHandle n; + + // string name for the rosbag + std::string bagName; + + // start the ClothRecorder class instance + if (argc > 1) + { + bagName = argv[1]; + ClothRecorder recorder(&n,bagName); + ros::spin(); + } + else + { + std::cout << "Usage: run program with fileName as input argument" << std::endl; + } + + // clean ros shutdown + ros::shutdown(); + return 0; +} diff --git a/pool/shard001/C++/0023783_SystemBase.cc b/pool/shard001/C++/0023783_SystemBase.cc new file mode 100644 index 0000000000000000000000000000000000000000..4edb3fd240961e3416031b2b1b5181d3d26ca0c5 --- /dev/null +++ b/pool/shard001/C++/0023783_SystemBase.cc @@ -0,0 +1,248 @@ +/************************************************************************* + * + * + * Copyright 2014 Adam Harmat (McGill University) + * [adam.harmat@mail.mcgill.ca] + * Michael Tribou (University of Waterloo) + * [mjtribou@uwaterloo.ca] + * + * Multi-Camera Parallel Tracking and Mapping (MCPTAM) 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 . + * + * MCPTAM is based on the Parallel Tracking and Mapping (PTAM) software. + * Copyright 2008 Isis Innovation Limited + * + * + ************************************************************************/ + + +//========================================================================================= +// +// Copyright 2012 Adam Harmat, McGill University +// adam.harmat@mail.mcgill.ca +// +// Parts of this code are from the original PTAM, which are +// Copyright 2008 Isis Innovation Limited +// +//========================================================================================= + +#include +#include +#include +#include +#include +#include +#include + +using namespace TooN; + +//bool SystemBase::sbLevelZeroPoints = false; + +SystemBase::SystemBase(std::string windowName, bool bFullSize, bool bDrawWindow) +: mNodeHandlePriv("~") +, mpVideoSourceMulti(InitVideoSource()) +, mpGLWindow((bDrawWindow ? InitWindow(windowName,bFullSize) : NULL)) +{ + mNodeHandle.setCallbackQueue(&mCallbackQueueROS); + mNodeHandlePriv.setCallbackQueue(&mCallbackQueueROS); + + ImageRefMap mImageSizes = mpVideoSourceMulti->GetSizes(); + ImageRefMap mFullScaleSizes = mpVideoSourceMulti->GetFullScaleSizes(); + ImageRefMap mCalibSizes = mpVideoSourceMulti->GetCalibSizes(); + ParamMap mParams = mpVideoSourceMulti->GetParams(); + + mmDrawOffsets = mpVideoSourceMulti->GetDrawOffsets(); + mmPoses = mpVideoSourceMulti->GetPoses(); + + std::string cameraPoseFile; + if(mNodeHandlePriv.getParam("camera_pose_file", cameraPoseFile)) + { + std::ifstream poseStream(cameraPoseFile.c_str()); + while ( poseStream.good() ) + { + std::string camName; + TooN::SE3<> se3Pose; + + poseStream>>camName; + poseStream>>se3Pose; + + se3Pose = se3Pose.inverse(); + + if(!mmPoses.count(camName)) + ROS_WARN_STREAM("Got camera name "<second.get_translation() *= dExtrinsicScale; + } + } + + // Create camera models here + for(ImageRefMap::iterator it = mImageSizes.begin(); it != mImageSizes.end(); it++) + { + std::string camName = it->first; + + CVD::ImageRef& irImageSize = mImageSizes[camName]; + CVD::ImageRef& irFullScaleSize = mFullScaleSizes[camName]; + CVD::ImageRef& irCalibSize = mCalibSizes[camName]; + Vector<9>& v9Params = mParams[camName]; + + mmCameraModels.insert(std::pair(camName, TaylorCamera(v9Params, irCalibSize, irFullScaleSize, irImageSize))); + } + + mpMap = new Map; +} + +SystemBase::~SystemBase() +{ + if(mpGLWindow) // window might not have been created if running client in headless mode + delete mpGLWindow; + + if(mpVideoSourceMulti) // video source might have been shut down already (ie in server) + delete mpVideoSourceMulti; + + delete mpMap; +} + +// Calculates the average of the durations contained in the argument +double SystemBase::AverageDuration(std::deque& queue) +{ + ros::Duration durSum(0); + for(unsigned i=0; i < queue.size(); ++i) + { + durSum += queue[i]; + } + + double dAvg = durSum.toSec() / queue.size(); + return dAvg; +} + +// This can be used with GUI.RegisterCommand to capture user input +void SystemBase::GUICommandCallBack(void *ptr, std::string command, std::string params) +{ + Command c; + c.command = command; + c.params = params; + static_cast(ptr)->mqCommands.push(c); +} + +// Creates a new GLWindow2 object +GLWindow2* SystemBase::InitWindow(std::string windowName, bool bFullSize) +{ + return new GLWindow2(mpVideoSourceMulti->GetTotalSize(bFullSize), windowName); +} + +// Creates a new VideoSourceMulti object +VideoSourceMulti* SystemBase::InitVideoSource() +{ + bool bGetPoseSeparately = false; + mNodeHandlePriv.getParam("get_pose_separately", bGetPoseSeparately); + + return new VideoSourceMulti(bGetPoseSeparately); +} + +// Write the camera parameters to the given file name +void SystemBase::DumpCamerasToFile(std::string filename) +{ + std::ofstream ofs(filename.c_str()); + + if(!ofs.good()) + { + ROS_ERROR_STREAM("Couldn't open "<first; + TaylorCamera& camera = cam_it->second; + + CVD::ImageRef irImageSize = camera.GetImageSize(); + TooN::Vector<9> v9Params = camera.GetParams(); + TooN::Vector vxInvPoly = camera.GetInvPoly(); + + // The parameters (by index) are: + // 0 - a0 coefficient + // 1 - a2 coefficient + // 2 - a3 coefficient + // 3 - a4 coefficient + // 4 - center of projection xc + // 5 - center of projection yc + // 6 - affine transform param c + // 7 - affine transform param d + // 8 - affine transform param e + + ofs<second); + ROS_INFO_STREAM("Loading "<first] = CVD::img_load(ss.str()); + } + } + + return masksMap; +} diff --git a/pool/shard001/C++/0023794_OverrideView.cpp b/pool/shard001/C++/0023794_OverrideView.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b95b9681ed8731c0aed18cddd8c639ddfc650fdd --- /dev/null +++ b/pool/shard001/C++/0023794_OverrideView.cpp @@ -0,0 +1,107 @@ +/* + Created by Jenny White on 29.04.18. + Copyright (c) 2018 nullworks. All rights reserved. +*/ + +#include +#include +#include "HookedMethods.hpp" + +static settings::Float override_fov{ "visual.fov", "0" }; +static settings::Float freecam_speed{ "visual.freecam-speed", "800.0f" }; +static settings::Button freecam{ "visual.freecam-button", "" }; +bool freecam_is_toggled{ false }; + +namespace hooked_methods +{ + +DEFINE_HOOKED_METHOD(OverrideView, void, void *this_, CViewSetup *setup) +{ + original::OverrideView(this_, setup); + + if (!isHackActive() || g_Settings.bInvalid || CE_BAD(LOCAL_E)) + return; + + bool zoomed = setup->fov < CE_INT(LOCAL_E, netvar.iDefaultFOV) || g_pLocalPlayer->bZoomed; + if (*no_zoom && zoomed) + { + auto fov = g_ICvar->FindVar("fov_desired"); + setup->fov = override_fov ? *override_fov : fov->GetInt(); + } + else if (override_fov && !zoomed) + { + setup->fov = *override_fov; + } + + if (spectator_target) + { + CachedEntity *spec = ENTITY(spectator_target); + if (CE_GOOD(spec) && !CE_BYTE(spec, netvar.iLifeState)) + { + setup->origin = spec->m_vecOrigin() + CE_VECTOR(spec, netvar.vViewOffset); + // why not spectate yourself + if (spec == LOCAL_E) + { + setup->angles = CE_VAR(spec, netvar.m_angEyeAnglesLocal, QAngle); + } + else + { + setup->angles = CE_VAR(spec, netvar.m_angEyeAngles, QAngle); + } + } + if (g_IInputSystem->IsButtonDown(ButtonCode_t::KEY_SPACE)) + { + spectator_target = 0; + } + } + + if (freecam && current_user_cmd) + { + static Vector freecam_origin{ 0 }; + static bool freecam_last{ false }; + static bool first_toggle{ true }; + + if (freecam.isKeyDown() && !freecam_last) + { + freecam_is_toggled = !freecam_is_toggled; + first_toggle = true; + } + if (freecam_is_toggled) + { + if (first_toggle) + { + freecam_origin = setup->origin; + first_toggle = false; + } + QAngle ang; + Vector angle; + + float speed = *freecam_speed * g_GlobalVars->absoluteframetime; + g_IEngine->GetViewAngles(ang); + angle = QAngleToVector(ang); + if (stored_buttons & IN_FORWARD) + freecam_origin += GetForwardVector({ 0.0f, 0.0f, 0.0f }, angle, speed); + if (stored_buttons & IN_BACK) + freecam_origin -= GetForwardVector({ 0.0f, 0.0f, 0.0f }, angle, speed); + if (stored_buttons & IN_MOVELEFT || stored_buttons & IN_MOVERIGHT) + { + Vector new_angle = angle; + new_angle.y += 90.0f; + new_angle.x = 0.0f; + fClampAngle(new_angle); + Vector touse = GetForwardVector({ 0.0f, 0.0f, 0.0f }, new_angle, speed); + if (stored_buttons & IN_MOVELEFT) + freecam_origin += touse; + if (stored_buttons & IN_MOVERIGHT) + freecam_origin -= touse; + } + setup->origin = freecam_origin; + } + freecam_last = freecam.isKeyDown(); + } + else if (current_user_cmd) + freecam_is_toggled = false; + + draw::fov = setup->fov; +} +} // namespace hooked_methods diff --git a/pool/shard001/C++/0023798_baz_vector_ruby.cpp b/pool/shard001/C++/0023798_baz_vector_ruby.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8742ebb458c76867ed8b31fe5080b653376a0313 --- /dev/null +++ b/pool/shard001/C++/0023798_baz_vector_ruby.cpp @@ -0,0 +1,97 @@ +// ext/baz/baz_vector_ruby.cpp + +/////////////////////////////////////////////////////////////////////////////// +// +// Definitions for Ruby wrappers to BVector class +// +/////////////////////////////////////////////////////////////////////////////// + +#include "baz_vector_ruby.h" + +/////////////////////////////////////////////////////////////////////////////// +// +// Memory management. TODO: Check best practice for this. +// + +BVector *rb_create_bvector() { + return new BVector(); +} + +void rb_delete_bvector( BVector *p_bvector ) { + delete p_bvector; + return; +} + +/////////////////////////////////////////////////////////////////////////////// +// +// Low-level Ruby integration +// + +VALUE BazVector = Qnil; + +inline VALUE bvector_as_ruby_class( BVector *p_bvector , VALUE klass ) { + return Data_Wrap_Struct( klass, 0, rb_delete_bvector, p_bvector ); +} + +VALUE bv_alloc(VALUE klass) { + return bvector_as_ruby_class( rb_create_bvector(), klass ); +} + +inline BVector *get_bvector( VALUE obj ) { + BVector *p_bvector; + Data_Get_Struct( obj, BVector, p_bvector ); + return p_bvector; +} + +void assert_value_wraps_bvector( VALUE obj ) { + if ( TYPE(obj) != T_DATA || + RDATA(obj)->dfree != (RUBY_DATA_FUNC)rb_delete_bvector) { + rb_raise( rb_eTypeError, "Expected a Baz::Vector object, but got something else" ); + } +} + +/////////////////////////////////////////////////////////////////////////////// +// +// Ruby methods exposed in the class API +// + +// Native extensions version of initialize +VALUE baz_vector_initialize( VALUE self, VALUE init_x, VALUE init_y ) { + BVector *p_bvector = get_bvector( self ); + + p_bvector->set_xy( NUM2DBL( init_x ), NUM2DBL( init_y ) ); + + return self; +} + +// Native extensions version of clone +VALUE baz_vector_initialize_copy( VALUE copy, VALUE orig ) { + BVector *bv_copy; + BVector *bv_orig; + + if (copy == orig) return copy; + bv_copy = get_bvector( copy ); + bv_orig = get_bvector( orig ); + memcpy( bv_copy, bv_orig, sizeof(BVector) ); + + return copy; +} + +// Example of using a "native" struct method +VALUE baz_vector_magnitude( VALUE self ) { + BVector *p_bvector = get_bvector( self ); + return DBL2NUM( p_bvector->magnitude() ); +} + +/////////////////////////////////////////////////////////////////////////////// +// +// Build Ruby class ::Vector +// + +void init_baz_vector( VALUE parent_module ) { + BazVector = rb_define_class_under( parent_module, "Vector", rb_cObject ); + rb_define_alloc_func( BazVector, bv_alloc ); + rb_define_method( BazVector, "initialize", (VALUE(*)(ANYARGS))baz_vector_initialize, 2 ); + rb_define_method( BazVector, "initialize_copy", (VALUE(*)(ANYARGS))baz_vector_initialize_copy, 1 ); + rb_define_method( BazVector, "magnitude", (VALUE(*)(ANYARGS))baz_vector_magnitude, 0 ); +} diff --git a/pool/shard001/C++/0023802_signalthread_unittest.cc b/pool/shard001/C++/0023802_signalthread_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..fe6c6023a65841eeb6205935df238d724ed1bb21 --- /dev/null +++ b/pool/shard001/C++/0023802_signalthread_unittest.cc @@ -0,0 +1,199 @@ +/* + * Copyright 2004 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/base/gunit.h" +#include "webrtc/base/signalthread.h" +#include "webrtc/base/thread.h" +#include "webrtc/test/testsupport/gtest_disable.h" + +using namespace rtc; + +class SignalThreadTest : public testing::Test, public sigslot::has_slots<> { + public: + class SlowSignalThread : public SignalThread { + public: + SlowSignalThread(SignalThreadTest* harness) : harness_(harness) { + } + + virtual ~SlowSignalThread() { + EXPECT_EQ(harness_->main_thread_, Thread::Current()); + ++harness_->thread_deleted_; + } + + const SignalThreadTest* harness() { return harness_; } + + protected: + virtual void OnWorkStart() { + ASSERT_TRUE(harness_ != NULL); + ++harness_->thread_started_; + EXPECT_EQ(harness_->main_thread_, Thread::Current()); + EXPECT_FALSE(worker()->RunningForTest()); // not started yet + } + + virtual void OnWorkStop() { + ++harness_->thread_stopped_; + EXPECT_EQ(harness_->main_thread_, Thread::Current()); + EXPECT_TRUE(worker()->RunningForTest()); // not stopped yet + } + + virtual void OnWorkDone() { + ++harness_->thread_done_; + EXPECT_EQ(harness_->main_thread_, Thread::Current()); + EXPECT_TRUE(worker()->RunningForTest()); // not stopped yet + } + + virtual void DoWork() { + EXPECT_NE(harness_->main_thread_, Thread::Current()); + EXPECT_EQ(worker(), Thread::Current()); + Thread::Current()->socketserver()->Wait(250, false); + } + + private: + SignalThreadTest* harness_; + RTC_DISALLOW_COPY_AND_ASSIGN(SlowSignalThread); + }; + + void OnWorkComplete(rtc::SignalThread* thread) { + SlowSignalThread* t = static_cast(thread); + EXPECT_EQ(t->harness(), this); + EXPECT_EQ(main_thread_, Thread::Current()); + + ++thread_completed_; + if (!called_release_) { + thread->Release(); + } + } + + virtual void SetUp() { + main_thread_ = Thread::Current(); + thread_ = new SlowSignalThread(this); + thread_->SignalWorkDone.connect(this, &SignalThreadTest::OnWorkComplete); + called_release_ = false; + thread_started_ = 0; + thread_done_ = 0; + thread_completed_ = 0; + thread_stopped_ = 0; + thread_deleted_ = 0; + } + + virtual void TearDown() { + } + + Thread* main_thread_; + SlowSignalThread* thread_; + bool called_release_; + + int thread_started_; + int thread_done_; + int thread_completed_; + int thread_stopped_; + int thread_deleted_; +}; + +class OwnerThread : public Thread, public sigslot::has_slots<> { + public: + explicit OwnerThread(SignalThreadTest* harness) + : harness_(harness), + has_run_(false) { + } + + virtual ~OwnerThread() { + Stop(); + } + + virtual void Run() { + SignalThreadTest::SlowSignalThread* signal_thread = + new SignalThreadTest::SlowSignalThread(harness_); + signal_thread->SignalWorkDone.connect(this, &OwnerThread::OnWorkDone); + signal_thread->Start(); + Thread::Current()->socketserver()->Wait(100, false); + signal_thread->Release(); + // Delete |signal_thread|. + signal_thread->Destroy(true); + has_run_ = true; + } + + bool has_run() { return has_run_; } + void OnWorkDone(SignalThread* signal_thread) { + FAIL() << " This shouldn't get called."; + } + + private: + SignalThreadTest* harness_; + bool has_run_; + RTC_DISALLOW_COPY_AND_ASSIGN(OwnerThread); +}; + +// Test for when the main thread goes away while the +// signal thread is still working. This may happen +// when shutting down the process. +TEST_F(SignalThreadTest, OwnerThreadGoesAway) { + { + scoped_ptr owner(new OwnerThread(this)); + main_thread_ = owner.get(); + owner->Start(); + while (!owner->has_run()) { + Thread::Current()->socketserver()->Wait(10, false); + } + } + // At this point the main thread has gone away. + // Give the SignalThread a little time to do its callback, + // which will crash if the signal thread doesn't handle + // this situation well. + Thread::Current()->socketserver()->Wait(500, false); +} + +#define EXPECT_STATE(started, done, completed, stopped, deleted) \ + EXPECT_EQ(started, thread_started_); \ + EXPECT_EQ(done, thread_done_); \ + EXPECT_EQ(completed, thread_completed_); \ + EXPECT_EQ(stopped, thread_stopped_); \ + EXPECT_EQ(deleted, thread_deleted_); + +TEST_F(SignalThreadTest, ThreadFinishes) { + thread_->Start(); + EXPECT_STATE(1, 0, 0, 0, 0); + Thread::SleepMs(500); + EXPECT_STATE(1, 0, 0, 0, 0); + Thread::Current()->ProcessMessages(0); + EXPECT_STATE(1, 1, 1, 0, 1); +} + +TEST_F(SignalThreadTest, ReleasedThreadFinishes) { + thread_->Start(); + EXPECT_STATE(1, 0, 0, 0, 0); + thread_->Release(); + called_release_ = true; + EXPECT_STATE(1, 0, 0, 0, 0); + Thread::SleepMs(500); + EXPECT_STATE(1, 0, 0, 0, 0); + Thread::Current()->ProcessMessages(0); + EXPECT_STATE(1, 1, 1, 0, 1); +} + +TEST_F(SignalThreadTest, DestroyedThreadCleansUp) { + thread_->Start(); + EXPECT_STATE(1, 0, 0, 0, 0); + thread_->Destroy(true); + EXPECT_STATE(1, 0, 0, 1, 1); + Thread::Current()->ProcessMessages(0); + EXPECT_STATE(1, 0, 0, 1, 1); +} + +TEST_F(SignalThreadTest, DeferredDestroyedThreadCleansUp) { + thread_->Start(); + EXPECT_STATE(1, 0, 0, 0, 0); + thread_->Destroy(false); + EXPECT_STATE(1, 0, 0, 1, 0); + Thread::SleepMs(500); + EXPECT_STATE(1, 0, 0, 1, 0); + Thread::Current()->ProcessMessages(0); + EXPECT_STATE(1, 1, 0, 1, 1); +} diff --git a/pool/shard001/C++/0023815_ISubDDrw.cpp b/pool/shard001/C++/0023815_ISubDDrw.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5859fb38108c262787871f59cfc4b72f8ac381aa --- /dev/null +++ b/pool/shard001/C++/0023815_ISubDDrw.cpp @@ -0,0 +1,156 @@ +//-***************************************************************************** +// +// Copyright (c) 2009-2012, +// Sony Pictures Imageworks, Inc. and +// Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. +// +// 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 Sony Pictures Imageworks, nor +// Industrial Light & Magic nor the names of their 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 "ISubDDrw.h" + +namespace AbcOpenGL { +namespace ABCOPENGL_VERSION_NS { + +//-***************************************************************************** +ISubDDrw::ISubDDrw( ISubD &iPmesh ) + : IObjectDrw( iPmesh, false ) + , m_subD( iPmesh ) +{ + // Get out if problems. + if ( !m_subD.valid() ) + { + return; + } + + if ( m_subD.getSchema().getNumSamples() > 0 ) + { + m_subD.getSchema().get( m_samp ); + } + + m_boundsProp = m_subD.getSchema().getSelfBoundsProperty(); + + // The object has already set up the min time and max time of + // all the children. + // if we have a non-constant time sampling, we should get times + // out of it. + TimeSamplingPtr iTsmp = m_subD.getSchema().getTimeSampling(); + if ( !m_subD.getSchema().isConstant() ) + { + size_t numSamps = m_subD.getSchema().getNumSamples(); + if ( numSamps > 0 ) + { + chrono_t minTime = iTsmp->getSampleTime( 0 ); + m_minTime = std::min( m_minTime, minTime ); + chrono_t maxTime = iTsmp->getSampleTime( numSamps-1 ); + m_maxTime = std::max( m_maxTime, maxTime ); + } + } +} + +//-***************************************************************************** +ISubDDrw::~ISubDDrw() +{ + // Nothing! +} + +//-***************************************************************************** +bool ISubDDrw::valid() +{ + return IObjectDrw::valid() && m_subD.valid(); +} + +//-***************************************************************************** +void ISubDDrw::setTime( chrono_t iSeconds ) +{ + IObjectDrw::setTime( iSeconds ); + if ( !valid() ) + { + m_drwHelper.makeInvalid(); + return; + } + + // Use nearest for now. + ISampleSelector ss( iSeconds, ISampleSelector::kNearIndex ); + ISubDSchema::Sample psamp; + + if ( m_subD.getSchema().isConstant() ) + { + psamp = m_samp; + } + else if ( m_subD.getSchema().getNumSamples() > 0 ) + { + m_subD.getSchema().get( psamp, ss ); + } + + // Get the stuff. + P3fArraySamplePtr P = psamp.getPositions(); + Int32ArraySamplePtr indices = psamp.getFaceIndices(); + Int32ArraySamplePtr counts = psamp.getFaceCounts(); + + Box3d bounds; + bounds.makeEmpty(); + + if ( m_boundsProp && m_boundsProp.getNumSamples() > 0 ) + { bounds = m_boundsProp.getValue( ss ); } + + // Update the mesh hoo-ha. + m_drwHelper.update( P, V3fArraySamplePtr(), + indices, counts, bounds ); + + if ( !m_drwHelper.valid() ) + { + m_subD.reset(); + return; + } + + // The Object update computed child bounds. + // Extend them by this. + if ( !m_drwHelper.getBounds().isEmpty() ) + { + m_bounds.extendBy( m_drwHelper.getBounds() ); + } +} + +//-***************************************************************************** +void ISubDDrw::draw( const DrawContext &iCtx ) +{ + if ( !valid() ) + { + return; + } + + m_drwHelper.draw( iCtx ); + + IObjectDrw::draw( iCtx ); +} + +} // End namespace ABCOPENGL_VERSION_NS +} // End namespace AbcOpenGL diff --git a/pool/shard001/C++/0023820_horizontal-bracket-engraver.cc b/pool/shard001/C++/0023820_horizontal-bracket-engraver.cc new file mode 100644 index 0000000000000000000000000000000000000000..941f78a172932d57bed20c23a1ced52b958d336d --- /dev/null +++ b/pool/shard001/C++/0023820_horizontal-bracket-engraver.cc @@ -0,0 +1,126 @@ +/* + This file is part of LilyPond, the GNU music typesetter. + + Copyright (C) 2002--2012 Han-Wen Nienhuys + + LilyPond 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. + + LilyPond 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 LilyPond. If not, see . +*/ + +#include "engraver.hh" +#include "international.hh" +#include "item.hh" +#include "note-column.hh" +#include "pointer-group-interface.hh" +#include "side-position-interface.hh" +#include "spanner.hh" +#include "stream-event.hh" + +#include "translator.icc" + +class Horizontal_bracket_engraver : public Engraver +{ +public: + TRANSLATOR_DECLARATIONS (Horizontal_bracket_engraver); + vector bracket_stack_; + vector events_; + vsize pop_count_; + vsize push_count_; + + void stop_translation_timestep (); + void process_music (); + DECLARE_ACKNOWLEDGER (note_column); + DECLARE_TRANSLATOR_LISTENER (note_grouping); +}; + +Horizontal_bracket_engraver::Horizontal_bracket_engraver () +{ + pop_count_ = 0; + push_count_ = 0; +} + +IMPLEMENT_TRANSLATOR_LISTENER (Horizontal_bracket_engraver, note_grouping); +void +Horizontal_bracket_engraver::listen_note_grouping (Stream_event *ev) +{ + Direction d = to_dir (ev->get_property ("span-direction")); + + if (d == STOP) + { + pop_count_++; + if (pop_count_ > bracket_stack_.size ()) + ev->origin ()->warning (_ ("do not have that many brackets")); + } + else + { + push_count_++; + events_.push_back (ev); + } + + if (pop_count_ && push_count_) + ev->origin ()->warning (_ ("conflicting note group events")); +} + +void +Horizontal_bracket_engraver::acknowledge_note_column (Grob_info gi) +{ + for (vsize i = 0; i < bracket_stack_.size (); i++) + { + Side_position_interface::add_support (bracket_stack_[i], gi.grob ()); + Pointer_group_interface::add_grob (bracket_stack_[i], + ly_symbol2scm ("columns"), gi.grob ()); + add_bound_item (bracket_stack_[i], + gi.grob ()); + } +} + +void +Horizontal_bracket_engraver::process_music () +{ + for (vsize k = 0; k < push_count_; k++) + { + Spanner *sp = make_spanner ("HorizontalBracket", events_[k]->self_scm ()); + + for (vsize i = 0; i < bracket_stack_.size (); i++) + /* sp is the smallest, it should be added to the bigger brackets. */ + Side_position_interface::add_support (bracket_stack_[i], sp); + bracket_stack_.push_back (sp); + } +} + +void +Horizontal_bracket_engraver::stop_translation_timestep () +{ + for (vsize i = pop_count_; i--;) + if (bracket_stack_.size ()) + bracket_stack_.pop_back (); + pop_count_ = 0; + push_count_ = 0; + events_.clear (); +} + +ADD_ACKNOWLEDGER (Horizontal_bracket_engraver, note_column); +ADD_TRANSLATOR (Horizontal_bracket_engraver, + /* doc */ + "Create horizontal brackets over notes for musical analysis" + " purposes.", + + /* create */ + "HorizontalBracket ", + + /* read */ + "", + + /* write */ + "" + ); diff --git a/pool/shard001/C++/0023821_ImageAttrHandlerHDF5.cc b/pool/shard001/C++/0023821_ImageAttrHandlerHDF5.cc new file mode 100644 index 0000000000000000000000000000000000000000..a88c809082f8c72e26db208296a941563c7bed42 --- /dev/null +++ b/pool/shard001/C++/0023821_ImageAttrHandlerHDF5.cc @@ -0,0 +1,134 @@ +//# ImageAttrHandlerHDF5.cc: Attributes handler for HDF5 images +//# Copyright (C) 2012 +//# Associated Universities, Inc. Washington DC, USA. +//# +//# 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; if not, write to the Free Software Foundation, +//# Inc., 675 Massachusetts Ave, Cambridge, MA 02139, USA. +//# +//# Correspondence concerning AIPS++ should be addressed as follows: +//# Internet email: aips2-request@nrao.edu. +//# Postal address: AIPS++ Project Office +//# National Radio Astronomy Observatory +//# 520 Edgemont Road +//# Charlottesville, VA 22903-2475 USA +//# +//# $Id$ + +//# Includes +#include +#include +#include +#include +#include + +using namespace std; + +namespace casacore { + + ImageAttrHandlerHDF5::ImageAttrHandlerHDF5() + : itsCanWrite (False) + {} + + ImageAttrHandlerHDF5::~ImageAttrHandlerHDF5() + {} + + ImageAttrHandlerHDF5& ImageAttrHandlerHDF5::attachHid (const HDF5Object& hid, + Bool createHandler, + Bool isWritable) + { + itsGroupMap.clear(); + // If ATTRGROUPS is defined, get all groups in it. + if (HDF5Group::exists (hid, "ATTRGROUPS")) { + itsGroup = CountedPtr(new HDF5Group(hid, "ATTRGROUPS", true)); + vector names = HDF5Group::linkNames (*itsGroup); + for (uInt i=0; i(new HDF5Group(hid, "ATTRGROUPS", false)); + itsCanWrite = True; + } + return *this; + } + + void ImageAttrHandlerHDF5::flush() + { + for (map::iterator it=itsGroupMap.begin(); + it!=itsGroupMap.end(); ++it) { + it->second.flush (*itsGroup, it->first); + } + } + + Bool ImageAttrHandlerHDF5::hasGroup (const String& groupName) + { + return (itsGroupMap.find(groupName) != itsGroupMap.end()); + } + + Vector ImageAttrHandlerHDF5::groupNames() const + { + Vector names(itsGroupMap.size()); + uInt i=0; + for (map::const_iterator it=itsGroupMap.begin(); + it!=itsGroupMap.end(); ++it) { + names[i++] = it->first; + } + return names; + } + + ImageAttrGroup& ImageAttrHandlerHDF5::openGroup (const String& groupName) + { + map::iterator pos = itsGroupMap.find (groupName); + if (pos == itsGroupMap.end()) { + throw AipsError("ImageAttrHandlerHDF5: group " + groupName + + " does not exist"); + } + if (pos->second.isNull()) { + // Read the group. + pos->second = ImageAttrGroupHDF5(*itsGroup, groupName, itsCanWrite); + } + return pos->second; + } + + ImageAttrGroup& ImageAttrHandlerHDF5::createGroup (const String& groupName) + { + if (hasGroup(groupName)) { + throw AipsError("ImageAttrHandlerHDF5: group " + groupName + + " cannot be created; it already exists"); + } + // Assert that a group can be created. + if (!itsCanWrite) { + throw AipsError("ImageAttrHandlerHDF5: cannot create group " + groupName + + " because image is not writable"); + } + return itsGroupMap[groupName] = ImageAttrGroupHDF5 (True); + } + + void ImageAttrHandlerHDF5::closeGroup (const String& groupName) + { + map::iterator pos = itsGroupMap.find (groupName); + if (pos != itsGroupMap.end()) { + pos->second.flush (*itsGroup, groupName); + pos->second = ImageAttrGroupHDF5(); + } + } + +} //# NAMESPACE CASACORE - END diff --git a/pool/shard001/C++/0023827_Registrymonitor.cpp b/pool/shard001/C++/0023827_Registrymonitor.cpp new file mode 100644 index 0000000000000000000000000000000000000000..42532b1d3bd4693c2d73fb04e4b1f9e17d3c2eb5 --- /dev/null +++ b/pool/shard001/C++/0023827_Registrymonitor.cpp @@ -0,0 +1,125 @@ +/* +Whitebox Proto-type + +Released as open source by NCC Group Plc - http://www.nccgroup.com/ + +Developed by Ollie Whitehouse, ollie dot whitehouse at nccgroup dot com + +http://www.github.com/nccgroup/whitebox + +Released under AGPL see LICENSE for more information + +(c) 2008 - 2013 Ollie Whitehouse +(c) 2013 NCC Group Plc +*/ + +#include "stdafx.h" +#include "drivers.h" +#include "utils.h" +#include "engine.h" +#include "configuration.h" + +char RStats[LOGBUFSIZE]; + +// +// Function : PrintOutput +// Role : Takes the buffer we recieve from the driver and prints it out nicley +// Notes : +// +void PrintOutputReg(DWORD dwLen){ + + PENTRY ptr; + + for ( ptr = (PENTRY)RStats; (char *)ptr < min(RStats+dwLen,RStats + sizeof (RStats)); ) { + // Add to list + size_t len = strlen(ptr->text); + + ReplaceTabs(ptr,dwLen); + wbprintf(0,"[regmon] %s \n",ptr->text); + addactivity("[regmon] %s \n",ptr->text); + + len += 4; len &= 0xFFFFFFFC; // +1 for null-terminator +3 for 32bit alignment + ptr = (PENTRY)(ptr->text + len); + } + +} + +// +// Function : RegMonitorThread +// Role : Communicates with the Sysinternal Regmon driver to minitor reg activity +// Notes : +// +DWORD WINAPI RegMonitorThread(LPVOID lpvParam){ + + RFILTER FilterDefinition; + DWORD dwFoo=0; + DWORD dwRLen=0; + DWORD dwCrapOla=0; + + + // Have driver turn on hooks + if (!DeviceIoControl(hgSysReg, IOCTL_REGMON_HOOK, + &dwCrapOla, 4, NULL, 0, &dwFoo, NULL ) ) { + wbprintf(1,"[!] Couldn't get RegMon driver to turn on hooks!\n"); + CloseHandle(hgSysReg); + ExitProcess(1); + } else { + if(bVerbose && intVerboseLvl >= 1) wbprintf(0,"[i] RegMon has turned on hooks\n"); + } + + // Set the filters + memset(&FilterDefinition,0x00,sizeof(FilterDefinition)); + + if(strlen(strRegiExcludeFilter)>0) { + if(bVerbose && intVerboseLvl>=5){ + wbprintf(0,"[i] Regmon Exclude : %s\n",strRegiExcludeFilter); + } + strcpy_s(FilterDefinition.excludefilter,1024,strRegiExcludeFilter); + } else strcpy_s(FilterDefinition.excludefilter,1024,"WHITEBOX.EXE"); + + if(strlen(strRegiIncludeFilter)>0) { + if(bVerbose && intVerboseLvl>=5){ + wbprintf(0,"[i] Regmon Include : %s\n",strRegiIncludeFilter); + } + strcpy_s(FilterDefinition.includefilter,1024,strRegiIncludeFilter); + } else strcpy_s(FilterDefinition.includefilter,1024,"*"); + + FilterDefinition.logaux=FALSE; + FilterDefinition.logerror=FALSE; + FilterDefinition.logreads=FALSE; + FilterDefinition.logsuccess=TRUE; + FilterDefinition.logwrites=TRUE; + if (!DeviceIoControl(hgSysReg,IOCTL_REGMON_SETFILTER, + (PVOID) &FilterDefinition, sizeof(FilterDefinition), + NULL, 0, &dwFoo, NULL ) ) { + wbprintf(1,"[!] Couldn't set Regmon filters\n"); + ExitProcess(1); + } else { + if(bVerbose && intVerboseLvl >= 5) wbprintf(0,"[i] Regmon filters set - %d - %d\n",dwFoo,sizeof(FilterDefinition)); + else if(bVerbose && intVerboseLvl >= 1) wbprintf(0,"[i] Regmon filters set\n"); + } + + wbprintf(0,"[*] Registry activity monitor active\n"); + + // Now loop + while(1){ + if(bDebug) wbprintf(0,"[debug] Checking regmon buffers\n"); + + // Have driver fill stats buffer + if (!DeviceIoControl(hgSysReg,IOCTL_REGMON_GETSTATS,NULL,0,&RStats,sizeof RStats,&dwRLen, NULL)) + { + ExitProcess(1); + } else { + if(dwRLen>0){ + if(bDebug) wbprintf(0,"[debug] Regmon got data - %d\n",dwRLen); + if(bDebug) PrintHex(0,(LPBYTE)RStats,dwRLen,0); + PrintOutputReg(dwRLen); + } + } + + // Have a little nap + Sleep(500); + } + + wbprintf(0,"[*] Registry activity monitor exiting\n"); +} \ No newline at end of file diff --git a/pool/shard001/C++/0023832_publisher.cpp b/pool/shard001/C++/0023832_publisher.cpp new file mode 100644 index 0000000000000000000000000000000000000000..68a85bf63a7f7611d4b1a514dfe61a2dc44d622d --- /dev/null +++ b/pool/shard001/C++/0023832_publisher.cpp @@ -0,0 +1,104 @@ +#include +#include + +#include "publisher.h" + +namespace slam +{ + + Publisher::Publisher() + { + ros::NodeHandle nhp("~"); + pub_clustering_ = nhp.advertise("keypoints_clustering", 2, true); + pub_stereo_matches_img_ = nhp.advertise("stereo_matches_img", 2, true); + pub_stereo_matches_num_ = nhp.advertise("stereo_matches_num", 2, true); + } + + void Publisher::publishClustering(const Frame frame) + { + if (pub_clustering_.getNumSubscribers() > 0) + drawKeypointsClustering(frame); + } + + void Publisher::publishStereoMatches(const Frame frame) + { + if (pub_stereo_matches_img_.getNumSubscribers() > 0 || + pub_stereo_matches_num_.getNumSubscribers() > 0) + drawStereoMatches(frame); + } + + void Publisher::drawKeypointsClustering(const Frame frame) + { + vector< vector > clusters = frame.getClusters(); + if (clusters.size() == 0) return; + + cv::Mat img; + frame.getLeftImg().copyTo(img); + vector kp = frame.getLeftKp(); + cv::RNG rng(12345); + for (uint i=0; i l_kp = frame.getNonFilteredLeftKp(); + vector r_kp = frame.getNonFilteredRightKp(); + vector matches = frame.getMatches(); + + if (pub_stereo_matches_img_.getNumSubscribers() > 0) + { + cv::drawMatches(l_img, l_kp, r_img, r_kp, matches, out); + + // Draw text + stringstream s; + int baseline = 0; + s << " Number of matches: " << matches.size(); + cv::Size text_size = cv::getTextSize(s.str(), cv::FONT_HERSHEY_PLAIN, 1.5, 1, &baseline); + cv::Mat im_text = cv::Mat(out.rows + text_size.height + 20, out.cols, out.type()); + out.copyTo(im_text.rowRange(0, out.rows).colRange(0, out.cols)); + im_text.rowRange(out.rows, im_text.rows).setTo(cv::Scalar(255,255,255)); + cv::putText(im_text, s.str(), cv::Point(5, im_text.rows - 10), cv::FONT_HERSHEY_PLAIN, 1.5, cv::Scalar(0,0,0), 2, 8); + + // Publish + cv_bridge::CvImage ros_image; + ros_image.image = im_text.clone(); + ros_image.header.stamp = ros::Time::now(); + ros_image.encoding = "bgr8"; + pub_stereo_matches_img_.publish(ros_image.toImageMsg()); + } + + if (pub_stereo_matches_num_.getNumSubscribers() > 0) + { + std_msgs::Int32 msg; + msg.data = lexical_cast(matches.size()); + pub_stereo_matches_num_.publish(msg); + } + + } + +} //namespace slam \ No newline at end of file diff --git a/pool/shard001/C++/0023835_Storage.cpp b/pool/shard001/C++/0023835_Storage.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b59c01d9812ab3401076de527ed4046a2958e688 --- /dev/null +++ b/pool/shard001/C++/0023835_Storage.cpp @@ -0,0 +1,85 @@ +#include "Storage.h" + +#include + +namespace NoLimits { + namespace NoLimits2 { + void Storage::read(File::File *file) { + setEnableTransportDevice(file->readBoolean()); + setTransportType((Transport::TransportType)file->readUnsigned8()); + setBuilding((Storage::Building)file->readUnsigned8()); + setRoofColor(file->readColor()); + setSideColor(file->readColor()); + setFrameColor(file->readColor()); + + file->readNull(20); + } + + void Storage::write(File::File *file) { + file->writeBoolean(getEnableTransportDevice()); + file->writeUnsigned8(getTransportType()); + file->writeUnsigned8(getBuilding()); + file->writeColor(getRoofColor()); + file->writeColor(getSideColor()); + file->writeColor(getFrameColor()); + + file->writeNull(20); + } + + bool Storage::getEnableTransportDevice() const { + return enableTransportDevice; + } + + void Storage::setEnableTransportDevice(bool value) { + enableTransportDevice = value; + } + + TransportDevice *Storage::getTransportDevice() const { + return transportDevice; + } + + void Storage::setTransportDevice(TransportDevice *value) { + transportDevice = value; + } + + Transport::TransportType Storage::getTransportType() const { + return transportType; + } + + void Storage::setTransportType(const Transport::TransportType &value) { + transportType = value; + } + + Storage::Building Storage::getBuilding() const { + return building; + } + + void Storage::setBuilding(const Storage::Building &value) { + building = value; + } + + glm::vec3 Storage::getSideColor() const { + return sideColor; + } + + void Storage::setSideColor(const glm::vec3 &value) { + sideColor = value; + } + + glm::vec3 Storage::getRoofColor() const { + return roofColor; + } + + void Storage::setRoofColor(const glm::vec3 &value) { + roofColor = value; + } + + glm::vec3 Storage::getFrameColor() const { + return frameColor; + } + + void Storage::setFrameColor(const glm::vec3 &value) { + frameColor = value; + } + } +} diff --git a/pool/shard001/C++/0023838_quickChat.cpp b/pool/shard001/C++/0023838_quickChat.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3823c41716f440d8e102d7c6e954e66bdf92dfca --- /dev/null +++ b/pool/shard001/C++/0023838_quickChat.cpp @@ -0,0 +1,212 @@ +//----------------------------------------------------------------------------------- +// +// Torque Network Library - ZAP example multiplayer vector graphics space game +// Copyright (C) 2004 GarageGames.com, Inc. +// For more information see http://www.opentnl.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. +// +// For use in products that are not compatible with the terms of the GNU +// General Public License, alternative licensing options are available +// from GarageGames.com. +// +// 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 "quickChat.h" +#include "UIGame.h" +#include "glutInclude.h" +#include "gameType.h" +#include "UIMenus.h" +#include "gameObjectRender.h" +#include "input.h" +#include +namespace Zap +{ +void renderControllerButton(F32 x, F32 y, U32 buttonIndex, U32 keyIndex); + +VChatHelper::VChatNode VChatHelper::mChatTree[] = +{ + // Root node + {0, ' ', -1, true, "", ""}, + {1, 'G', 5, true, "Global", ""}, + {2, 'Z', 5, false, "Doh", "Doh!"}, + {2, 'S', 4, false, "Shazbot", "Shazbot!"}, + {2, 'D', 3, false, "Damnit", "Dammit!"}, + {2, 'C', -1, false, "Crap", "Ah Crap!"}, + {2, 'E', 2, false, "Duh", "Duh."}, + {2, 'X', -1, false, "You idiot!", "You idiot!"}, + {2, 'T', 1, false, "Thanks", "Thanks."}, + {2, 'A', 0, false, "No Problem", "No Problemo."}, + {1, 'D', 4, true, "Defense", ""}, + {2, 'A', -1, true, "Attacked", "We are being attacked."}, + {2, 'E', 5, true, "Enemy Attacking Base", "The enemy is attacking our base."}, + {2, 'N', 4, true, "Need More Defense", "We need more defense."}, + {2, 'T', 3, true, "Base Taken", "Base is taken."}, + {2, 'C', 2, true, "Base Clear", "Base is secured."}, + {2, 'Q', 1, true, "Is Base Clear?", "Is our base clear?"}, + {2, 'D', 0, true, "Defending Base", "Defending our base."}, + {2, 'G', -1, true, "Defend Our Base", "Defend our base."}, + {1, 'F', 3, true, "Flag", ""}, + {2, 'G', 5, true, "Flag gone", "Our flag is not in the base!"}, + {2, 'E', 4, true, "Enemy has flag", "The enemy has our flag!"}, + {2, 'H', 3, true, "Have enemy flag", "I have the enemy flag."}, + {2, 'S', 2, true, "Flag secure", "Our flag is secure."}, + {2, 'R', 1, true, "Return our flag", "Return our flag to base."}, + {2, 'F', 0, true, "Get enemy flag", "Get the enemy flag."}, + {1, 'S', -1, true, "Incoming Enemies - Direction", ""}, + {2, 'V', -1, true, "Incoming Enemies", "Incoming enemies!"}, + {2, 'W', -1, true, "Incoming North", "*** INCOMING NORTH ***"}, + {2, 'D', -1, true, "Incoming West", "*** INCOMING WEST ***"}, + {2, 'A', -1, true, "Incoming East", "*** INCOMING EAST ***"}, + {2, 'S', -1, true, "Incoming South", "*** INCOMING SOUTH ***"}, + {1, 'V', 2, true, "Quick", ""}, + {2, 'Z', 5, true, "Move out", "Move out."}, + {2, 'G', 4, true, "Going offense", "Going offense."}, + {2, 'E', 3, true, "Regroup", "Regroup."}, + {2, 'V', 2, true, "Help!", "Help!" }, + {2, 'W', 1, true, "Wait for signal", "Wait for my signal to attack."}, + {2, 'A', 0, true, "Attack!", "Attack!"}, + {2, 'O', -1, true, "Go on the offensive", "Go on the offensive."}, + {2, 'J', -1, true, "Capture the objective", "Capture the objective."}, + {1, 'R', 1, true, "Reponses", ""}, + {2, 'D', 5, true, "Dont know", "I don't know."}, + {2, 'T', 4, true, "Thanks", "Thanks."}, + {2, 'S', 3, true, "Sorry", "Sorry."}, + {2, 'Y', 2, true, "Yes", "Yes."}, + {2, 'N', 1, true, "No", "No."}, + {2, 'A', 0, true, "Acknowledge", "Acknowledged."}, + {1, 'T', 0, true, "Taunts", ""}, + {2, 'E', 5, false, "Yoohoo!", "Yoohoo!"}, + {2, 'Q', 4, false, "How'd THAT feel?", "How'd THAT feel?"}, + {2, 'W', 3, false, "I've had worse...", "I've had worse..."}, + {2, 'X', 2, false, "Missed me!", "Missed me!"}, + {2, 'D', 1, false, "Dance!", "Dance!"}, + {2, 'C', 0, false, "Come get some!", "Come get some!"}, + {2, 'R', -1, false, "Rawr", "RAWR!"}, + + // Terminate + {0, ' ', false, "", ""} +}; + +VChatHelper::VChatHelper() +{ + mCurNode = &mChatTree[0]; +} + +void VChatHelper::render() +{ + Vector renderNodes; + + VChatNode *walk = mCurNode; + U32 matchLevel = walk->depth + 1; + walk++; + + // First get to the end... + while(walk->depth >= matchLevel) + walk++; + + // Then draw bottom up... + while(walk != mCurNode) + { + if(walk->depth == matchLevel && (!mFromController || (mFromController && walk->buttonIndex != -1))) + renderNodes.push_back(walk); + walk--; + } + + S32 curPos = 300; + const int fontSize = 15; + + for(S32 i = 0; i < renderNodes.size(); i++) + { + glColor3f(0.3, 1.0, 0.3); + renderControllerButton(UserInterface::horizMargin, curPos, renderNodes[i]->buttonIndex, renderNodes[i]->trigger); + + glColor3f(0.3, 1.0, 0.3); + UserInterface::drawStringf(UserInterface::horizMargin + 20, curPos, fontSize, "- %s", + renderNodes[i]->caption); + curPos += fontSize + 4; + } +} + +void VChatHelper::show(bool fromController) +{ + mCurNode = &mChatTree[0]; + mFromController = OptionsMenuUserInterface::joystickType != -1; + mIdleTimer.reset(MenuTimeout); +} + +void VChatHelper::idle(U32 delta) +{ + if(mIdleTimer.update(delta)) + gGameUserInterface.setPlayMode(); +} + +void VChatHelper::processKey(U32 key) +{ + // Escape... + if(key == 8 || key == 27) + { + UserInterface::playBoop(); + gGameUserInterface.setPlayMode(); + return; + } + + // Try to find a match if we can... + + // work in upper case... + key = toupper(key); + + // Set up walk... + VChatNode *walk = mCurNode; + U32 matchLevel = walk->depth+1; + walk++; + + // Iterate over anything at our desired depth or lower... + while(walk->depth >= matchLevel) + { + + // If it has the same key and depth... + bool match = (!mFromController && toupper(walk->trigger) == key) || + (mFromController && key == walk->buttonIndex); + if(match && walk->depth == matchLevel) + { + mIdleTimer.reset(MenuTimeout); + // select it... + mCurNode = walk; + + UserInterface::playBoop(); + + // If we're at a leaf (ie, next child down is higher or equal to us), then issue the chat and call it good... + walk++; + if(mCurNode->depth >= walk->depth) + { + GameType *gt = gClientGame->getGameType(); + gGameUserInterface.setPlayMode(); + + StringTableEntry entry(mCurNode->msg); + if(gt) + gt->c2sSendChatSTE(!mCurNode->teamOnly, entry); + + return; + } + } + + walk++; + } + +} + + +}; diff --git a/pool/shard001/C++/0023842_listenserv.cpp b/pool/shard001/C++/0023842_listenserv.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b36e3f9887fe19e230ba089ed5a1484c8d7abacb --- /dev/null +++ b/pool/shard001/C++/0023842_listenserv.cpp @@ -0,0 +1,181 @@ +/* + * This file is part of range++. + * + * range++ 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. + * + * range++ 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 range++. If not, see . + */ + +#include "listenserv.h" +#include "signalhandler.h" +#include "paxos.h" +#include "worker_thread.h" + + +namespace range { namespace stored { + +using boost::asio::ip::udp; + +static ::range::EmitterModuleRegistration ListenServerLogModule { "stored.ListenServer" }; +//############################################################################## +//############################################################################## +ListenServer::ListenServer(boost::shared_ptr<::range::StoreDaemonConfig> cfg) + : WorkerThread{ListenServerLogModule}, + socket_{io_service_, udp::endpoint(udp::v4(), cfg->port())}, + cfg_{cfg} +{ + receive(); +} + +//############################################################################## +//############################################################################## +void +ListenServer::event_loop_init() +{ +} + +//############################################################################## +//############################################################################## +void +ListenServer::event_task() +{ + io_service_.run(); +} + + +//############################################################################## +//############################################################################## +void +ListenServer::shutdown() +{ + RANGE_LOG_FUNCTION(); + WorkerThread::shutdown(); + io_service_.stop(); + paxos::unblock_queues(); +} + +//############################################################################## +//############################################################################## +void +ListenServer::receive() +{ + RANGE_LOG_FUNCTION(); + if (this->get_shutdown()) { return; } + + using namespace std::placeholders; + socket_.async_receive_from( + boost::asio::buffer(buf_, sizeof(buf_)), endpoint_, + std::bind(&ListenServer::receive_handler, this, _1, _2) + ); +} + +//############################################################################## +//############################################################################## +void +ListenServer::receive_handler(const boost::system::error_code &error, std::size_t len) +{ + RANGE_LOG_TIMED_FUNCTION(); + + if (this->get_shutdown()) { return; } + + using namespace std::placeholders; + stored::Request msg; + stored::Ack ack = validate_msg(error, len, msg); + + if(ack.status()) { + LOG(debug1, "received_message") + << "source addr: " << endpoint_.address().to_string() + << " source port: " << endpoint_.port() + << " type: " << msg.GetTypeName() + << " method: " << msg.method(); + } + + switch (msg.type()) { + case Request::Type::Request_Type_HEARTBEAT: + socket_.async_send_to( + boost::asio::buffer(ack.SerializeAsString()), endpoint_, + std::bind(&ListenServer::send_handler, this, _1, _2) + ); + break; + default: + if(ack.status()) { + msg.set_sender_addr(endpoint_.address().to_v4().to_ulong()); + msg.set_sender_port(endpoint_.port()); + + paxos::submit(msg); + } + break; + } + receive(); +} + +//############################################################################## +//############################################################################## +void +ListenServer::send_handler(const boost::system::error_code&, std::size_t) +{ + RANGE_LOG_FUNCTION(); +} + +//############################################################################## +//############################################################################## +Ack +ListenServer::validate_msg(const boost::system::error_code &error, size_t len, Request &msg) +{ + stored::Ack ack; + + ack.set_status(true); + ack.set_code(0); + ack.set_reason(""); + ack.set_request_id(std::numeric_limits::max()); + ack.set_client_id(""); + + if(error) { + LOG(warning, "receive_error") + << "source addr: " << endpoint_.address().to_string() + << " source port: " << endpoint_.port() + << error.message(); + ack.set_status(error); + ack.set_code(error.value()); + ack.set_reason(error.message()); + } else { + msg.ParseFromString(std::string(buf_, len)); + if(!msg.IsInitialized()) { + LOG(warning, "invalid_msg") + << "source addr: " << endpoint_.address().to_string() + << " source port: " << endpoint_.port() ; + ack.set_status(false); + ack.set_code(-1); + ack.set_reason("Unable to parse datagram"); + } else { + uint32_t crc = msg.crc(); + msg.set_crc(0); + if (crc != ::range::util::crc32(msg.SerializeAsString())) { + LOG(warning, "invalid_crc32") + << "source addr: " << endpoint_.address().to_string() + << " source port: " << endpoint_.port() ; + ack.set_status(false); + ack.set_code(-2); + ack.set_reason("Invalid CRC"); + } + } + } + + ack.set_request_id(msg.request_id()); + ack.set_client_id(msg.client_id()); + + return ack; +} + + + +} /* namespace */ } /* namespace stored */ diff --git a/pool/shard001/C++/0023843_SpriteSheet.cpp b/pool/shard001/C++/0023843_SpriteSheet.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a711aea21f49a3757271fcfde3ce074bab7b2dd4 --- /dev/null +++ b/pool/shard001/C++/0023843_SpriteSheet.cpp @@ -0,0 +1,157 @@ +#include "SpriteSheet.hpp" +#include "Animation.hpp" + +#include "Simple OpenGL Image Library/SOIL.h" +#include "rapidxml/rapidxml.hpp" + +#include +#include + +namespace Engine +{ + SpriteSheet::SpriteSheet(const std::string& spriteSheetName, const std::string& spriteSheetNameXml) + { + loadSpriteSheet(spriteSheetName); + loadSpritesFromXml(spriteSheetNameXml); + } + + void SpriteSheet::loadSpriteSheet(const std::string& path) + { + if (path.empty()) + { + return; + } + + glGenTextures(1, &m_texture); + + glBindTexture(GL_TEXTURE_2D, m_texture); // All upcoming GL_TEXTURE_2D operations now have effect on our texture object + // Set our texture parameters + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); // Set texture wrapping to GL_REPEAT + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); + // Set texture filtering + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + const auto image = SOIL_load_image(path.c_str(), &m_width, &m_height, nullptr, SOIL_LOAD_RGBA); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, m_width, m_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, image); + SOIL_free_image_data(image); + glBindTexture(GL_TEXTURE_2D, 0); // Unbind texture when done, so we won't accidentally mess up our texture. + + m_sprites.emplace_back("wholeSpriteSheet", glm::vec4(m_width, m_height, m_width, m_height)); + } + + void SpriteSheet::loadSpritesFromXml(const std::string& path) + { + if (path.empty()) + { + return; + } + + auto doc = new rapidxml::xml_document<>(); + // Read the xml file into a vector + std::ifstream theFile(path); + std::vector buffer((std::istreambuf_iterator(theFile)), std::istreambuf_iterator()); + buffer.push_back('\0'); + // Parse the buffer using the xml file parsing library into doc + doc->parse<0>(&buffer[0]); + // Find our root node + rapidxml::xml_node<>* root_node = doc->first_node(); + // Iterate over the breweries + for (auto brewery_node = root_node->first_node(); brewery_node; brewery_node = brewery_node->next_sibling()) + { + auto animation = glm::vec4(atof(brewery_node->first_attribute("x")->value()), + atof(brewery_node->first_attribute("y")->value()), + atof(brewery_node->first_attribute("width")->value()), + atof(brewery_node->first_attribute("height")->value())); + m_sprites.emplace_back(brewery_node->first_attribute("name")->value(), animation); + } + + theFile.close(); + doc->clear(); + delete doc; + } + + std::shared_ptr SpriteSheet::getSprite(const std::string& index) + { + auto sprites = getSprites(); + + for (const auto& sprite : sprites) + { + if (sprite.first == index) + { + auto animation = std::make_shared(m_texture, getWidth(), getHeight()); + animation->addSprite(sprite.second); + return animation; + } + } + + return nullptr; + } + + glm::vec4 SpriteSheet::getSpriteAsVector(const std::string& index) const + { + auto sprites = getSprites(); + const auto it = std::find_if(sprites.begin(), sprites.end(), [index](auto idx) { return idx.first == index; }); + + return it != sprites.end() ? it->second : glm::vec4(0.0, 0.0, 0.0, 0.0); + } + + void SpriteSheet::makeAnimation(const std::string& index, const std::vector& indexes) + { + auto animations = getAnimations(); + + for (const auto& animation : animations) + { + if (animation.first == index) + { + return; + } + } + + auto _animation = std::make_shared(getTexture(), getWidth(), getHeight()); + auto sprites = getSprites(); + + for (const auto& _index : indexes) + { + for (const auto& sprite : sprites) + { + if (sprite.first == _index) + { + _animation->addSprite(sprite.second); + break; + } + } + } + + m_animations.emplace_back(index, _animation); + } + + void SpriteSheet::makeAnimation(const std::string& index, const std::vector& sprites) + { + auto animations = getAnimations(); + + for (const auto& animation : animations) + { + if (animation.first == index) + { + return; + } + } + + auto _animation = std::make_shared(getTexture(), getWidth(), getHeight()); + + for (auto sprite : sprites) + { + _animation->addSprite(sprite); + } + + m_animations.emplace_back(index, _animation); + } + + std::shared_ptr SpriteSheet::getAnimation(const std::string& index) const + { + auto animations = getAnimations(); + const auto it = std::find_if(animations.begin(), animations.end(), [index](auto idx) { return idx.first == index; }); + + return it != animations.end() ? it->second : nullptr; + } +} diff --git a/pool/shard001/C++/0023845_playertest.cpp b/pool/shard001/C++/0023845_playertest.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e6ac8ce1df66cd1346811aa3147071afc2ec25db --- /dev/null +++ b/pool/shard001/C++/0023845_playertest.cpp @@ -0,0 +1,238 @@ +/* + * Adplug - Replayer for many OPL2/OPL3 audio file formats. + * Copyright (C) 1999 - 2008 Simon Peter, , et al. + * + * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * playertest.cpp - Test AdPlug replayers, by Simon Peter + */ + +#include +#include +#include +#include + +#include "../src/adplug.h" +#include "../src/opl.h" + +#ifdef MSDOS +# define DIR_DELIM "\\" +#else +# define DIR_DELIM "/" +#endif + +/***** Local variables *****/ + +// List of all filenames to test +static const char *filelist[] = { + "SONG1.sng", // Adlib Tracker + "2001.MKJ", // MK-Jamz + "ADAGIO.DFM", // Digital-FM + "adlibsp.s3m", // Scream Tracker 3 + "ALLOYRUN.RAD", // Reality AdLib Tracker + "ARAB.BAM", // Bob's AdLib Music + "BEGIN.KSM", // Ken Silverman + "BOOTUP.M", // Ultima 6 + "CHILD1.XSM", // eXtra Simple Music + "DTM-TRK1.DTM", // DeFy Adlib Tracker + "fdance03.dmo", // TwinTrack + "ice_thnk.sci", // Sierra + "inc.raw", // RAW + "loudness.lds", // Loudness + "MARIO.A2M", // AdLib Tracker 2 + "mi2.laa", // LucasArts + "michaeld.cmf", // Creative Music Format + "PLAYMUS1.SNG", // SNGPlay + "rat.xad", // xad: rat + "REVELAT.SNG", // Faust Music Creator + "SAILOR.CFF", // Boomtracker + "samurai.dro", // DOSBox v0.1 (one-byte hardware type) + "doofus.dro", // DOSBox v0.1 (four-byte hardware type) + "SCALES.SA2", // Surprise! Adlib Tracker 2 + "SMKEREM.HSC", // HSC-Tracker + "TOCCATA.MAD", // Mlat Adlib Tracker + "TUBES.SAT", // Surprise! Adlib Tracker + "TU_BLESS.AMD", // AMUSIC + "VIB_VOL3.D00", // EdLib Packed + "WONDERIN.WLF", // Apogee + "bmf1_2.xad", // xad: BMF + "flash.xad", // xad: flash + "HIP_D.ROL", // Visual Composer + "hybrid.xad", // xad: hybrid + "hyp.xad", // xad: hyp + "psi1.xad", // xad: PSI + "SATNIGHT.HSP", // HSC Packed + "blaster2.msc", // AdLib MSCplay + "RI051.RIX", // Softstar RIX OPL Music + "DUNE19.ADL", // Westwood ADL + "DEMO4.JBM", // JBM Adlib Music + "dro_v2.dro", // DOSBox DRO v2.0 + NULL +}; + +// String holding the relative path to the source directory +static const char *srcdir; + +/***** Testopl *****/ + +class Testopl: public Copl +{ +public: + Testopl(const std::string filename) + { + f = fopen(filename.c_str(), "w"); + if(!f) std::cerr << "Error opening for writing: " << filename << std::endl; + + currType = TYPE_OPL3; + } + + virtual ~Testopl() + { + if(f) fclose(f); + } + + void update(CPlayer *p) + { + if(!f) return; + fprintf(f, "r%.2f\n", p->getrefresh()); + } + + // template methods + void write(int reg, int val) + { + if(reg > 255 || val > 255 || reg < 0 || val < 0) + std::cerr << "Warning: The player is writing data out of range! (reg = " + << std::hex << reg << ", val = " << val << ")\n"; + if(!f) return; + fprintf(f, "%x <- %x\n", reg, val); + } + + void setchip(int n) + { + Copl::setchip(n); + + if(!f) return; + fprintf(f, "setchip(%d)\n", n); + } + + void init() + { + if(!f) return; + fprintf(f, "init\n"); + } + +private: + FILE *f; +}; + +/***** Local functions *****/ + +static bool diff(const std::string fn1, const std::string fn2) + /* + * Compares files 'fn1' and 'fn2' line by line and returns true if they are + * equal or false otherwise. A line is at most 79 characters in length or the + * comparison will fail. + */ +{ + FILE *f1, *f2; + bool retval = true; + + // open both files + if(!(f1 = fopen(fn1.c_str(), "r"))) return false; + if(!(f2 = fopen(fn2.c_str(), "r"))) { fclose(f1); return false; } + + // compare both files line by line + char *s1 = (char *)malloc(80), *s2 = (char *)malloc(80); + while(!(feof(f1) || feof(f2))) { + fgets(s1, 80, f1); + fgets(s2, 80, f2); + if(strncmp(s1, s2, 79)) { + retval = false; + break; + } + } + free(s1), free(s2); + if(feof(f1) != feof(f2)) + retval = false; + + // close both files + fclose(f1), fclose(f2); + return retval; +} + +static bool testplayer(const std::string filename) + /* + * Tests playback of file 'filename' by comparing its RAW output with a + * prerecorded original and returns true if they match, false otherwise. + */ +{ + std::string fn = std::string(srcdir) + DIR_DELIM + filename; +#ifdef __WATCOMC__ + std::string testfn = tmpnam(NULL); +#else + std::string testfn = filename + ".test"; +#endif + std::string reffn = fn.substr(0, fn.find_last_of(".")) + ".ref"; + Testopl *opl = new Testopl(testfn); + CPlayer *p = CAdPlug::factory(fn, opl); + + if(!p) { + std::cout << "Error loading: " << fn << std::endl; + delete opl; return false; + } + + // Output file information + std::cout << "Testing format: " << p->gettype() << " - "; + + // Write whole file to disk + while(p->update()) + opl->update(p); + + delete p; + delete opl; + + if(diff(reffn, testfn)) { + std::cout << "OK\n"; + remove(std::string(testfn).c_str()); + return true; + } else { + std::cout << "FAIL\n"; + return false; + } +} + +/***** Main program *****/ + +int main(int argc, char *argv[]) +{ + int i; + bool retval = true; + + // Set path to source directory + srcdir = getenv("srcdir"); + if(!srcdir) srcdir = "."; + + // Try all files one by one + if(argc > 1) { + for(i = 1; i < argc; i++) + if(!testplayer(argv[i])) + retval = false; + } else + for(i = 0; filelist[i] != NULL; i++) + if(!testplayer(filelist[i])) + retval = false; + + return retval ? EXIT_SUCCESS : EXIT_FAILURE; +} diff --git a/pool/shard001/C++/0023848_signal.cc b/pool/shard001/C++/0023848_signal.cc new file mode 100644 index 0000000000000000000000000000000000000000..ded307b1647a720a2fcc33f439eb7feae56467d6 --- /dev/null +++ b/pool/shard001/C++/0023848_signal.cc @@ -0,0 +1,232 @@ +/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab: + * + * Data Differential Utility library + * + * Copyright (C) 2012 Data Differential, http://datadifferential.com/ + * + * 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. + * + * * The names of its contributors may not 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 "gear_config.h" + +#include +#include +#include +#include +#include +#include + +#include + +namespace datadifferential { +namespace util { + +#define MAGIC_MEMORY 123569 + +bool SignalThread::is_shutdown() +{ + bool ret; + pthread_mutex_lock(&shutdown_mutex); + ret= bool(__shutdown != SHUTDOWN_RUNNING); + pthread_mutex_unlock(&shutdown_mutex); + + return ret; +} + +void SignalThread::set_shutdown(shutdown_t arg) +{ + pthread_mutex_lock(&shutdown_mutex); + __shutdown= arg; + pthread_mutex_unlock(&shutdown_mutex); + + if (arg == SHUTDOWN_GRACEFUL) + { + if (pthread_kill(thread, SIGUSR2) == 0) + { + void *retval; + pthread_join(thread, &retval); + } + } +} + +shutdown_t SignalThread::get_shutdown() +{ + shutdown_t local; + pthread_mutex_lock(&shutdown_mutex); + local= __shutdown; + pthread_mutex_unlock(&shutdown_mutex); + + return local; +} + +void SignalThread::post() +{ + sem_post(&lock); +} + +void SignalThread::test() +{ + assert(magic_memory == MAGIC_MEMORY); + assert(sigismember(&set, SIGABRT)); + assert(sigismember(&set, SIGINT)); + assert(sigismember(&set, SIGQUIT)); + assert(sigismember(&set, SIGTERM)); + assert(sigismember(&set, SIGUSR2)); +} + +void SignalThread::sighup(signal_callback_fn* arg) +{ + _sighup= arg; +} + +void SignalThread::sighup() +{ + if (_sighup) + { + _sighup(); + } +} + +SignalThread::~SignalThread() +{ + if (not is_shutdown()) + { + set_shutdown(SHUTDOWN_GRACEFUL); + } + +#if 0 + if (pthread_equal(thread, pthread_self()) != 0 and (pthread_kill(thread, 0) == ESRCH) == true) + { + void *retval; + pthread_join(thread, &retval); + } +#endif + sem_destroy(&lock); +} + +extern "C" { + +static void *sig_thread(void *arg) +{ + SignalThread *context= (SignalThread*)arg; + + context->test(); + context->post(); + + while (context->get_shutdown() == SHUTDOWN_RUNNING) + { + int sig; + + if (context->wait(sig) == -1) + { + std::cerr << "sigwait() returned errno:" << strerror(errno) << std::endl; + continue; + } + + switch (sig) + { + case SIGUSR2: + break; + + case SIGHUP: + context->sighup(); + break; + + case SIGABRT: + case SIGINT: + case SIGQUIT: + case SIGTERM: + if (context->is_shutdown() == false) + { + context->set_shutdown(SHUTDOWN_FORCED); + } + + if (context->exit_on_signal()) + { + exit(EXIT_SUCCESS); + } + + break; + + default: + std::cerr << "Signal handling thread got unexpected signal " << strsignal(sig) << std::endl; + break; + } + } + + return NULL; +} + +} + +SignalThread::SignalThread(bool exit_on_signal_arg) : + _exit_on_signal(exit_on_signal_arg), + magic_memory(MAGIC_MEMORY), + __shutdown(SHUTDOWN_RUNNING), + thread(pthread_self()), + _sighup(NULL) +{ + pthread_mutex_init(&shutdown_mutex, NULL); + sigemptyset(&set); + + sigaddset(&set, SIGABRT); + sigaddset(&set, SIGINT); + sigaddset(&set, SIGQUIT); + sigaddset(&set, SIGTERM); + sigaddset(&set, SIGUSR2); + + sem_init(&lock, 0, 0); +} + + +bool SignalThread::setup() +{ + set_shutdown(SHUTDOWN_RUNNING); + + int error; + if ((error= pthread_sigmask(SIG_BLOCK, &set, NULL)) != 0) + { + std::cerr << "pthread_sigmask() died during pthread_sigmask(" << strerror(error) << ")" << std::endl; + return false; + } + + if ((error= pthread_create(&thread, NULL, &sig_thread, this)) != 0) + { + std::cerr << "pthread_create() died during pthread_create(" << strerror(error) << ")" << std::endl; + return false; + } + + sem_wait(&lock); + + return true; +} + +} /* namespace util */ +} /* namespace datadifferential */ diff --git a/pool/shard001/C++/0023849_qmlprofilerdetailsrewriter.cpp b/pool/shard001/C++/0023849_qmlprofilerdetailsrewriter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f2ce13c544f07a046afb7d61fb16967e3ed60d0a --- /dev/null +++ b/pool/shard001/C++/0023849_qmlprofilerdetailsrewriter.cpp @@ -0,0 +1,216 @@ +/**************************************************************************** +** +** 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 "qmlprofilerdetailsrewriter.h" + +#include +#include +#include + +#include + +namespace QmlProfiler { +namespace Internal { + +struct PendingEvent { + QmlDebug::QmlEventLocation location; + QString localFile; + int requestId; +}; + +class PropertyVisitor: protected QmlJS::AST::Visitor +{ + QmlJS::AST::Node * _lastValidNode; + unsigned _line; + unsigned _col; +public: + QmlJS::AST::Node * operator()(QmlJS::AST::Node *node, unsigned line, unsigned col) + { + _line = line; + _col = col; + _lastValidNode = 0; + accept(node); + return _lastValidNode; + } + +protected: + using QmlJS::AST::Visitor::visit; + + void accept(QmlJS::AST::Node *node) + { + if (node) + node->accept(this); + } + + bool containsLocation(QmlJS::AST::SourceLocation start, QmlJS::AST::SourceLocation end) + { + return (_line > start.startLine || (_line == start.startLine && _col >= start.startColumn)) && + (_line < end.startLine || (_line == end.startLine && _col <= end.startColumn)); + } + + + virtual bool preVisit(QmlJS::AST::Node *node) + { + if (QmlJS::AST::cast(node)) + return false; + return containsLocation(node->firstSourceLocation(), node->lastSourceLocation()); + } + + virtual bool visit(QmlJS::AST::UiScriptBinding *ast) + { + _lastValidNode = ast; + return true; + } + + virtual bool visit(QmlJS::AST::UiPublicMember *ast) + { + _lastValidNode = ast; + return true; + } +}; + +class QmlProfilerDetailsRewriter::QmlProfilerDetailsRewriterPrivate +{ +public: + QmlProfilerDetailsRewriterPrivate(QmlProfilerDetailsRewriter *qq, + Utils::FileInProjectFinder *fileFinder) + : m_projectFinder(fileFinder), q(qq) {} + ~QmlProfilerDetailsRewriterPrivate() {} + + QList m_pendingEvents; + QStringList m_pendingDocs; + Utils::FileInProjectFinder *m_projectFinder; + QMap m_filesCache; + + QmlProfilerDetailsRewriter *q; +}; + +QmlProfilerDetailsRewriter::QmlProfilerDetailsRewriter( + QObject *parent, Utils::FileInProjectFinder *fileFinder) + : QObject(parent), d(new QmlProfilerDetailsRewriterPrivate(this, fileFinder)) +{ } + +QmlProfilerDetailsRewriter::~QmlProfilerDetailsRewriter() +{ + delete d; +} + +void QmlProfilerDetailsRewriter::requestDetailsForLocation(int requestId, + const QmlDebug::QmlEventLocation &location) +{ + QString localFile; + if (!d->m_filesCache.contains(location.filename)) { + localFile = d->m_projectFinder->findFile(location.filename); + d->m_filesCache[location.filename] = localFile; + } else { + localFile = d->m_filesCache[location.filename]; + } + QFileInfo fileInfo(localFile); + if (!fileInfo.exists() || !fileInfo.isReadable()) + return; + if (!QmlJS::ModelManagerInterface::guessLanguageOfFile(localFile).isQmlLikeLanguage()) + return; + + localFile = fileInfo.canonicalFilePath(); + + PendingEvent ev = {location, localFile, requestId}; + d->m_pendingEvents << ev; + if (!d->m_pendingDocs.contains(localFile)) { + if (d->m_pendingDocs.isEmpty()) + connect(QmlJS::ModelManagerInterface::instance(), + &QmlJS::ModelManagerInterface::documentUpdated, + this, + &QmlProfilerDetailsRewriter::documentReady); + + d->m_pendingDocs << localFile; + } +} + +void QmlProfilerDetailsRewriter::reloadDocuments() +{ + if (!d->m_pendingDocs.isEmpty()) + QmlJS::ModelManagerInterface::instance()->updateSourceFiles(d->m_pendingDocs, false); + else + emit eventDetailsChanged(); +} + +void QmlProfilerDetailsRewriter::rewriteDetailsForLocation(QTextStream &textDoc, + QmlJS::Document::Ptr doc, int requestId, const QmlDebug::QmlEventLocation &location) +{ + PropertyVisitor propertyVisitor; + QmlJS::AST::Node *node = propertyVisitor(doc->ast(), location.line, location.column); + + if (!node) + return; + + qint64 startPos = node->firstSourceLocation().begin(); + qint64 len = node->lastSourceLocation().end() - startPos; + + textDoc.seek(startPos); + QString details = textDoc.read(len).replace(QLatin1Char('\n'), QLatin1Char(' ')).simplified(); + + emit rewriteDetailsString(requestId, details); +} + +void QmlProfilerDetailsRewriter::clearRequests() +{ + d->m_filesCache.clear(); + d->m_pendingDocs.clear(); +} + +void QmlProfilerDetailsRewriter::documentReady(QmlJS::Document::Ptr doc) +{ + // this could be triggered by an unrelated reload in Creator + if (!d->m_pendingDocs.contains(doc->fileName())) + return; + + // if the file could not be opened this slot is still triggered but source will be an empty string + QString source = doc->source(); + if (!source.isEmpty()) { + QTextStream st(&source, QIODevice::ReadOnly); + + for (int i = d->m_pendingEvents.count()-1; i>=0; i--) { + PendingEvent ev = d->m_pendingEvents[i]; + if (ev.localFile == doc->fileName()) { + d->m_pendingEvents.removeAt(i); + rewriteDetailsForLocation(st, doc, ev.requestId, ev.location); + } + } + } + + d->m_pendingDocs.removeOne(doc->fileName()); + + if (d->m_pendingDocs.isEmpty()) { + disconnect(QmlJS::ModelManagerInterface::instance(), + &QmlJS::ModelManagerInterface::documentUpdated, + this, + &QmlProfilerDetailsRewriter::documentReady); + emit eventDetailsChanged(); + d->m_filesCache.clear(); + } +} + +} // namespace Internal +} // namespace QmlProfiler diff --git a/pool/shard001/C++/0023853_sched_timezone.cpp b/pool/shard001/C++/0023853_sched_timezone.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b2c843e0b27c89297dcdc71b569b2c4fb562dfdf --- /dev/null +++ b/pool/shard001/C++/0023853_sched_timezone.cpp @@ -0,0 +1,325 @@ +// This file is part of BOINC. +// http://boinc.berkeley.edu +// Copyright (C) 2008 University of California +// +// BOINC 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. +// +// BOINC 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 BOINC. If not, see . + +// Scheduler code for directing a client to one of several +// download servers based on its time zone + +#include "config.h" +#include +#include +#include +#include + +#include "parse.h" + +#include "sched_types.h" +#include "sched_msgs.h" +#include "sched_config.h" + +#ifdef _USING_FCGI_ +#include "boinc_fcgi.h" +#endif + +typedef struct urltag { + int zone; + char name[124]; +} URLTYPE; + + +// these global variables are needed to pass information into the +// compare function below. +// +static int tzone=0; +static int hostid=0; + +// Evaluate differences between time-zone. Two time zones that differ +// by almost 24 hours are actually very close on the surface of the +// earth. This function finds the 'shortest way around' +// +static int compare(const void *x, const void *y) { + const URLTYPE *a=(const URLTYPE *)x; + const URLTYPE *b=(const URLTYPE *)y; + + char longname[512]; + + const int twelve_hours = 12*3600; + + int diffa = abs(tzone - (a->zone)); + int diffb = abs(tzone - (b->zone)); + + if (diffa > twelve_hours) { + diffa = 2*twelve_hours-diffa; + } + + if (diffb > twelve_hours) { + diffb = 2*twelve_hours-diffb; + } + + if (diffa < diffb) { + return -1; + } + + if (diffa > diffb) { + return +1; + } + + // In order to ensure uniform distribution, we hash paths that are + // equidistant from the host's timezone in a way that gives a + // unique ordering for each host but which is effectively random + // between hosts. + // + sprintf(longname, "%s%d", a->name, hostid); + std::string sa = md5_string((const unsigned char *)longname, strlen((const char *)longname)); + sprintf(longname, "%s%d", b->name, hostid); + std::string sb = md5_string((const unsigned char *)longname, strlen((const char *)longname)); + int xa = strtol(sa.substr(1, 7).c_str(), 0, 16); + int xb = strtol(sb.substr(1, 7).c_str(), 0, 16); + + if (xaxb) { + return 1; + } + + return 0; +} + +static URLTYPE *cached=NULL; +#define BLOCKSIZE 32 + +URLTYPE* read_download_list() { + int count=0; + int i; + + if (cached) return cached; + + const char *download_servers = config.project_path("download_servers"); +#ifndef _USING_FCGI_ + FILE *fp=fopen(download_servers, "r"); +#else + FCGI_FILE *fp=FCGI::fopen(download_servers, "r"); +#endif + + if (!fp) { + log_messages.printf(MSG_CRITICAL, + "File %s not found or unreadable!\n", download_servers + ); + return NULL; + } + + // read in lines from file + // + while (1) { + // allocate memory in blocks + if ((count % BLOCKSIZE)==0) { + cached=(URLTYPE *)realloc(cached, (count+BLOCKSIZE)*sizeof(URLTYPE)); + if (!cached) { + fclose(fp); + return NULL; + } + } + // read timezone offset and URL from file, and store in cache list + // + if (2==fscanf(fp, "%d %s", &(cached[count].zone), cached[count].name)) { + count++; + } else { + // provide a null terminator so we don't need to keep + // another global variable for count. + // + cached[count].name[0]='\0'; + break; + } + } + fclose(fp); + + if (!count) { + log_messages.printf(MSG_CRITICAL, + "File %s contained no valid entries!\n" + "Format of this file is one or more lines containing:\n" + "TIMEZONE_OFFSET_IN_SEC http://some.url.path\n", + download_servers + ); + free(cached); + return NULL; + } + + // sort URLs by distance from host timezone. See compare() above + // for details. + qsort(cached, count, sizeof(URLTYPE), compare); + + log_messages.printf(MSG_DEBUG, + "Sorted list of URLs follows [host timezone: UTC%+d]\n", + tzone + ); + for (i=0; i%s%s", i?"\n ":"", serverlist[i].name, path); + len += l; + if (len >= lim) { + *start = '\0'; + return (start-buffer); + } + start += l; + } + + return (start-buffer); +} + +// returns zero on success, non-zero to indicate an error +// +int add_download_servers(char *old_xml, char *new_xml, int tz) { + char *p, *q, *r; + int total_free = BLOB_SIZE - strlen(old_xml); + + p = (r = old_xml); + + // search for next URL to do surgery on + while ((q=strstr(p, ""))) { + // p is at current position + // q is at beginning of next "" tag + + char *s; + char path[MAXPATHLEN]; + int len = q-p; + + // copy everything from p to q to new_xml + // + strncpy(new_xml, p, len); + new_xml += len; + + // locate next instance of + // + if (!(r = strstr(q, ""))) { + return 1; + } + r += strlen(""); + + // r points to the end of the whole "..." tag + // parse out the URL into 'path' + // + if (!parse_str(q, "", path, 1024)) { + return 1; + } + + // check if path contains the string specified in config.xml + // + if (!(s = strstr(path,config.replace_download_url_by_timezone))) { + // if it doesn't, just copy the whole tag as it is + strncpy(new_xml, q, r-q); + new_xml += r-q; + p=r; + } else { + // calculate free space available for URL replaces + int lim = total_free - (len - (p - old_xml)); + + // find end of the specified replace string, + // i.e. start of the 'path' + s += strlen(config.replace_download_url_by_timezone); + + // insert new download list in place of the original single URL + len = make_download_list(new_xml, s, lim, tz); + if (len == 0) { + // if the replacement would exceed the maximum XML length, + // just keep the original URL + len = r-q; + strncpy(new_xml, q, len); + } else if (len < 0) { + return 1; + } + new_xml += len; + // advance pointer to start looking for next tag. + // + p=r; + } + } + + strcpy(new_xml, r); + return 0; +} + +// replace the download URL for apps with a list of +// multiple download servers. +// +void process_av_timezone(APP_VERSION* avp, APP_VERSION& av2) { + int retval; + + // set these global variables, needed by the compare() + // function so that the download URL list can be sorted by timezone + // + tzone = g_reply->host.timezone; + hostid = g_reply->host.id; + retval = add_download_servers(avp->xml_doc, av2.xml_doc, g_reply->host.timezone); + if (retval) { + log_messages.printf(MSG_CRITICAL, + "add_download_servers(to APP version) failed\n" + ); + // restore original WU! + av2 = *avp; + } +} + +// replace the download URL for WU files with a list of +// multiple download servers. +// +void process_wu_timezone( + WORKUNIT& wu2, WORKUNIT& wu3 +) { + int retval; + + tzone = g_reply->host.timezone; + hostid = g_reply->host.id; + + retval = add_download_servers(wu2.xml_doc, wu3.xml_doc, g_reply->host.timezone); + if (retval) { + log_messages.printf(MSG_CRITICAL, + "add_download_servers(to WU) failed\n" + ); + // restore original WU! + wu3 = wu2; + } +} + +const char *BOINC_RCSID_28b6ac7093 = "$Id$"; + diff --git a/pool/shard001/C++/0023856_delete_turn_dialog.cpp b/pool/shard001/C++/0023856_delete_turn_dialog.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3a007b730aaee5bc2b564a5afdeb7cfd05c4311b --- /dev/null +++ b/pool/shard001/C++/0023856_delete_turn_dialog.cpp @@ -0,0 +1,113 @@ +/*! + * \file delete_turn_dialog.cpp + * \author Remi BERTHO + * \date 06/10/15 + * \version 4.3.0 + */ + +/* + * delete_turn_dialog.cpp + * + * Copyright 2014-2017 Remi BERTHO + * + * This file is part of Csuper-gtk. + * + * Csuper-gtk 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. + * + * Csuper-gtk 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 "config.h" +#include + +#include "delete_turn_dialog.h" + +#include "csu_application.h" + +using namespace Gtk; +using namespace Glib; +using namespace csuper; + + +// +// Constructor and destructor +// +DeleteTurnDialog::DeleteTurnDialog(BaseObjectType* cobject, const RefPtr& refGlade) : CsuWidget(), Dialog(cobject) +{ + refGlade->get_widget("delete_turn_validate_button", ok_button_); + refGlade->get_widget("delete_turn_cancel_button", cancel_button_); + refGlade->get_widget("delete_turn_label", title_); + refGlade->get_widget("delete_turn_grid", main_grid_); + refGlade->get_widget("delete_turn_scrolledwindow", window_); + refGlade->get_widget("delete_turn_viewport", viewport_); + + ok_button_->set_image_from_icon_name("gtk-ok", ICON_SIZE_BUTTON); + cancel_button_->set_image_from_icon_name("gtk-cancel", ICON_SIZE_BUTTON); +} + +// +// Function +// +bool DeleteTurnDialog::launch(unsigned int turn) +{ + bool res = false; + + Grid* grid = new Grid(); + grid->set_column_spacing(5); + grid->set_row_spacing(5); + grid->set_margin_end(10); + grid->set_margin_start(10); + grid->set_margin_top(10); + grid->set_margin_bottom(10); + + + unsigned int nb = 0; + for (unsigned int i = 0; i < app()->game()->nbPlayer(); i++) + { + if (app()->game()->hasTurn(i, turn)) + { + CheckButton* tmp_button = manage(new CheckButton(app()->game()->playerName(i))); + grid->attach(*tmp_button, 0, nb, 1, 1); + nb++; + } + } + + viewport_->add(*grid); + + show_all(); + switch (run()) + { + case RESPONSE_ACCEPT: + res = true; + unsigned int i; + for (i = 0; i < nb; i++) + { + CheckButton* tmp_check_button = static_cast(grid->get_child_at(0, i)); + if (tmp_check_button->get_active()) + app()->game()->deleteTurn(turn, tmp_check_button->get_label()); + } + break; + case RESPONSE_CANCEL: + break; + default: + break; + } + hide(); + + delete grid; + + return res; +} diff --git a/pool/shard001/C++/0023858_PutEvaluationsResult.cpp b/pool/shard001/C++/0023858_PutEvaluationsResult.cpp new file mode 100644 index 0000000000000000000000000000000000000000..186f0f1f939cd787601d7117202a84e9e575f86a --- /dev/null +++ b/pool/shard001/C++/0023858_PutEvaluationsResult.cpp @@ -0,0 +1,43 @@ +/** + * 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::ConfigService::Model; +using namespace Aws::Utils::Json; +using namespace Aws::Utils; +using namespace Aws; + +PutEvaluationsResult::PutEvaluationsResult() +{ +} + +PutEvaluationsResult::PutEvaluationsResult(const Aws::AmazonWebServiceResult& result) +{ + *this = result; +} + +PutEvaluationsResult& PutEvaluationsResult::operator =(const Aws::AmazonWebServiceResult& result) +{ + JsonView jsonValue = result.GetPayload().View(); + if(jsonValue.ValueExists("FailedEvaluations")) + { + Array failedEvaluationsJsonList = jsonValue.GetArray("FailedEvaluations"); + for(unsigned failedEvaluationsIndex = 0; failedEvaluationsIndex < failedEvaluationsJsonList.GetLength(); ++failedEvaluationsIndex) + { + m_failedEvaluations.push_back(failedEvaluationsJsonList[failedEvaluationsIndex].AsObject()); + } + } + + + + return *this; +} diff --git a/pool/shard001/C++/0023862_jit.cpp b/pool/shard001/C++/0023862_jit.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ef6edee164d4ce590e3b6724b674ff3e24ea8d33 --- /dev/null +++ b/pool/shard001/C++/0023862_jit.cpp @@ -0,0 +1,107 @@ +#include "configuration.hpp" +#include "memory.hpp" + +#include "class/block_environment.hpp" +#include "class/jit.hpp" +#include "class/list.hpp" + +namespace rubinius { + void JIT::bootstrap(STATE) { + Module* jit = state->memory()->new_module(state, G(rubinius), "JIT"); + GO(jit).set(jit); + + Class* cls = state->memory()->new_class(state, G(jit), "CompileRequest"); + G(jit)->compile_class(state, cls); + + G(jit)->compile_list(state, List::create(state)); + } + + void JIT::initialize(STATE, JIT* obj, Module* under, const char* name) { + Module::initialize(state, obj, under, name); + } + + Object* JIT::compile(STATE, Object* object, CompiledCode* code, + Object* block_environment) + { + if(!CBOOL(enabled_p(state))) return cFalse; + + BlockEnvironment* block_env = try_as(block_environment); + if(!block_env) block_env = nil(); + + return cTrue; + } + + Object* JIT::enabled_p(STATE) { + return RBOOL(state->shared().config.machine_jit_enabled.value); + } + + Object* JIT::compile_threshold(STATE) { + // TODO: JIT + return Integer::from(state, 0 /*state->shared().config.jit_threshold_compile*/); + } + + Object* JIT::sync_set(STATE, Object* flag) { + return cFalse; + /* TODO: JIT + state->shared().config.jit_sync.set(CBOOL(flag)); + return sync_get(state); + */ + } + + Object* JIT::sync_get(STATE) { + return cFalse; + /* TODO: JIT + return RBOOL(state->shared().config.jit_sync); + */ + } + + Object* JIT::enable(STATE) { + if(!CBOOL(enabled_p(state))) return cFalse; + + return cTrue; + } + + Object* JIT::compile_soon(STATE, CompiledCode* code, + Class* receiver_class, BlockEnvironment* block_env, bool is_block) + { + if(!CBOOL(enabled_p(state))) return cFalse; + + return cTrue; + } + + Object* JIT::compile_callframe(STATE, CompiledCode* code, + int primitive) + { + if(!CBOOL(enabled_p(state))) return cFalse; + + return cTrue; + } + + Object* JIT::start_method_update(STATE) { + if(!CBOOL(enabled_p(state))) return cFalse; + + return cTrue; + } + + Object* JIT::end_method_update(STATE) { + if(!CBOOL(enabled_p(state))) return cFalse; + + return cTrue; + } + + JITCompileRequest* JITCompileRequest::create(STATE, CompiledCode* code, + Class* receiver_class, int hits, BlockEnvironment* block_env, bool is_block) + { + JITCompileRequest* request = + state->memory()->new_object(state, G(jit)->compile_class()); + + request->method(state, code); + request->receiver_class(state, receiver_class); + request->block_env(state, block_env); + request->hits(hits); + request->is_block(is_block); + request->waiter(NULL); + + return request; + } +} diff --git a/pool/shard001/C++/0023867_CISOBlob.cpp b/pool/shard001/C++/0023867_CISOBlob.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7fb5c2f4f6b32eb8f7d874751851ea288026099b --- /dev/null +++ b/pool/shard001/C++/0023867_CISOBlob.cpp @@ -0,0 +1,85 @@ +// Copyright 2010 Dolphin Emulator Project +// Licensed under GPLv2+ +// Refer to the license.txt file included. + +#include +#include +#include +#include + +#include "Common/CommonTypes.h" +#include "Common/File.h" +#include "DiscIO/CISOBlob.h" + +namespace DiscIO +{ +CISOFileReader::CISOFileReader(File::IOFile file) : m_file(std::move(file)) +{ + m_size = m_file.GetSize(); + + CISOHeader header; + m_file.Seek(0, SEEK_SET); + m_file.ReadArray(&header, 1); + + m_block_size = header.block_size; + + MapType count = 0; + for (u32 idx = 0; idx < CISO_MAP_SIZE; ++idx) + m_ciso_map[idx] = (1 == header.map[idx]) ? count++ : UNUSED_BLOCK_ID; +} + +std::unique_ptr CISOFileReader::Create(File::IOFile file) +{ + CISOHeader header; + if (file.Seek(0, SEEK_SET) && file.ReadArray(&header, 1) && header.magic == CISO_MAGIC) + return std::unique_ptr(new CISOFileReader(std::move(file))); + + return nullptr; +} + +u64 CISOFileReader::GetDataSize() const +{ + return static_cast(CISO_MAP_SIZE) * m_block_size; +} + +u64 CISOFileReader::GetRawSize() const +{ + return m_size; +} + +bool CISOFileReader::Read(u64 offset, u64 nbytes, u8* out_ptr) +{ + if (offset + nbytes > GetDataSize()) + return false; + + while (nbytes != 0) + { + u64 const block = offset / m_block_size; + u64 const data_offset = offset % m_block_size; + u64 const bytes_to_read = std::min(m_block_size - data_offset, nbytes); + + if (block < CISO_MAP_SIZE && UNUSED_BLOCK_ID != m_ciso_map[block]) + { + // calculate the base address + u64 const file_off = CISO_HEADER_SIZE + m_ciso_map[block] * (u64)m_block_size + data_offset; + + if (!(m_file.Seek(file_off, SEEK_SET) && m_file.ReadArray(out_ptr, bytes_to_read))) + { + m_file.Clear(); + return false; + } + } + else + { + std::fill_n(out_ptr, bytes_to_read, 0); + } + + out_ptr += bytes_to_read; + offset += bytes_to_read; + nbytes -= bytes_to_read; + } + + return true; +} + +} // namespace DiscIO diff --git a/pool/shard001/C++/0023876_Polygon3.cpp b/pool/shard001/C++/0023876_Polygon3.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d99c34cce811d0e235c5f689b416acaad05ed9d3 --- /dev/null +++ b/pool/shard001/C++/0023876_Polygon3.cpp @@ -0,0 +1,206 @@ +#include "csgjs/math/Polygon3.h" + +#include + +namespace csgjs { + Polygon::Polygon(const std::vector &v, const Plane &p) : _boundingSphereCacheValid(false), _boundingBoxCacheValid(false), vertices(v), plane(p) { +#ifdef CSGJS_DEBUG + if(!checkIfConvex()) { + std::cout << "not convex " << *this << std::endl; +// throw std::runtime_error("Not convex!"); + } +#endif + } + + Polygon::Polygon(std::vector &&v, const Plane &p) : _boundingSphereCacheValid(false), _boundingBoxCacheValid(false), vertices(v), plane(p) { +#ifdef CSGJS_DEBUG + if(!checkIfConvex()) { + std::cout << "not convex " << *this << std::endl; +// throw std::runtime_error("Not convex!"); + } +#endif + } + + Polygon::Polygon(const std::vector &v) : vertices(v), _boundingSphereCacheValid(false), _boundingBoxCacheValid(false) { + plane = Plane::fromVector3s(vertices[0].pos, vertices[1].pos, vertices[2].pos); +#ifdef CSGJS_DEBUG + if(!checkIfConvex()) { + std::cout << "not convex " << *this << std::endl; +// throw std::runtime_error("Not convex!"); + } +#endif + } + + Polygon::Polygon() : _boundingSphereCacheValid(false), _boundingBoxCacheValid(false) {} + + Polygon Polygon::flipped() const { + std::vector newVertices; + Plane newPlane = plane.flipped(); + + std::vector::const_reverse_iterator itr = vertices.rbegin(); + while(itr != vertices.rend()) { + newVertices.push_back(itr->flipped()); + ++itr; + } + + return Polygon(std::move(newVertices), newPlane); + } + + bool Polygon::checkIfDegenerateTriangle() const { + int numVertices = vertices.size(); + if(numVertices == 3) { + Vector3 v1 = (vertices[2].pos-vertices[0].pos); + Vector3 v2 = (vertices[1].pos-vertices[0].pos); + Vector3 v3 = (vertices[2].pos-vertices[1].pos); + + double a = v1.length(); + double b = v2.length(); + double c = v3.length(); + + if(a > c) { + double tmp = c; + c = a; + a = tmp; + } + + if(a > b) { + double tmp = b; + b = a; + a = tmp; + } + + if(b > c) { + double tmp = c; + c = b; + b = tmp; + } + + double d = a+b-c; + + return (d < EPS); + } + return false; + } + + bool Polygon::checkIfConvex() const { + int numVertices = vertices.size(); + if(numVertices > 2) { + Vector3 prevprevpos = vertices[numVertices-2].pos; + Vector3 prevpos = vertices[numVertices-1].pos; + for(int i = 0; i < numVertices; i++) { + Vector3 pos = vertices[i].pos; + if(!Polygon::isConvexPoint(prevprevpos, prevpos, pos, plane.normal)) { + return false; + } + prevprevpos = prevpos; + prevpos = pos; + } + } + return true; + } + + Polygon Polygon::transform(const Matrix4x4 &m) const { + std::vector verts(vertices); + std::vector::iterator itr = verts.begin(); + while(itr != verts.end()) { + *itr = itr->transform(m); + ++itr; + } + + if(m.isMirroring()) { + std::reverse(verts.begin(), verts.end()); + } + + return Polygon(std::move(verts), plane.transform(m)); + } + + bool Polygon::isConvexPoint(const Vector3 &prevpoint, const Vector3 &point, const Vector3 &nextpoint, const Vector3 normal) { + Vector3 crossproduct = (point-prevpoint).cross(nextpoint-point); + csgjs_real crossdotnormal = crossproduct.dot(normal); + return crossdotnormal >= 0; + } + + // seems like this caching scheme could be an unnecessary optimization, but + // this is how it was done in CSG.js, maybe try calculating the bounding box and sphere + // in the constructor to avoid any branching (it probably makes sense in JavaScript, + // but I question the benefit in C++). It would come down to how often polygons are + // constructed without ever needing a bounding box or sphere, which I'm not sure about. + std::pair Polygon::boundingBox() const { + if(!_boundingBoxCacheValid) { + std::vector::const_iterator itr = vertices.begin(); + + if(itr != vertices.end()) { + _boundingBoxCache.first = itr->pos; + _boundingBoxCache.second = itr->pos; + + while(itr != vertices.end()) { + _boundingBoxCache.first = _boundingBoxCache.first.min(itr->pos); + _boundingBoxCache.second = _boundingBoxCache.second.max(itr->pos); + ++itr; + } + _boundingBoxCacheValid = true; + + } else { + _boundingBoxCache.first = Vector3(0,0,0); + _boundingBoxCache.second = Vector3(0,0,0); + _boundingBoxCacheValid = true; + } + } + + return _boundingBoxCache; + } + + std::pair Polygon::boundingSphere() const { + if(!_boundingSphereCacheValid) { + std::pair box = boundingBox(); + _boundingSphereCache.first = .5*(box.first+box.second); + _boundingSphereCache.second = (box.second-_boundingSphereCache.first).length(); + _boundingSphereCacheValid = true; + } + + return _boundingSphereCache; + } + + PolygonEdgeData::PolygonEdgeData() : polygon(NULL) { + } + + PolygonEdgeData::PolygonEdgeData(Polygon *p, const Vector3 &a, const Vector3 &b) : polygon(p), first(a), second(b) { + } + + std::ostream& operator<<(std::ostream& os, const Polygon &poly) { + os << "Polygon - vertices: { "; + + std::vector::const_iterator itr = poly.vertices.begin(); + while(itr != poly.vertices.end()) { + os << *itr; + ++itr; + + if(itr != poly.vertices.end()) { + os << ", "; + } + } + os << " }, plane: { " << poly.plane << " }"; + + return os; + } + + std::ostream& operator<<(std::ostream& os, const std::pair &bounds) { + os << bounds.first << " - " << bounds.second; + return os; + } + + std::ostream& operator<<(std::ostream& os, const std::pair &bounds) { + os << bounds.first << " - " << bounds.second; + return os; + } + + std::ostream& operator<<(std::ostream& os, const std::vector &vertices) { + std::vector::const_iterator itr = vertices.begin(); + while(itr != vertices.end()) { + os << itr->pos << " "; + ++itr; + } + return os; + } +} + diff --git a/pool/shard001/C++/0023877_LanguagePackagesItem.cpp b/pool/shard001/C++/0023877_LanguagePackagesItem.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a90ce234ceb8f2000cf63c1859e516f948abc201 --- /dev/null +++ b/pool/shard001/C++/0023877_LanguagePackagesItem.cpp @@ -0,0 +1,135 @@ +/* + * This file is part of Manjaro Settings Manager. + * + * Ramon Buldó + * + * Manjaro Settings Manager 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. + * + * Manjaro Settings Manager 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 Manjaro Settings Manager. If not, see . + */ + +#include "LanguagePackagesItem.h" + +LanguagePackagesItem::LanguagePackagesItem() : + m_name( QByteArray() ), + m_languagePackage( QByteArray() ), + m_parentPackages( QList() ), + m_parentPkgInstalled( QList() ), + m_languagePkgInstalled( QList() ), + m_languagePkgAvailable( QList() ) +{ +} + +LanguagePackagesItem::LanguagePackagesItem( + const QByteArray& name, + const QByteArray& languagePackage, + const QList& parentPackages, + const QList& parentPkgInstalled, + const QList& languagePkgInstalled, + const QList& languagePkgAvailable ) + : m_name( name ), + m_languagePackage( languagePackage ), + m_parentPackages( parentPackages ), + m_parentPkgInstalled( parentPkgInstalled ), + m_languagePkgInstalled( languagePkgInstalled ), + m_languagePkgAvailable( languagePkgAvailable ) +{ +} + + +LanguagePackagesItem::~LanguagePackagesItem() +{ +} + + +QByteArray +LanguagePackagesItem::name() const +{ + return m_name; +} + + +void +LanguagePackagesItem::setName( const QByteArray& name ) +{ + m_name = name; +} + + +QByteArray +LanguagePackagesItem::languagePackage() const +{ + return m_languagePackage; +} + + +void +LanguagePackagesItem::setLanguagePackage( const QByteArray& languagePackage ) +{ + m_languagePackage = languagePackage; +} + + +QList +LanguagePackagesItem::parentPackages() const +{ + return m_parentPackages; +} + + +void +LanguagePackagesItem::setParentPackages( const QList& parentPackages ) +{ + m_parentPackages = parentPackages; +} + + +QList +LanguagePackagesItem::parentPkgInstalled() const +{ + return m_parentPkgInstalled; +} + + +void +LanguagePackagesItem::setParentPkgInstalled( const QList& parentPkgInstalled ) +{ + m_parentPkgInstalled = parentPkgInstalled; +} + + +QList +LanguagePackagesItem::languagePkgInstalled() const +{ + return m_languagePkgInstalled; +} + + +void +LanguagePackagesItem::setLanguagePkgInstalled( const QList& languagePkgInstalled ) +{ + m_languagePkgInstalled = languagePkgInstalled; +} + + +QList +LanguagePackagesItem::languagePkgAvailable() const +{ + return m_languagePkgAvailable; +} + + +void +LanguagePackagesItem::setLanguagePkgAvailable( const QList& languagePkgAvailable ) +{ + m_languagePkgAvailable = languagePkgAvailable; +} diff --git a/pool/shard001/C++/0023886_UDPServer.cpp b/pool/shard001/C++/0023886_UDPServer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3071297be38a76b5b4f76af9986e0ae3bc2ceb58 --- /dev/null +++ b/pool/shard001/C++/0023886_UDPServer.cpp @@ -0,0 +1,414 @@ +/************************************************************************/ +/* */ +/* UDPServer.cpp The C++ wrapper class for the deIP UDP server class */ +/* */ +/************************************************************************/ +/* Author: Keith Vogel */ +/* Copyright 2013, Digilent Inc. */ +/************************************************************************/ +/* DEIPcK deIP core network library +* +* Copyright (c) 2013-2014, Digilent +* Contact Digilent for the latest version. +* +* This program is free software; distributed under the terms of +* BSD 3-clause license ("Revised BSD License", "New BSD License", or "Modified 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 name(s) of the above-listed copyright holder(s) 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. +*/ +/************************************************************************/ +/* Module Description: */ +/* */ +/* Implements the UDPServer Class */ +/* */ +/************************************************************************/ +/* Revision History: */ +/* */ +/* 12/10/2013(KeithV): Created */ +/* */ +/************************************************************************/ +#include "DEIPcK.h" + +FFPT UDPServer::_ffptPeriodTask = {NULL, NULL}; + +/*** Prevent Copies +** +** Notes: +** +** These are private methods that prevent +** copying of the instance. They are +** dummy functions and are never used. +** +*/ +UDPServer::UDPServer(UDPServer& udpServer){}; + +/*** UDPServer Constructors +** +** Notes: +** +** Initialize a new UDPServer Instance and specify +** maximum number of sockets that it will use. +** Only 1 socket is listening at a time on the port +** however there may be many sockets pending and accept. +** Once all sockets are consumed by unaccepted clients +** UDPServer will stop listening on the port until +** a client is accepted and a socket opens up. +** +*/ +UDPServer::UDPServer() +{ + clear(); +} + +/*** UDPServer Destructor +** +** Notes: +** +** Shuts down all sockets and releases all resources +** +** +*/ +UDPServer::~UDPServer() +{ + close(); +} + +void UDPServer::clear(void) +{ + _ffptInfo._pNext = NULL; + _ffptInfo._this = this; + _pDEIPcK = NULL; + _listeningPort = portUnassigned; + memset(&_ffptSockets, 0, sizeof(FFPT)); +} + +/*** void UDPServer::close(void) +** +** Synopsis: +** Stops Listening and closes all unaccepted sockets/connections +** and clears everything back to it's originally constructed state. +** +** Parameters: +** None +** +** Return Values: +** None +** +** Errors: +** None +** +** Notes: +** +** Returns the UDPServer instance to +** a state just as if the instance had just been +** constructed. It also, Close all connections +** and releases all resources (sockets). +** +*/ +void UDPServer::close(void) +{ + FFLL * pffll = NULL; + + // pull this off the listening list + FFRemove(&_ffptPeriodTask, &_ffptInfo); + + // close and sockets added to the server + while((pffll = (FFLL *) FFOutPacket(&_ffptSockets)) != NULL) + { + ((UDPSocket *) (pffll->_this))->close(); + } + + clear(); +} + +bool UDPServer::addSocket(UDPSocket& udpSocket, IPSTATUS * pStatus) +{ + // if we don't have a page manager, assign the default one + if(udpSocket._hPMGR == NULL) + { + udpSocket._hPMGR = hNetworkPMGR; + } + + if(udpSocket._hPMGR == NULL) + { + AssignStatusSafely(pStatus, ipsNoPMGRGiven); + return(false); + } + else if(_pDEIPcK == NULL) + { + AssignStatusSafely(pStatus, ipsNotInitialized); + return(false); + } + else if(udpSocket._pDEIPcK != NULL) + { + AssignStatusSafely(pStatus, ipsInUse); + return(false); + } + + // add it to the list of sockets to listen on + FFInPacket(&_ffptSockets, &udpSocket._ffptInfo); + udpSocket._pDEIPcK = _pDEIPcK; + return(true); +} + +/*** int UDPServer::availableClients(void) +** +** Synopsis: +** Checks to see how many pending clients are availabe to be accepted. +** +** Parameters: +** None +** +** Return Values: +** The number of waiting TCPSockets to be accepted. +** +** Errors: +** None +** +** Notes: +** +** This is the workhorse of the UDPServer Class +** It will update pending clients if a connection is detected +** It will attempt to start listening if a socket comes avalialbe for listening +** It will clean up disconnected clients +*/ +int UDPServer::availableClients(int& cListening, IPSTATUS * pStatus) +{ + int cAvailable = 0; + cListening = 0; + + FFLL * pffllSocket = NULL; + + if(_pDEIPcK == NULL) + { + AssignStatusSafely(pStatus, ipsNotInitialized); + return(0); + } + + if(ILIsIPNetworkReady(_pDEIPcK->_pLLAdp, pStatus)) + { + while((pffllSocket = (FFLL *) FFNext(&_ffptSockets, pffllSocket)) != NULL) + { + UDPSocket& udpSocket = *((UDPSocket *) (pffllSocket->_this)); // for syntax sake + + if(udpSocket.available() > 0) + { + cAvailable++; + } + else if(udpSocket._socket.s.ipRemote.ipv4.u32 == IPv4Listen.u32) + { + cListening++; + } + } + } + return(cAvailable); +} + +/*** bool UDPServer::acceptClient(UDPSocket * pTCPSocket) +** bool UDPServer::acceptClient(UDPSocket * pTCPSocket, int index) +** bool UDPServer::acceptClient(UDPSocket * pTCPSocket, DEIPcK::STATUS * pStatus) +** bool UDPServer::acceptClient(UDPSocket * pTCPSocket, int index, DEIPcK::STATUS * pStatus) +** +** Synopsis: +** Removes a pending UDPSocket by accepting it from the server. +** +** Parameters: +** pTCPSocket A pointer to a newly constructed client UDPSocket +** +** index This is the zero based index of the client you want to accept. index must be less +** than what AvailableClients. +** +** pStatus A pointer to receive the status of AcceptClient +** +** Return Values: +** true if the UDPSocket was returned +** false if the UDPSocket could not be created +** +** Errors: +** None +** +** Notes: +** +** This call should be made immediately after AvailableClients or GetAvailableClientsRemoteEndPoint. +** Do not run PeriodicTasks between AvailableClients and this call because the client count could change. +** In order to keep the indexes within the range of AvailableClients and consistent with what GetAvailableClientsRemoteEndPoint +** returned, do not run AvailableClients or PeriodicTasks inbetween them. That is, do not run any stack task as that +** would change the AvailableClients count and order. +** +*/ +// We can get errors, you passed me a NULL, or an opened UDPSocket, or index out of range. +UDPSocket * UDPServer::acceptClient(int index) +{ + FFLL * pffllSocket = NULL; + int c = 0; + + while((pffllSocket = (FFLL *) FFNext(&_ffptSockets, pffllSocket)) != NULL) + { + UDPSocket& udpSocket = *((UDPSocket *) (pffllSocket->_this)); // for syntax sake + + if(udpSocket.available() > 0 && c == index) + { + FFRemove(&_ffptSockets, pffllSocket); + udpSocket._classState = ipsInUseW; + return(&udpSocket); + } + } + + return(NULL); +} + +/*** bool UDPServer::getAvailableClientsRemoteEndPoint(IPEndPoint *pRemoteEP, int index) +** bool UDPServer::getAvailableClientsRemoteEndPoint(IPEndPoint *pRemoteEP, MAC * pRemoteMAC, int index) +** +** Synopsis: +** Returns endpoint information about a UDPSocket waiting to be accepted. +** +** Parameters: +** pRemoteEP A pointer to an IPEndPoint to receive the remote endpoint information for the client +** waiting to be accepted. This may be NULL if you don't want the info +** +** pRemoteMAC A pointer to a MAC to receive the remote MAC address of the client waiting to be accepted. +** This will be the MAC address as known by ARP and will only have MAC address of machines +** on your local area network. If the IP is not local, the MAC will most probably be the MAC +** of your router. This may be NULL if you don't want the info +** +** index This is a zero based index and must be less than what AvailableClients returns. It +** selects the Client within the server list that you want remote endpoint information on. +** +** Return Values: +** true The local endpoint was returned. +** false An error occured, most likely your index was out of range +** +** Errors: +** None +** +** Notes: +** +** This allows you to determine if you want to accept this endpoint before removing it from +** the server. It allows you to accept other clients first and out of order. +** +** This call should be made immediately after AvailableClients and immediately before +** AcceptClient so that the servers pending list does not change due to another connection. +** +*/ +bool UDPServer::getAvailableClientsRemoteEndPoint(IPEndPoint& epRemote, int index) +{ + FFLL * pffllSocket = NULL; + int c = 0; + + while((pffllSocket = (FFLL *) FFNext(&_ffptSockets, pffllSocket)) != NULL) + { + UDPSocket& udpSocket = *((UDPSocket *) (pffllSocket->_this)); // for syntax sake + + if(udpSocket.available() > 0 && c == index) + { + return(udpSocket.getRemoteEndPoint(epRemote)); + } + } + + return(false); +} + +/*** bool UDPServer::getListeningEndPoint(IPEndPoint *pListeningEP) +** +** Synopsis: +** Gets the endpoint that the server is listening on. +** This is both the IP and port the server is on. +** +** Parameters: +** epLocal A pointer to an IPEndPoint to receive the local endpoint information. +** +** Return Values: +** true The local endpoint was returned. +** false The local endpoint is not known, usually because the connection was not set up yet. +** +** Errors: +** None +** +** Notes: +** +** If false is returned, then *pLocalEP will be garbage. +** +*/ +bool UDPServer::getListeningEndPoint(IPEndPoint& epLocal) +{ + if(_pDEIPcK != NULL && ILIsIPSetup(_pDEIPcK->_pLLAdp, NULL)) + { + ILGetMyIP(_pDEIPcK->_pLLAdp, &epLocal.ip); + epLocal.port = _listeningPort; + return(true); + } + + return(false); +} + +/*** void UDPServer::periodicTask(void) +** +** Synopsis: +** Gets the endpoint that the server is listening on. +** This is both the IP and port the server is on. +** +** Parameters: +** None +** +** Return Values: +** None +** +** Errors: +** None +** +** Notes: +** +** This will open up any new sockets for listening +** +*/ +void UDPServer::periodicTask(void) +{ + FFLL * pffllServer = NULL; + + // look at all of the server objects + while((pffllServer = (FFLL *) FFNext(&_ffptPeriodTask, pffllServer)) != NULL) + { + FFLL * pffllSocket = NULL; + UDPServer& udpServer = *((UDPServer *) (pffllServer->_this)); // for syntax sake + + if(ILIsIPSetup(udpServer._pDEIPcK->_pLLAdp, NULL)) + { + while((pffllSocket = (FFLL *) FFNext(&udpServer._ffptSockets, pffllSocket)) != NULL) + { + UDPSocket& udpSocket = *((UDPSocket *) (pffllSocket->_this)); // for syntax sake + + // start listening on available sockets + if(udpSocket._classState == ipsNotInitialized) + { + // get this listening + if(UDPOpenWithSocket(udpSocket._pDEIPcK->_pLLAdp, &udpSocket._socket, udpSocket._hPMGR, &IPListen, portListen, udpServer._listeningPort, NULL) == &udpSocket._socket) + { + udpSocket._classState = ipsListening; + } + } + } + } + } +} diff --git a/pool/shard001/C++/0023891_hsThread_Unix.cpp b/pool/shard001/C++/0023891_hsThread_Unix.cpp new file mode 100644 index 0000000000000000000000000000000000000000..011cb4ab661546ee18120b4e0d7da9ad1f2a3636 --- /dev/null +++ b/pool/shard001/C++/0023891_hsThread_Unix.cpp @@ -0,0 +1,205 @@ +/*==LICENSE==* + +CyanWorlds.com Engine - MMOG client, server and tools +Copyright (C) 2011 Cyan Worlds, Inc. + +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 . + +Additional permissions under GNU GPL version 3 section 7 + +If you modify this Program, or any covered work, by linking or +combining it with any of RAD Game Tools Bink SDK, Autodesk 3ds Max SDK, +NVIDIA PhysX SDK, Microsoft DirectX SDK, OpenSSL library, Independent +JPEG Group JPEG library, Microsoft Windows Media SDK, or Apple QuickTime SDK +(or a modified version of those libraries), +containing parts covered by the terms of the Bink SDK EULA, 3ds Max EULA, +PhysX SDK EULA, DirectX SDK EULA, OpenSSL and SSLeay licenses, IJG +JPEG Library README, Windows Media SDK EULA, or QuickTime SDK EULA, the +licensors of this Program grant you additional +permission to convey the resulting work. Corresponding Source for a +non-source form of such a combination shall include the source code for +the parts of OpenSSL and IJG JPEG Library used as well as that of the covered +work. + +You can contact Cyan Worlds, Inc. by email legal@cyan.com + or by snail mail at: + Cyan Worlds, Inc. + 14617 N Newport Hwy + Mead, WA 99021 + +*==LICENSE==*/ +#include "hsThread.h" +#include "hsExceptions.h" +#include +#include +#include +#include + +#define NO_POSIX_CLOCK 1 + +#if NO_POSIX_CLOCK +#include +#include +#define CLOCK_REALTIME 0 + +// +// A linux hack b/c we're not quite POSIX +// +int clock_gettime(int clocktype, struct timespec* ts) +{ + struct timezone tz; + struct timeval tv; + + int result = gettimeofday(&tv, &tz); + ts->tv_sec = tv.tv_sec; + ts->tv_nsec = tv.tv_usec * 1000 + 500; // sice we're losing accuracy round up by 500 nanos + + return result; +} + +#endif + +///////////////////////////////////////////////////////////////////////////// + +hsGlobalSemaphore::hsGlobalSemaphore(int initialValue, const char* name) +{ +#ifdef USE_SEMA + fPSema = nil; + if ((fNamed = (name != nil))) { + /* Named semaphore shared between processes */ + fPSema = sem_open(name, O_CREAT, 0666, initialValue); + if (fPSema == SEM_FAILED) + { + hsAssert(0, "hsOSException"); + throw hsOSException(errno); + } + } else { + /* Anonymous semaphore shared between threads */ + int shared = 0; // 1 if sharing between processes + fPSema = new sem_t; + int status = sem_init(fPSema, shared, initialValue); + hsThrowIfOSErr(status); + } +#else + int status = ::pthread_mutex_init(&fPMutex, nil); + hsThrowIfOSErr(status); + + status = ::pthread_cond_init(&fPCond, nil); + hsThrowIfOSErr(status); + + fCounter = initialValue; +#endif +} + +hsGlobalSemaphore::~hsGlobalSemaphore() +{ +#ifdef USE_SEMA + int status = 0; + if (fNamed) { + status = sem_close(fPSema); + } else { + status = sem_destroy(fPSema); + delete fPSema; + } + hsThrowIfOSErr(status); +#else + int status = ::pthread_cond_destroy(&fPCond); + hsThrowIfOSErr(status); + + status = ::pthread_mutex_destroy(&fPMutex); + hsThrowIfOSErr(status); +#endif +} + +bool hsGlobalSemaphore::Wait(hsMilliseconds timeToWait) +{ +#ifdef USE_SEMA // SHOULDN'T THIS USE timeToWait??!?!? -rje + // shouldn't this use sem_timedwait? -dpogue (2012-03-04) + hsAssert( timeToWait==kPosInfinity32, "sem_t does not support wait with timeout. #undef USE_SEMA and recompile." ); + int status = sem_wait(fPSema); + hsThrowIfOSErr(status); + return true; +#else + bool retVal = true; + int status = ::pthread_mutex_lock(&fPMutex); + hsThrowIfOSErr(status); + + if (timeToWait == kPosInfinity32) + { while (fCounter == 0) + { status = ::pthread_cond_wait(&fPCond, &fPMutex); + hsThrowIfOSErr(status); + } + } + else + { timespec spec; + int result; + + result = ::clock_gettime(CLOCK_REALTIME, &spec); + hsThrowIfFalse(result == 0); + + spec.tv_sec += timeToWait / 1000; + spec.tv_nsec += (timeToWait % 1000) * 1000 * 1000; + while (spec.tv_nsec >= 1000 * 1000 * 1000) + { spec.tv_sec += 1; + spec.tv_nsec -= 1000 * 1000 * 1000; + } + + while (fCounter == 0) + { status = ::pthread_cond_timedwait(&fPCond, &fPMutex, &spec); + if (status == ETIMEDOUT) + { retVal = false; + goto EXIT; + } + hsThrowIfOSErr(status); + } + } + + hsAssert(fCounter > 0, "oops"); + fCounter -= 1; +EXIT: + status = ::pthread_mutex_unlock(&fPMutex); + hsThrowIfOSErr(status); + return retVal; +#endif +} + +void hsGlobalSemaphore::Signal() +{ +#ifdef USE_SEMA + int status = sem_post(fPSema); + hsThrowIfOSErr(status); +#else + int status = ::pthread_mutex_lock(&fPMutex); + hsThrowIfOSErr(status); + + fCounter += 1; + + status = ::pthread_mutex_unlock(&fPMutex); + hsThrowIfOSErr(status); + + status = ::pthread_cond_signal(&fPCond); + hsThrowIfOSErr(status); +#endif +} + +void hsSleep::Sleep(uint32_t millis) +{ + uint32_t secs = millis / 1000; + if (secs > 0) + { + millis %= 1000; + ::sleep(secs); + } + usleep(millis*1000); +} diff --git a/pool/shard001/C++/0023893_ViewProviderTrajectory.cpp b/pool/shard001/C++/0023893_ViewProviderTrajectory.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bf1d90f4acf4ecc556975ab1c5ff22358d1567e8 --- /dev/null +++ b/pool/shard001/C++/0023893_ViewProviderTrajectory.cpp @@ -0,0 +1,167 @@ +/*************************************************************************** + * Copyright (c) 2008 Jürgen Riegel * + * * + * This file is part of the FreeCAD CAx development system. * + * * + * 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., 59 Temple Place, * + * Suite 330, Boston, MA 02111-1307, USA * + * * + ***************************************************************************/ + + +#include "PreCompiled.h" + +#ifndef _PreComp_ +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +#endif + +#include "ViewProviderTrajectory.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +using namespace Gui; +using namespace RobotGui; +using namespace Robot; + +PROPERTY_SOURCE(RobotGui::ViewProviderTrajectory, Gui::ViewProviderGeometryObject) + +ViewProviderTrajectory::ViewProviderTrajectory() +{ + + pcTrajectoryRoot = new Gui::SoFCSelection(); + pcTrajectoryRoot->highlightMode = Gui::SoFCSelection::OFF; + pcTrajectoryRoot->selectionMode = Gui::SoFCSelection::SEL_OFF; + //pcRobotRoot->style = Gui::SoFCSelection::BOX; + pcTrajectoryRoot->ref(); + + pcCoords = new SoCoordinate3(); + pcCoords->ref(); + pcDrawStyle = new SoDrawStyle(); + pcDrawStyle->ref(); + pcDrawStyle->style = SoDrawStyle::LINES; + pcDrawStyle->lineWidth = 2; + + pcLines = new SoLineSet; + pcLines->ref(); + + +} + +ViewProviderTrajectory::~ViewProviderTrajectory() +{ + pcTrajectoryRoot->unref(); + pcCoords->unref(); + pcDrawStyle->unref(); + pcLines->unref(); + +} + +void ViewProviderTrajectory::attach(App::DocumentObject *pcObj) +{ + ViewProviderDocumentObject::attach(pcObj); + + // Draw trajectory lines + SoSeparator* linesep = new SoSeparator; + SoBaseColor * basecol = new SoBaseColor; + basecol->rgb.setValue( 1.0f, 0.5f, 0.0f ); + linesep->addChild(basecol); + linesep->addChild(pcCoords); + linesep->addChild(pcLines); + + // Draw markers + SoBaseColor * markcol = new SoBaseColor; + markcol->rgb.setValue( 1.0f, 1.0f, 0.0f ); + SoMarkerSet* marker = new SoMarkerSet; + marker->markerIndex=Gui::Inventor::MarkerBitmaps::getMarkerIndex("CROSS", App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View")->GetInt("MarkerSize", 5)); + linesep->addChild(markcol); + linesep->addChild(marker); + + pcTrajectoryRoot->addChild(linesep); + + addDisplayMaskMode(pcTrajectoryRoot, "Waypoints"); + pcTrajectoryRoot->objectName = pcObj->getNameInDocument(); + pcTrajectoryRoot->documentName = pcObj->getDocument()->getName(); + pcTrajectoryRoot->subElementName = "Main"; + +} + +void ViewProviderTrajectory::setDisplayMode(const char* ModeName) +{ + if ( strcmp("Waypoints",ModeName)==0 ) + setDisplayMaskMode("Waypoints"); + ViewProviderGeometryObject::setDisplayMode( ModeName ); +} + +std::vector ViewProviderTrajectory::getDisplayModes(void) const +{ + std::vector StrList; + StrList.push_back("Waypoints"); + return StrList; +} + +void ViewProviderTrajectory::updateData(const App::Property* prop) +{ + Robot::TrajectoryObject* pcTracObj = static_cast(pcObject); + if (prop == &pcTracObj->Trajectory) { + const Trajectory &trak = pcTracObj->Trajectory.getValue(); + + pcCoords->point.deleteValues(0); + pcCoords->point.setNum(trak.getSize()); + + for(unsigned int i=0;ipoint.set1Value(i,pos.x,pos.y,pos.z); + + } + pcLines->numVertices.set1Value(0, trak.getSize()); + } + else if (prop == &pcTracObj->Base) { + Base::Placement loc = *(&pcTracObj->Base.getValue()); + } + +} + +void ViewProviderTrajectory::setupContextMenu(QMenu* menu, QObject* receiver, const char* member) +{ + QAction* act = menu->addAction(QObject::tr("Modify"), receiver, member); + act->setData(QVariant((int)ViewProvider::Default)); +} + diff --git a/pool/shard001/C++/0023894_media_player_extension_api.cc b/pool/shard001/C++/0023894_media_player_extension_api.cc new file mode 100644 index 0000000000000000000000000000000000000000..a573abe8fd6005940bc26bddcc36d73671f0459f --- /dev/null +++ b/pool/shard001/C++/0023894_media_player_extension_api.cc @@ -0,0 +1,76 @@ +// 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/values.h" +#include "chrome/browser/chromeos/media/media_player.h" +#include "chrome/browser/chromeos/media/media_player_extension_api.h" + +static const char kPropertyItems[] = "items"; +static const char kPropertyPosition[] = "position"; + +bool PlayMediaplayerFunction::RunImpl() { + if (args_->GetSize() < 2) { + return false; + } + + ListValue* url_list = NULL; + if (!args_->GetList(0, &url_list)) + return false; + + int position; + if (!args_->GetInteger(1, &position)) + return false; + + MediaPlayer* player = MediaPlayer::GetInstance(); + + player->PopupMediaPlayer(); + player->ClearPlaylist(); + + size_t len = url_list->GetSize(); + for (size_t i = 0; i < len; ++i) { + std::string path; + url_list->GetString(i, &path); + player->EnqueueMediaFileUrl(GURL(path)); + } + + player->SetPlaylistPosition(position); + player->NotifyPlaylistChanged(); + + return true; +} + +static ListValue* GetPlaylistItems() { + ListValue* result = new ListValue(); + + MediaPlayer::UrlVector const& src = MediaPlayer::GetInstance()->GetPlaylist(); + + for (size_t i = 0; i < src.size(); i++) { + result->Append(Value::CreateStringValue(src[i].spec())); + } + return result; +} + +bool GetPlaylistMediaplayerFunction::RunImpl() { + DictionaryValue* result = new DictionaryValue(); + MediaPlayer* player = MediaPlayer::GetInstance(); + + result->Set(kPropertyItems, GetPlaylistItems()); + result->SetInteger(kPropertyPosition, player->GetPlaylistPosition()); + + SetResult(result); + return true; +} + +bool SetWindowHeightMediaplayerFunction::RunImpl() { + int height; + if (!args_->GetInteger(0, &height)) + return false; + MediaPlayer::GetInstance()->SetWindowHeight(height); + return true; +} + +bool CloseWindowMediaplayerFunction::RunImpl() { + MediaPlayer::GetInstance()->CloseWindow(); + return true; +} diff --git a/pool/shard001/C++/0023895_dialog-manager.cpp b/pool/shard001/C++/0023895_dialog-manager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d427e3590c5bb74bd5a5f4569771cebdc142b9ef --- /dev/null +++ b/pool/shard001/C++/0023895_dialog-manager.cpp @@ -0,0 +1,288 @@ +/** + * @file + * Object for managing a set of dialogs, including their signals and + * construction/caching/destruction of them. + */ +/* Authors: + * Bryce W. Harrington + * Jon Phillips + * Gustav Broberg + * + * Copyright (C) 2004-2007 Authors + * + * Released under GNU GPL. Read the file 'COPYING' for more information. + */ + +#ifdef HAVE_CONFIG_H +# include +#endif + +#include "ui/dialog/dialog-manager.h" + +#include "ui/dialog/align-and-distribute.h" +#include "ui/dialog/document-metadata.h" +#include "ui/dialog/document-properties.h" +#include "ui/dialog/extension-editor.h" +#include "ui/dialog/fill-and-stroke.h" +#include "ui/dialog/filter-effects-dialog.h" +#include "ui/dialog/find.h" +#include "ui/dialog/glyphs.h" +#include "ui/dialog/inkscape-preferences.h" +#include "ui/dialog/input.h" +#include "ui/dialog/livepatheffect-editor.h" +#include "ui/dialog/memory.h" +#include "ui/dialog/messages.h" +#include "ui/dialog/symbols.h" +#include "ui/dialog/tile.h" +#include "ui/dialog/tracedialog.h" +#include "ui/dialog/pixelartdialog.h" +#include "ui/dialog/transformation.h" +#include "ui/dialog/undo-history.h" +#include "ui/dialog/panel-dialog.h" +#include "ui/dialog/layers.h" +#include "ui/dialog/icon-preview.h" +#include "ui/dialog/floating-behavior.h" +#include "ui/dialog/dock-behavior.h" +//#include "ui/dialog/print-colors-preview-dialog.h" +#include "util/ege-appear-time-tracker.h" +#include "preferences.h" +#include "ui/dialog/object-attributes.h" +#include "ui/dialog/object-properties.h" +#include "ui/dialog/text-edit.h" +#include "ui/dialog/spellcheck.h" +#include "ui/dialog/export.h" +#include "ui/dialog/xml-tree.h" +#include "ui/dialog/clonetiler.h" +#include "ui/dialog/svg-fonts-dialog.h" + +namespace Inkscape { +namespace UI { +namespace Dialog { + +namespace { + +using namespace Behavior; + +template +inline Dialog *create() { return PanelDialog::template create(); } + +} + +/** + * This class is provided as a container for Inkscape's various + * dialogs. This allows Inkscape::Application to treat the various + * dialogs it invokes, as abstractions. + * + * DialogManager is essentially a cache of dialogs. It lets us + * initialize dialogs lazily - instead of constructing them during + * application startup, they're constructed the first time they're + * actually invoked by Inkscape::Application. The constructed + * dialog is held here after that, so future invokations of the + * dialog don't need to get re-constructed each time. The memory for + * the dialogs are then reclaimed when the DialogManager is destroyed. + * + * In addition, DialogManager also serves as a signal manager for + * dialogs. It provides a set of signals that can be sent to all + * dialogs for doing things such as hiding/unhiding them, etc. + * DialogManager ensures that every dialog it handles will listen + * to these signals. + * + */ +DialogManager::DialogManager() { + + using namespace Behavior; + using namespace Inkscape::UI::Dialogs; // temporary + + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + int dialogs_type = prefs->getIntLimited("/options/dialogtype/value", DOCK, 0, 1); + + // The preferences dialog is broken, the DockBehavior code resizes it's floating window to the smallest size + registerFactory("InkscapePreferences", &create); + + if (dialogs_type == FLOATING) { + registerFactory("AlignAndDistribute", &create); + registerFactory("DocumentMetadata", &create); + registerFactory("DocumentProperties", &create); + registerFactory("ExtensionEditor", &create); + registerFactory("FillAndStroke", &create); + registerFactory("FilterEffectsDialog", &create); + registerFactory("Find", &create); + registerFactory("Glyphs", &create); + registerFactory("IconPreviewPanel", &create); + registerFactory("LayersPanel", &create); + registerFactory("LivePathEffect", &create); + registerFactory("Memory", &create); + registerFactory("Messages", &create); + registerFactory("ObjectAttributes", &create); + registerFactory("ObjectProperties", &create); +// registerFactory("PrintColorsPreviewDialog", &create); + registerFactory("SvgFontsDialog", &create); + registerFactory("Swatches", &create); + registerFactory("TileDialog", &create); + registerFactory("Symbols", &create); + registerFactory("Trace", &create); + registerFactory("PixelArt", &create); + registerFactory("Transformation", &create); + registerFactory("UndoHistory", &create); + registerFactory("InputDevices", &create); + registerFactory("TextFont", &create); + registerFactory("SpellCheck", &create); + registerFactory("Export", &create); + registerFactory("CloneTiler", &create); + registerFactory("XmlTree", &create); + + } else { + + registerFactory("AlignAndDistribute", &create); + registerFactory("DocumentMetadata", &create); + registerFactory("DocumentProperties", &create); + registerFactory("ExtensionEditor", &create); + registerFactory("FillAndStroke", &create); + registerFactory("FilterEffectsDialog", &create); + registerFactory("Find", &create); + registerFactory("Glyphs", &create); + registerFactory("IconPreviewPanel", &create); + registerFactory("LayersPanel", &create); + registerFactory("LivePathEffect", &create); + registerFactory("Memory", &create); + registerFactory("Messages", &create); + registerFactory("ObjectAttributes", &create); + registerFactory("ObjectProperties", &create); +// registerFactory("PrintColorsPreviewDialog", &create); + registerFactory("SvgFontsDialog", &create); + registerFactory("Swatches", &create); + registerFactory("TileDialog", &create); + registerFactory("Symbols", &create); + registerFactory("Trace", &create); + registerFactory("PixelArt", &create); + registerFactory("Transformation", &create); + registerFactory("UndoHistory", &create); + registerFactory("InputDevices", &create); + registerFactory("TextFont", &create); + registerFactory("SpellCheck", &create); + registerFactory("Export", &create); + registerFactory("CloneTiler", &create); + registerFactory("XmlTree", &create); + + } +} + +DialogManager::~DialogManager() { + // TODO: Disconnect the signals + // TODO: Do we need to explicitly delete the dialogs? + // Appears to cause a segfault if we do +} + + +DialogManager &DialogManager::getInstance() +{ + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + int dialogs_type = prefs->getIntLimited("/options/dialogtype/value", DOCK, 0, 1); + + /* Use singleton behavior for floating dialogs */ + if (dialogs_type == FLOATING) { + static DialogManager *instance = 0; + + if (!instance) + instance = new DialogManager(); + return *instance; + } + + return *new DialogManager(); +} + +/** + * Registers a dialog factory function used to create the named dialog. + */ +void DialogManager::registerFactory(gchar const *name, + DialogManager::DialogFactory factory) +{ + registerFactory(g_quark_from_string(name), factory); +} + +/** + * Registers a dialog factory function used to create the named dialog. + */ +void DialogManager::registerFactory(GQuark name, + DialogManager::DialogFactory factory) +{ + _factory_map[name] = factory; +} + +/** + * Fetches the named dialog, creating it if it has not already been + * created (assuming a factory has been registered for it). + */ +Dialog *DialogManager::getDialog(gchar const *name) { + return getDialog(g_quark_from_string(name)); +} + +/** + * Fetches the named dialog, creating it if it has not already been + * created (assuming a factory has been registered for it). + */ +Dialog *DialogManager::getDialog(GQuark name) { + DialogMap::iterator dialog_found; + dialog_found = _dialog_map.find(name); + + Dialog *dialog=NULL; + if ( dialog_found != _dialog_map.end() ) { + dialog = dialog_found->second; + } else { + FactoryMap::iterator factory_found; + factory_found = _factory_map.find(name); + + if ( factory_found != _factory_map.end() ) { + dialog = factory_found->second(); + _dialog_map[name] = dialog; + } + } + + return dialog; +} + +/** + * Shows the named dialog, creating it if necessary. + */ +void DialogManager::showDialog(gchar const *name, bool grabfocus) { + showDialog(g_quark_from_string(name), grabfocus); +} + +/** + * Shows the named dialog, creating it if necessary. + */ +void DialogManager::showDialog(GQuark name, bool grabfocus) { + bool wantTiming = Inkscape::Preferences::get()->getBool("/dialogs/debug/trackAppear", false); + GTimer *timer = (wantTiming) ? g_timer_new() : 0; // if needed, must be created/started before getDialog() + Dialog *dialog = getDialog(name); + if ( dialog ) { + if ( wantTiming ) { + gchar const * nameStr = g_quark_to_string(name); + ege::AppearTimeTracker *tracker = new ege::AppearTimeTracker(timer, dialog->gobj(), nameStr); + tracker->setAutodelete(true); + timer = 0; + } + if (grabfocus) + dialog->present(); + } + + if ( timer ) { + g_timer_destroy(timer); + timer = 0; + } +} + +} // namespace Dialog +} // namespace UI +} // namespace Inkscape + +/* + Local Variables: + mode:c++ + c-file-style:"stroustrup" + c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) + indent-tabs-mode:nil + fill-column:99 + End: +*/ +// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : diff --git a/pool/shard001/C++/0023909_lua_vector_common.cpp b/pool/shard001/C++/0023909_lua_vector_common.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e1f0fb7876a19f9fd2bdd4e19c67396f80010ffb --- /dev/null +++ b/pool/shard001/C++/0023909_lua_vector_common.cpp @@ -0,0 +1,101 @@ +//#include +#include +#include +#include +#include +#include +//#include +#include "lua.hpp" + +#include "def.hpp" +#include "Naming.hpp" +#include "RuntimeNames.hpp" +#include "StateSynchrony.hpp" +#include "interfaces/ILogger.hpp" +#include "LoggingSystem.hpp" +#include "ParameterValue.hpp" +#include "ParameterType.hpp" +#include "types/LuaFunctionWrapper.hpp" +#include "ParameterTypeSystem.hpp" +#include "TypeLookup.hpp" +#include "ParameterValueCollection.hpp" +#include "Module.hpp" +#include "EntryPoint.hpp" +#include "EntryPointSystem.hpp" +#include "ChimeraSystem.hpp" +#include "ModuleLoader.hpp" +#include "ChimeraRuntime.hpp" +#include "types/lua_static.hpp" +#include "lua/types/vector/lua_vector_common.hpp" + +static int meta_pid_vector = 0; + +void chimera::runtime::types::push_vector_library(lua_State* const L, size_t pid_vector) +{ + meta_pid_vector = pid_vector; + void** lib = (void**)lua_newuserdata(L, sizeof(void*)); + *lib = nullptr; + lua_newtable(L); + lua_pushcfunction (L, chimera::lua_ignore_newindex); + lua_setfield(L, -2, "__newindex"); + lua_pushstring (L, "Library"); + lua_setfield(L, -2, "__name"); + lua_pushinteger (L, chimera::systemtypes::PID_LIBRARAY); + lua_setfield(L, -2, "__type"); + lua_pushcfunction (L, lua_vector_new); + lua_setfield(L, -2, "__call"); + lua_pushstring(L, "__index"); + lua_newtable(L); + //lua_pushcfunction (L, lua_vector_base); + //lua_setfield(L, -2, "base"); + lua_rawset(L, -3); + lua_setmetatable(L, -2); +} + +int chimera::runtime::types::lua_vector_new(lua_State* const L) +{ + // TODO (kekstoaster#1#): add copy vector if 1st element is vector + if(lua_gettop(L) != 3) + { +#warning LOG (kekstoaster#1#): vector.new requires 2 arguments + //LoggingSystem::Error("vector.new requires 2 arguments"); + return 0; + } + if(!lua_isinteger(L, 2)) + { +#warning LOG (kekstoaster#1#): argument `1` to vector.new is not an integer number + //LoggingSystem::Error("argument `1` to vector.new is not an integer number"); + return 0; + } + int a = lua_tointeger(L, 2); + + if(a <= 0) + { +#warning LOG (kekstoaster#1#): attempt to create invalid vector in vector.new (dimension <= 0) + //LoggingSystem::Error("attempt to create invalid vector in vector.new (dimension <= 0)"); + return 0; + } + + ChimeraRuntime* chimeraSystem = (ChimeraRuntime*)(*((void**)lua_getextraspace(L))); + + size_t innerType = chimeraSystem->getTypeSystem()->getParameterType(L, 3); + size_t metaType = chimeraSystem->getTypeLookup()->findType(meta_pid_vector, innerType); + + if(metaType != 0) + { + lua_pushstring(L, chimera::registrynames::LUA_REGISTRY_CHIMERA_METATABLES); + lua_rawget(L, LUA_REGISTRYINDEX); + lua_rawgeti(L, -1, metaType); + + if(lua_getfield(L, -1, "__new") == LUA_TFUNCTION) + { + lua_pushvalue(L, 2); + lua_pushvalue(L, 3); + lua_call(L, 2, 1); + return 1; + } + } +#warning LOG (kekstoaster#1#): vector type is not supported + //LoggingSystem::Error("vector type is not supported"); + return 0; +} diff --git a/pool/shard001/C++/0023917_SerializedCells.cc b/pool/shard001/C++/0023917_SerializedCells.cc new file mode 100644 index 0000000000000000000000000000000000000000..c44e60adced8073c77c82b42ac3dcc36f0b67d47 --- /dev/null +++ b/pool/shard001/C++/0023917_SerializedCells.cc @@ -0,0 +1,91 @@ +/** + * Copyright (C) 2007-2016 Hypertable, Inc. + * + * This file is part of Hypertable. + * + * Hypertable 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. + * + * Hypertable 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 Hypertable. If not, see + */ +#include "Common/Compat.h" + +#include "../ThriftBroker/SerializedCellsReader.h" +#include "../ThriftBroker/SerializedCellsWriter.h" + +#include + +using namespace Hypertable; +using namespace boost::python; + +typedef bool (SerializedCellsWriter::*addfn)(const char *row, + const char *column_family, const char *column_qualifier, + int64_t timestamp, const char *value, int32_t value_length, + int cell_flag); +typedef const char *(SerializedCellsWriter::*getfn)(); +typedef int32_t (SerializedCellsWriter::*getlenfn)(); + +static addfn afn = &Hypertable::SerializedCellsWriter::add; +static getlenfn lenfn = &Hypertable::SerializedCellsWriter::get_buffer_length; + +static PyObject *convert(const SerializedCellsWriter &scw) { + boost::python::object obj(handle<>(PyBuffer_FromMemory( + (void *)scw.get_buffer(), scw.get_buffer_length()))); + return boost::python::incref(obj.ptr()); +} + +BOOST_PYTHON_MODULE(libHyperPython) +{ + + class_("Cell") + .def("sanity_check", &Cell::sanity_check) + .def_readwrite("row", &Cell::row_key) + .def_readwrite("column_family", &Cell::column_family) + .def_readwrite("column_qualifier", &Cell::column_qualifier) + .def_readwrite("timestamp", &Cell::timestamp) + .def_readwrite("revision", &Cell::revision) + .def_readwrite("value", &Cell::value) + .def_readwrite("flag", &Cell::flag) + .def(self_ns::str(self_ns::self)) + ; + + class_("SerializedCellsReader", + init()) + .def("has_next", &SerializedCellsReader::next) + .def("get_cell", &SerializedCellsReader::get_cell, + return_value_policy()) + .def("row", &SerializedCellsReader::row, + return_value_policy()) + .def("column_family", &SerializedCellsReader::column_family, + return_value_policy()) + .def("column_qualifier", &SerializedCellsReader::column_qualifier, + return_value_policy()) + .def("value", &SerializedCellsReader::value_str, + return_value_policy()) + .def("value_len", &SerializedCellsReader::value_len) + .def("value_str", &SerializedCellsReader::value_str, + return_value_policy()) + .def("timestamp", &SerializedCellsReader::timestamp) + .def("cell_flag", &SerializedCellsReader::cell_flag) + .def("flush", &SerializedCellsReader::flush) + .def("eos", &SerializedCellsReader::eos) + ; + + class_("SerializedCellsWriter", + init()) + .def("add", afn) + .def("finalize", &SerializedCellsWriter::finalize) + .def("empty", &SerializedCellsWriter::empty) + .def("clear", &SerializedCellsWriter::clear) + .def("__len__", lenfn) + .def("get", &convert) + ; +} diff --git a/pool/shard001/C++/0023920_move2.pass.cpp b/pool/shard001/C++/0023920_move2.pass.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e452ac98c49e8e347aeb5a23017272503a901a27 --- /dev/null +++ b/pool/shard001/C++/0023920_move2.pass.cpp @@ -0,0 +1,65 @@ +//===----------------------------------------------------------------------===// +// +// The LLVM Compiler Infrastructure +// +// This file is dual licensed under the MIT and the University of Illinois Open +// Source Licenses. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +// +// UNSUPPORTED: libcpp-has-no-threads +// UNSUPPORTED: c++98, c++03 + +// + +// class thread + +// thread& operator=(thread&& t); + +#include +#include +#include +#include + +class G +{ + int alive_; +public: + static int n_alive; + static bool op_run; + + G() : alive_(1) {++n_alive;} + G(const G& g) : alive_(g.alive_) {++n_alive;} + ~G() {alive_ = 0; --n_alive;} + + + + void operator()(int i, double j) + { + assert(alive_ == 1); + assert(n_alive >= 1); + assert(i == 5); + assert(j == 5.5); + op_run = true; + } +}; + +int G::n_alive = 0; +bool G::op_run = false; + +void f1() +{ + std::_Exit(0); +} + +int main() +{ + std::set_terminate(f1); + { + G g; + std::thread t0(g, 5, 5.5); + std::thread t1; + t0 = std::move(t1); + assert(false); + } +} diff --git a/pool/shard001/C++/0023921_TopologyFactoryFile.cpp b/pool/shard001/C++/0023921_TopologyFactoryFile.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4fd0db150e0becb1f9bc8b44fe986ca3f1e8ebfe --- /dev/null +++ b/pool/shard001/C++/0023921_TopologyFactoryFile.cpp @@ -0,0 +1,96 @@ +/****************************************************************************** + + source file TopologyFactoryFile.cpp with implementation of + createTopologyFile + + Author : T. Kleiberg + Version: 1 + Date : Mar 2007 + +******************************************************************************/ + +//------------------------------------------------------------------------------ +// Create a topology from file +// +// createTopologyFile() +//------------------------------------------------------------------------------ + +Topology* TopologyFactory::createTopologyFile(const TString &description) +{ + TRACE("TopologyFactory::createTopologyFile -->"); + + Topology* result = new Topology(); + result->input_type = 0; + result->is_directed = false; + //result->lcf_visitor = (LinkCostFunctionVisitor*) 0; + + FileReader fr(description.at(1)); + { // read headers + TString line; + + // read #nodes, #edgenodex, #qos + fr.firstLine(line); + result->number_of_nodes = atoi(line.at(0).c_str()); + int number_of_edgenodes = atoi(line.at(1).c_str()); + result->number_of_qos = atoi(line.at(2).c_str()); + if (line.size() > 3) + { + result->input_type = atoi(line.at(3).c_str()); + } + if (line.size() > 4) + { + result->is_directed = (bool) atoi(line.at(4).c_str()); + } + + // read edgenodes list + if (number_of_edgenodes > 0) + { + fr.nextLine(line); + for(std::size_t index=0;indexedge_nodes.push_back(atoi(line.at(index).c_str() )); + } + } + } //end: block + result->link_list = new LinkList(result->number_of_nodes); + + // read links and traffic matrix + for (TString line; fr.nextLine(line); ) + { + if (line.size() == 3 && result->input_type==1) // traffic matrix + { + result->f_src.push_back(atoi(line.at(0).c_str())); + result->f_dest.push_back(atoi(line.at(1).c_str())); + result->f_reqc.push_back(atof(line.at(2).c_str())); + } // line,size == 3 + else + { // length = #values per link, i.e. src, dst, cost, capacity & #qos + IntVector cost; + cost.push_back(atoi(line.at(0).c_str() )); // src + cost.push_back(atoi(line.at(1).c_str() )); // dst + cost.push_back(atoi(line.at(2).c_str() )); // cost + result->cost_list.push_back(cost); + + DblVector link; + link.push_back(cost[0]); // src + link.push_back(cost[1]); // dst + link.push_back(0.0); // core + link.push_back(cost[3]); // cap + for(std::size_t index= 4; index < line.size(); ++index) + { + link.push_back(atof( line.at(index).c_str() )); + } + result->link_list->insert(link); + if (!result->is_directed) + { + DblVector rlink(link); + rlink[0] = link[1]; + rlink[1] = link[0]; + result->link_list->insert(rlink); + } + } // line.size != 3 + } + TRACE("TopologyFactory::createTopologyFile <--"); + return result; +} + diff --git a/pool/shard001/C++/0023927_browsing_data_local_storage_helper_browsertest.cc b/pool/shard001/C++/0023927_browsing_data_local_storage_helper_browsertest.cc new file mode 100644 index 0000000000000000000000000000000000000000..1dad27a89c7ac19d083be577218239327c29460a --- /dev/null +++ b/pool/shard001/C++/0023927_browsing_data_local_storage_helper_browsertest.cc @@ -0,0 +1,188 @@ +// 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/browsing_data/browsing_data_local_storage_helper.h" + +#include + +#include "base/basictypes.h" +#include "base/bind.h" +#include "base/bind_helpers.h" +#include "base/callback.h" +#include "base/files/file_enumerator.h" +#include "base/files/file_path.h" +#include "base/files/file_util.h" +#include "base/memory/ref_counted.h" +#include "base/strings/utf_string_conversions.h" +#include "base/test/thread_test_helper.h" +#include "base/threading/sequenced_worker_pool.h" +#include "chrome/browser/browsing_data/browsing_data_helper_browsertest.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/ui/browser.h" +#include "chrome/test/base/in_process_browser_test.h" +#include "content/public/browser/dom_storage_context.h" +#include "content/public/test/test_utils.h" +#include "testing/gtest/include/gtest/gtest.h" + +using content::BrowserContext; +using content::BrowserThread; +using content::DOMStorageContext; + +namespace { +typedef + BrowsingDataHelperCallback + TestCompletionCallback; + +const base::FilePath::CharType kTestFile0[] = + FILE_PATH_LITERAL("http_www.chromium.org_0.localstorage"); + +const char kOriginOfTestFile0[] = "http://www.chromium.org/"; + +const base::FilePath::CharType kTestFile1[] = + FILE_PATH_LITERAL("http_www.google.com_0.localstorage"); + +const base::FilePath::CharType kTestFileInvalid[] = + FILE_PATH_LITERAL("http_www.google.com_localstorage_0.foo"); + +// This is only here to test that extension state is not listed by the helper. +const base::FilePath::CharType kTestFileExtension[] = FILE_PATH_LITERAL( + "chrome-extension_behllobkkfkfnphdnhnkndlbkcpglgmj_0.localstorage"); + +class BrowsingDataLocalStorageHelperTest : public InProcessBrowserTest { + protected: + void CreateLocalStorageFilesForTest() { + // Note: This helper depends on details of how the dom_storage library + // stores data in the host file system. + base::FilePath storage_path = GetLocalStoragePathForTestingProfile(); + base::CreateDirectory(storage_path); + const base::FilePath::CharType* kFilesToCreate[] = { + kTestFile0, kTestFile1, kTestFileInvalid, kTestFileExtension + }; + for (size_t i = 0; i < arraysize(kFilesToCreate); ++i) { + base::FilePath file_path = storage_path.Append(kFilesToCreate[i]); + base::WriteFile(file_path, nullptr, 0); + } + } + + base::FilePath GetLocalStoragePathForTestingProfile() { + return browser()->profile()->GetPath().AppendASCII("Local Storage"); + } +}; + +// This class is notified by BrowsingDataLocalStorageHelper on the UI thread +// once it finishes fetching the local storage data. +class StopTestOnCallback { + public: + explicit StopTestOnCallback( + BrowsingDataLocalStorageHelper* local_storage_helper) + : local_storage_helper_(local_storage_helper) { + DCHECK(local_storage_helper_); + } + + void Callback( + const std::list& + local_storage_info) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + // There's no guarantee on the order, ensure these files are there. + const char* const kTestHosts[] = {"www.chromium.org", "www.google.com"}; + bool test_hosts_found[arraysize(kTestHosts)] = {false, false}; + ASSERT_EQ(arraysize(kTestHosts), local_storage_info.size()); + for (size_t i = 0; i < arraysize(kTestHosts); ++i) { + for (const auto& info : local_storage_info) { + ASSERT_TRUE(info.origin_url.SchemeIs("http")); + if (info.origin_url.host() == kTestHosts[i]) { + ASSERT_FALSE(test_hosts_found[i]); + test_hosts_found[i] = true; + } + } + } + for (size_t i = 0; i < arraysize(kTestHosts); ++i) { + ASSERT_TRUE(test_hosts_found[i]) << kTestHosts[i]; + } + base::MessageLoop::current()->Quit(); + } + + private: + BrowsingDataLocalStorageHelper* local_storage_helper_; +}; + +IN_PROC_BROWSER_TEST_F(BrowsingDataLocalStorageHelperTest, CallbackCompletes) { + scoped_refptr local_storage_helper( + new BrowsingDataLocalStorageHelper(browser()->profile())); + CreateLocalStorageFilesForTest(); + StopTestOnCallback stop_test_on_callback(local_storage_helper.get()); + local_storage_helper->StartFetching(base::Bind( + &StopTestOnCallback::Callback, base::Unretained(&stop_test_on_callback))); + // Blocks until StopTestOnCallback::Callback is notified. + content::RunMessageLoop(); +} + +IN_PROC_BROWSER_TEST_F(BrowsingDataLocalStorageHelperTest, DeleteSingleFile) { + scoped_refptr local_storage_helper( + new BrowsingDataLocalStorageHelper(browser()->profile())); + CreateLocalStorageFilesForTest(); + local_storage_helper->DeleteOrigin(GURL(kOriginOfTestFile0)); + content::RunAllBlockingPoolTasksUntilIdle(); + + // Ensure the file has been deleted. + base::FileEnumerator file_enumerator( + GetLocalStoragePathForTestingProfile(), + false, + base::FileEnumerator::FILES); + int num_files = 0; + for (base::FilePath file_path = file_enumerator.Next(); + !file_path.empty(); + file_path = file_enumerator.Next()) { + ASSERT_FALSE(base::FilePath(kTestFile0) == file_path.BaseName()); + ++num_files; + } + ASSERT_EQ(3, num_files); +} + +IN_PROC_BROWSER_TEST_F(BrowsingDataLocalStorageHelperTest, + CannedAddLocalStorage) { + const GURL origin1("http://host1:1/"); + const GURL origin2("http://host2:1/"); + + scoped_refptr helper( + new CannedBrowsingDataLocalStorageHelper(browser()->profile())); + helper->AddLocalStorage(origin1); + helper->AddLocalStorage(origin2); + + TestCompletionCallback callback; + helper->StartFetching( + base::Bind(&TestCompletionCallback::callback, + base::Unretained(&callback))); + + std::list result = + callback.result(); + + ASSERT_EQ(2u, result.size()); + std::list::iterator info = + result.begin(); + EXPECT_EQ(origin1, info->origin_url); + info++; + EXPECT_EQ(origin2, info->origin_url); +} + +IN_PROC_BROWSER_TEST_F(BrowsingDataLocalStorageHelperTest, CannedUnique) { + const GURL origin("http://host1:1/"); + + scoped_refptr helper( + new CannedBrowsingDataLocalStorageHelper(browser()->profile())); + helper->AddLocalStorage(origin); + helper->AddLocalStorage(origin); + + TestCompletionCallback callback; + helper->StartFetching( + base::Bind(&TestCompletionCallback::callback, + base::Unretained(&callback))); + + std::list result = + callback.result(); + + ASSERT_EQ(1u, result.size()); + EXPECT_EQ(origin, result.begin()->origin_url); +} +} // namespace diff --git a/pool/shard001/C++/0023942_ResNode.cpp b/pool/shard001/C++/0023942_ResNode.cpp new file mode 100644 index 0000000000000000000000000000000000000000..61a3475bdcdd6515a20d27537c91dab9b92c9ad4 --- /dev/null +++ b/pool/shard001/C++/0023942_ResNode.cpp @@ -0,0 +1,65 @@ +#include "ResNode.h" + + +namespace tzw +{ + ResNode::ResNode() + { + auto atr = addOut(u8"Self"); + atr->m_localAttrValue.setUsrPtr(this); + } + + void ResNode::syncName() + { + + } + + GamePart* ResNode::getProxy() + { + return nullptr; + } + + + void ResNode::handleNameEdit() + { + if(getProxy()) + { + char a[128] = ""; + strcpy(a, getProxy()->getName().c_str()); + ImGui::PushItemWidth(80); + bool isInputName = ImGui::InputText(TRC(u8"Ãû³Æ"),a,128); + ImGui::PopItemWidth(); + if(isInputName) + { + getProxy()->setName(a); + syncName(); + } + } + + } + + vec3 ResNode::getNodeColor() + { + return vec3(95.0f/ 255.0f, 127.0f/255.0f, 90.0f / 255.0f); + } + + int ResNode::getType() + { + return Node_TYPE_RES; + } + + std::string ResNode::getResType() + { + return "baseRes"; + } + + void ResNode::dump(rapidjson::Value& partDocObj, rapidjson::Document::AllocatorType& allocator) + { + GraphNode::dump(partDocObj, allocator); + partDocObj.AddMember("Type", std::string("Resource"), allocator); + partDocObj.AddMember("ResType", getResType(), allocator); + partDocObj.AddMember("ResUID", std::string(getProxy()->getGUID()), allocator); + partDocObj.AddMember("UID", std::string(getGUID()), allocator); + + } +} diff --git a/pool/shard001/C++/0023943_DialogEx.cpp b/pool/shard001/C++/0023943_DialogEx.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c0156f1ab7e2c757cfb7d8da5e929ae7ad9fbe92 --- /dev/null +++ b/pool/shard001/C++/0023943_DialogEx.cpp @@ -0,0 +1,109 @@ +// Copyleft 2004 Chris Korda +// 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 any later version. +/* + chris korda + + revision history: + rev date comments + 00 19apr04 initial version + 01 05oct04 no more child dialogs; remove OnNcActivate + 02 07oct04 override EnableToolTips to make it virtual + + customized dialog base class + +*/ + +// DialogEx.cpp : implementation file +// + +#include "stdafx.h" +#include "Resource.h" +#include "DialogEx.h" + +#ifdef _DEBUG +#define new DEBUG_NEW +#undef THIS_FILE +static char THIS_FILE[] = __FILE__; +#endif + +///////////////////////////////////////////////////////////////////////////// +// CDialogEx dialog + +CDialogEx::CDialogEx(UINT nIDTemplate, UINT nIDAccel, CWnd* pParent /*=NULL*/) + : CDialog(nIDTemplate, pParent) +{ + //{{AFX_DATA_INIT(CDialogEx) + //}}AFX_DATA_INIT + m_Parent = NULL; + m_Accel = LOADACCEL(nIDAccel); +} + +CDialogEx::~CDialogEx() +{ + DestroyWindow(); +} + +void CDialogEx::DoDataExchange(CDataExchange* pDX) +{ + CDialog::DoDataExchange(pDX); + //{{AFX_DATA_MAP(CDialogEx) + //}}AFX_DATA_MAP +} + +void CDialogEx::SetParent(CWnd *Parent) +{ + m_Parent = Parent; + CDialog::SetParent(Parent); +} + +void CDialogEx::CenterWindowEx(const CPoint& Offset, bool Repaint) +{ + if (m_Parent == NULL) + return; + // center dialog's top left corner within parent window + CRect vr, dr; + m_Parent->GetClientRect(vr); + GetWindowRect(dr); + MoveWindow(vr.Width() / 2 + Offset.x, vr.Height() / 2 + Offset.y, + dr.Width(), dr.Height(), Repaint); +} + +BOOL CDialogEx::EnableToolTips(BOOL bEnable) +{ + return(CDialog::EnableToolTips(bEnable)); +} + +BEGIN_MESSAGE_MAP(CDialogEx, CDialog) + //{{AFX_MSG_MAP(CDialogEx) + ON_WM_HSCROLL() + ON_WM_CLOSE() + ON_WM_SHOWWINDOW() + //}}AFX_MSG_MAP + ON_NOTIFY_EX(TTN_NEEDTEXT, 0, OnToolTip) +END_MESSAGE_MAP() + +///////////////////////////////////////////////////////////////////////////// +// CDialogEx message handlers + +BOOL CDialogEx::PreTranslateMessage(MSG* pMsg) +{ + if (pMsg->message >= WM_KEYFIRST && pMsg->message <= WM_KEYLAST) { + if (TranslateAccelerator(m_hWnd, m_Accel, pMsg)) + return(TRUE); + } + return CDialog::PreTranslateMessage(pMsg); +} + +BOOL CDialogEx::OnToolTip(UINT id, NMHDR* pTTTStruct, LRESULT* pResult) +{ + LPNMTTDISPINFO ttp = LPNMTTDISPINFO(pTTTStruct); + UINT nID = ttp->hdr.idFrom; + if (ttp->uFlags & TTF_IDISHWND) // idFrom can be HWND or ID + nID = ::GetDlgCtrlID((HWND)nID); + CString s; + s.LoadString(nID); + strcpy(ttp->szText, s); + return(TRUE); +} diff --git a/pool/shard001/C++/0023945_is_many.pass.cpp b/pool/shard001/C++/0023945_is_many.pass.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5caf8cfaf3a6b646da386e5270984acd77e1572e --- /dev/null +++ b/pool/shard001/C++/0023945_is_many.pass.cpp @@ -0,0 +1,121 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +// + +// template <> class ctype; + +// const char* is(const char* low, const char* high, mask* vec) const; + +#include +#include +#include +#include + +#include + +#include "test_macros.h" + +int main(int, char**) +{ + std::locale l = std::locale::classic(); + { + typedef std::ctype F; + const F& f = std::use_facet(l); + const std::string in(" A\x07.a1"); + std::vector m(in.size()); + const char* h = f.is(in.data(), in.data() + in.size(), m.data()); + assert(h == in.data() + in.size()); + + // ' ' + assert( (m[0] & F::space)); + assert( (m[0] & F::print)); + assert(!(m[0] & F::cntrl)); + assert(!(m[0] & F::upper)); + assert(!(m[0] & F::lower)); + assert(!(m[0] & F::alpha)); + assert(!(m[0] & F::digit)); + assert(!(m[0] & F::punct)); + assert(!(m[0] & F::xdigit)); + assert( (m[0] & F::blank)); + assert(!(m[0] & F::alnum)); + assert(!(m[0] & F::graph)); + + // 'A' + assert(!(m[1] & F::space)); + assert( (m[1] & F::print)); + assert(!(m[1] & F::cntrl)); + assert( (m[1] & F::upper)); + assert(!(m[1] & F::lower)); + assert( (m[1] & F::alpha)); + assert(!(m[1] & F::digit)); + assert(!(m[1] & F::punct)); + assert( (m[1] & F::xdigit)); + assert(!(m[1] & F::blank)); + assert( (m[1] & F::alnum)); + assert( (m[1] & F::graph)); + + // '\x07' + assert(!(m[2] & F::space)); + assert(!(m[2] & F::print)); + assert( (m[2] & F::cntrl)); + assert(!(m[2] & F::upper)); + assert(!(m[2] & F::lower)); + assert(!(m[2] & F::alpha)); + assert(!(m[2] & F::digit)); + assert(!(m[2] & F::punct)); + assert(!(m[2] & F::xdigit)); + assert(!(m[2] & F::blank)); + assert(!(m[2] & F::alnum)); + assert(!(m[2] & F::graph)); + + // '.' + assert(!(m[3] & F::space)); + assert( (m[3] & F::print)); + assert(!(m[3] & F::cntrl)); + assert(!(m[3] & F::upper)); + assert(!(m[3] & F::lower)); + assert(!(m[3] & F::alpha)); + assert(!(m[3] & F::digit)); + assert( (m[3] & F::punct)); + assert(!(m[3] & F::xdigit)); + assert(!(m[3] & F::blank)); + assert(!(m[3] & F::alnum)); + assert( (m[3] & F::graph)); + + // 'a' + assert(!(m[4] & F::space)); + assert( (m[4] & F::print)); + assert(!(m[4] & F::cntrl)); + assert(!(m[4] & F::upper)); + assert( (m[4] & F::lower)); + assert( (m[4] & F::alpha)); + assert(!(m[4] & F::digit)); + assert(!(m[4] & F::punct)); + assert( (m[4] & F::xdigit)); + assert(!(m[4] & F::blank)); + assert( (m[4] & F::alnum)); + assert( (m[4] & F::graph)); + + // '1' + assert(!(m[5] & F::space)); + assert( (m[5] & F::print)); + assert(!(m[5] & F::cntrl)); + assert(!(m[5] & F::upper)); + assert(!(m[5] & F::lower)); + assert(!(m[5] & F::alpha)); + assert( (m[5] & F::digit)); + assert(!(m[5] & F::punct)); + assert( (m[5] & F::xdigit)); + assert(!(m[5] & F::blank)); + assert( (m[5] & F::alnum)); + assert( (m[5] & F::graph)); + } + + return 0; +} diff --git a/pool/shard001/C++/0023946_VertexArray.cpp b/pool/shard001/C++/0023946_VertexArray.cpp new file mode 100644 index 0000000000000000000000000000000000000000..157b69bae2aa62dbe435a9aa1a5f2c676815a733 --- /dev/null +++ b/pool/shard001/C++/0023946_VertexArray.cpp @@ -0,0 +1,58 @@ +#include + +namespace Bull +{ + VertexArray VertexArray::createPolygon(const Polygon& polygon, const Color& color, const Vector3F& normal, float depth) + { + VertexArray vertices; + Vector4F colorVector = Vector4F::makeFromColor(color); + + for(std::size_t i = 0; i < polygon.getVertexCount(); i++) + { + Vertex vertex; + { + vertex.position = polygon.getVertex(i); + vertex.position.z() = depth; + vertex.color = colorVector; + vertex.texCoord = Vector2F::Zero; + vertex.normal = normal; + } + + vertices.add(vertex); + } + + return vertices; + } + + VertexArray::VertexArray(std::size_t size) : + m_vertices(size) + { + /// Nothing + } + + VertexArray::VertexArray(const std::initializer_list& vertices) : + m_vertices(vertices) + { + /// Nothing + } + + void VertexArray::add(const Vertex& vertex) + { + m_vertices.push_back(vertex); + } + + std::size_t VertexArray::getSize() const + { + return m_vertices.size(); + } + + Vertex* VertexArray::getBuffer() + { + return m_vertices.data(); + } + + const Vertex* VertexArray::getBuffer() const + { + return m_vertices.data(); + } +} \ No newline at end of file diff --git a/pool/shard001/C++/0023947_ScenarioBase.cpp b/pool/shard001/C++/0023947_ScenarioBase.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f6ccb325a12ac982350d92afb0d81efb34b85141 --- /dev/null +++ b/pool/shard001/C++/0023947_ScenarioBase.cpp @@ -0,0 +1,235 @@ +#include "general.h" + +ScenarioBase::ScenarioBase() +{ + // Spactial DB initialization + // ////////////////////////////////////////////////////////////////////////////// + + const Vec3 center; + const float div = 10.0f; + const Vec3 divisions (div, div, div); + const float diameter = 1e6f; //XXX need better way to get this + const Vec3 dimensions (diameter, diameter, diameter); + typedef LQProximityDatabase LQPDAV; + proximityDatabase = new LQPDAV (center, dimensions, divisions); + + mCameraDistance = 600; + mCameraHeight = 100; +} + +// --------------------------------------------------------------------------------- + +ScenarioBase::~ScenarioBase() +{ + // Sectors + for (sectors_it = mSectors.begin(); + sectors_it != mSectors.end(); ++sectors_it) + { + delete (*sectors_it); + } + mSectors.clear(); + + delete proximityDatabase; + +} + +// --------------------------------------------------------------------------------- + +void ScenarioBase::setCurrentSector( ScenarioSectorBase* currentSector ) +{ + if ( currentSector == NULL || currentSector == mCurrentSector ) + return; + + // load the new sector and delete the old sector + currentSector->setActive(); + + if ( mCurrentSector != NULL ) + { + mCurrentSector->exit(); + + mLump.getLogger()->log("Sector", + "change from " + mCurrentSector->getName() + + " to " + currentSector->getName() ); + } + + mCurrentSector = currentSector; + + // Register to the proximity database of the current sector + mPlayerEntity->registerToProximityDB( mCurrentSector->getProximityDatabase() ); + mDefencePlayerFlock->registerToProximityDB( mCurrentSector->getProximityDatabase() ); + + mLump.getEventsLogger()->log( "Position", "You have changed sector" ); + +} + +// --------------------------------------------------------------------------------- + +// Aggiorna il contenuto dello scenario +void ScenarioBase::updateScenario( const float currentTime, const float elapsedTime ) +{ + // Entity and current sector update + // ////////////////////////////////////////////////////////////////////////////// + + mPlayerEntity->updateEntity( currentTime, elapsedTime ); + mDefencePlayerFlock->updateEntity( currentTime, elapsedTime ); + + if ( mLump.getTotalElapsedTime() > mLastBehaviourUpdateTime + mBehaviourUpdateDelay ) + { + mPlayerEntity->updateBehaviour( currentTime, elapsedTime ); + mDefencePlayerFlock->updateBehaviour( currentTime, elapsedTime ); + mLastBehaviourUpdateTime = mLump.getTotalElapsedTime(); + + mSparksPool->checkForExpiredPS(); + mEnergyExplPool->checkForExpiredPS(); + mAsteroidExplPool->checkForExpiredPS(); + } + + for (sectors_it = mSectors.begin(); + sectors_it != mSectors.end(); ++sectors_it) + { + ScenarioSectorBase* sector = (ScenarioSectorBase*) *sectors_it; + sector->updateSector( currentTime, elapsedTime ); + } + + // Update the asteroid in the playership neighborood + // ////////////////////////////////////////////////////////////////////////////// + + /*AVGroup playerShipneighbors = mPlayerEntity->getNeighbors(); + + for (AVIterator neighbors_it=playerShipneighbors.begin(); + neighbors_it != playerShipneighborfs.end(); ++neighbors_it) + { + SteerableEntity* neighbor = (SteerableEntity*)(*neighbors_it); + + if ( typeid( *neighbor ) == typeid( EntityAsteroid ) ) + { + neighbor->updateEntity( currentTime, elapsedTime ); + } + }*/ + + onUpdate(currentTime, elapsedTime); + +} // updateScenario + +// --------------------------------------------------------------------------------- + +void ScenarioBase::enterScenario() +{ + SceneManager *mSceneMgr = mLump.mSceneMgr; + + // Scenario reset + // ////////////////////////////////////////////////////////////////////////////// + + // Chiama il metodo specifico di inizializzazione + onEnter(); + + resetScenario(); + + mBehaviourUpdateDelay = StringConverter::parseReal( + mLump.getConfigFile()->getSetting("behaviourUpdateDelay", "General") + ); + + // Load the particle system pools + mSparksPool = new UtilityParticleSet( 20, 2, "Sparks", + "Lump/Sparks", "Lump/Sparks2" ); + mEnergyExplPool = new UtilityParticleSet( 3, 4, "EnergyExplosion", + "Lump/EnergyExplosion", "Lump/EnergyExplosion2" ); + mAsteroidExplPool = new UtilityParticleSet( 4, 4, "AsteroidExplosion", + "Lump/AsteroidExplosion" ); + +} // enterScenario + +// --------------------------------------------------------------------------------- + +void ScenarioBase::resetScenario() +{ + // TODO: operazioni generiche di reset + + // Chiama il metodo specifico di reset + onReset(); +} + +// --------------------------------------------------------------------------------- + +void ScenarioBase::exitScenario() +{ + // TODO: operazioni generiche di uscita + + // Chiama il metodo specifico di uscita + onExit(); +} + +// --------------------------------------------------------------------------------- + +void ScenarioBase::increaseCameraDistance(float incRatio) +{ + mCameraDistance += mCameraDistance * incRatio; +} + +// --------------------------------------------------------------------------------- + +void ScenarioBase::increaseCameraHeight(float incRatio) +{ + mCameraHeight += mCameraHeight * incRatio; +} + +// --------------------------------------------------------------------------------- + +void ScenarioBase::updateCamera( const float elapsedTime ) +{ + + ////// Main camera + ////////////////////////////////////////////////////////////////////////////////// + + Vector3 cameraDirection; + cameraDirection = mLump.mCamera->getDirection(); + + // Ottiene il vettore diretto indietro del veicolo dell'utente + Vector3 relativeForwardPosition = + - cameraDirection * + mCameraDistance; + + // Ottiene il vettore diretto verso l'alto del veicolo dell'utente + Vector3 relativeUpperPosition = + mLump.mCamera->getUp() * + mCameraHeight; + + Vector3 shakeEffect; + float diffTime = mLump.getTotalElapsedTime() - mShakeCameraStartTime; + if ( diffTime < 0 ) + { + shakeEffect = newRandVector3( diffTime * diffTime * 100 ); + } + + mLump.mCamera->setPosition(mPlayerEntity->getPosition() + + relativeForwardPosition + + relativeUpperPosition + + shakeEffect + ); + + // ************************************************* + // Linear smooth zooming + + Radian FOVyDistance = mLump.mCamera->getFOVy() - mCameraFOVy; + if ( FOVyDistance < - Radian(0.01) || FOVyDistance > Radian(0.01) ) + mLump.mCamera->setFOVy( mLump.mCamera->getFOVy() - Radian( FOVyDistance * elapsedTime * 10 ) ); + + ////// Front camera + ////////////////////////////////////////////////////////////////////////////////// + + /*mLump.mFrontCamera->setPosition( mPlayerEntity->getPosition() ); + mLump.mFrontCamera->setDirection( Vector3( mPlayerEntity->forward().x, + mPlayerEntity->forward().y, + - mPlayerEntity->forward().z ) + );*/ + + +} // updateCamera + + +// --------------------------------------------------------------------------------- + +void ScenarioBase::shakeCamera( float power ) +{ + mShakeCameraStartTime = mLump.getTotalElapsedTime() + power; +} \ No newline at end of file diff --git a/pool/shard001/C++/0023952_NitroLz.cpp b/pool/shard001/C++/0023952_NitroLz.cpp new file mode 100644 index 0000000000000000000000000000000000000000..49cb351ff51995ebe14b2319b991388156f4454a --- /dev/null +++ b/pool/shard001/C++/0023952_NitroLz.cpp @@ -0,0 +1,53 @@ +/************************************************************************* + NitroLz.cpp + :A wrapper for cprs_lz.cpp, just like DS a wrapper for GBA + Copyright (C) 2015 wwylele + + This file is part of MApRX. + + MApRX 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. + + MApRX 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 MApRX. If not, see . +**************************************************************************/ + +#include "NitroLz.h" +#include +#include +#include "cprs_lz.h" + +u32 compressLZ(const u8 *srcp,u32 size,u8 *dstp) +{ + RECORD src,dst; + src.data=(BYTE*)srcp; + src.width=1; + src.height=size; + dst.data=0; + lz77gba_compress(&dst,&src); + std::memcpy(dstp,dst.data,dst.height); + std::free(dst.data); + return dst.height; +} +void uncompressLZ(const u8 *srcp,u8 *destp) +{ + RECORD src,dst; + src.data=(BYTE*)srcp; + dst.data=0; + lz77gba_decompress(&dst,&src); + std::memcpy(destp,dst.data,dst.height); + std::free(dst.data); +} + +u32 getLengthLZ(const u8* srcp){ + u32 length; + memcpy(&length,srcp,4); + return length>>8; +} diff --git a/pool/shard001/C++/0023954_GUIWindowPrograms.cpp b/pool/shard001/C++/0023954_GUIWindowPrograms.cpp new file mode 100644 index 0000000000000000000000000000000000000000..82cee83c95d88a030fed5856ec91bd79bf5caf11 --- /dev/null +++ b/pool/shard001/C++/0023954_GUIWindowPrograms.cpp @@ -0,0 +1,212 @@ +/* + * Copyright (C) 2005-2013 Team XBMC + * http://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, see + * . + * + */ + +#include "system.h" +#include "GUIWindowPrograms.h" +#include "Util.h" +#include "addons/GUIDialogAddonInfo.h" +#include "guilib/GUIWindowManager.h" +#include "FileItem.h" +#include "settings/MediaSourceSettings.h" +#include "input/Key.h" +#include "utils/StringUtils.h" + +#define CONTROL_BTNVIEWASICONS 2 +#define CONTROL_BTNSORTBY 3 +#define CONTROL_BTNSORTASC 4 +#define CONTROL_LABELFILES 12 + +CGUIWindowPrograms::CGUIWindowPrograms(void) + : CGUIMediaWindow(WINDOW_PROGRAMS, "MyPrograms.xml") +{ + m_thumbLoader.SetObserver(this); + m_dlgProgress = NULL; + m_rootDir.AllowNonLocalSources(false); // no nonlocal shares for this window please +} + + +CGUIWindowPrograms::~CGUIWindowPrograms(void) +{ +} + +bool CGUIWindowPrograms::OnMessage(CGUIMessage& message) +{ + switch ( message.GetMessage() ) + { + case GUI_MSG_WINDOW_DEINIT: + { + if (m_thumbLoader.IsLoading()) + m_thumbLoader.StopThread(); + } + break; + + case GUI_MSG_WINDOW_INIT: + { + m_dlgProgress = (CGUIDialogProgress*)g_windowManager.GetWindow(WINDOW_DIALOG_PROGRESS); + + // is this the first time accessing this window? + if (m_vecItems->GetPath() == "?" && message.GetStringParam().empty()) + message.SetStringParam(CMediaSourceSettings::GetInstance().GetDefaultSource("programs")); + + return CGUIMediaWindow::OnMessage(message); + } + break; + + case GUI_MSG_CLICKED: + { + if (m_viewControl.HasControl(message.GetSenderId())) // list/thumb control + { + int iAction = message.GetParam1(); + int iItem = m_viewControl.GetSelectedItem(); + if (iAction == ACTION_PLAYER_PLAY) + { + OnPlayMedia(iItem); + return true; + } + else if (iAction == ACTION_SHOW_INFO) + { + OnInfo(iItem); + return true; + } + } + } + break; + } + + return CGUIMediaWindow::OnMessage(message); +} + +void CGUIWindowPrograms::GetContextButtons(int itemNumber, CContextButtons &buttons) +{ + if (itemNumber < 0 || itemNumber >= m_vecItems->Size()) + return; + CFileItemPtr item = m_vecItems->Get(itemNumber); + if (item && !item->GetProperty("pluginreplacecontextitems").asBoolean()) + { + if ( m_vecItems->IsVirtualDirectoryRoot() || m_vecItems->GetPath() == "sources://programs/" ) + { + CGUIDialogContextMenu::GetContextButtons("programs", item, buttons); + } + else + { + buttons.Add(CONTEXT_BUTTON_GOTO_ROOT, 20128); // Go to Root + } + } + CGUIMediaWindow::GetContextButtons(itemNumber, buttons); +} + +bool CGUIWindowPrograms::OnContextButton(int itemNumber, CONTEXT_BUTTON button) +{ + CFileItemPtr item = (itemNumber >= 0 && itemNumber < m_vecItems->Size()) ? m_vecItems->Get(itemNumber) : CFileItemPtr(); + + if (CGUIDialogContextMenu::OnContextButton("programs", item, button)) + { + Update(""); + return true; + } + switch (button) + { + case CONTEXT_BUTTON_GOTO_ROOT: + Update(""); + return true; + + case CONTEXT_BUTTON_INFO: + OnInfo(itemNumber); + return true; + + default: + break; + } + return CGUIMediaWindow::OnContextButton(itemNumber, button); +} + +bool CGUIWindowPrograms::Update(const std::string &strDirectory, bool updateFilterPath /* = true */) +{ + if (m_thumbLoader.IsLoading()) + m_thumbLoader.StopThread(); + + if (!CGUIMediaWindow::Update(strDirectory, updateFilterPath)) + return false; + + m_thumbLoader.Load(*m_vecItems); + return true; +} + +bool CGUIWindowPrograms::OnPlayMedia(int iItem) +{ + if ( iItem < 0 || iItem >= (int)m_vecItems->Size() ) return false; + CFileItemPtr pItem = m_vecItems->Get(iItem); + + if (pItem->m_bIsFolder) return false; + + return false; +} + +bool CGUIWindowPrograms::GetDirectory(const std::string &strDirectory, CFileItemList &items) +{ + if (!CGUIMediaWindow::GetDirectory(strDirectory, items)) + return false; + + // don't allow the view state to change these + if (StringUtils::StartsWithNoCase(strDirectory, "addons://")) + { + for (int i=0;iSetLabel2(items[i]->GetProperty("Addon.Version").asString()); + items[i]->SetLabelPreformated(true); + } + } + + return true; +} + +std::string CGUIWindowPrograms::GetStartFolder(const std::string &dir) +{ + std::string lower(dir); StringUtils::ToLower(lower); + if (lower == "plugins" || lower == "addons") + return "addons://sources/executable/"; + else if (lower == "androidapps") + return "androidapp://sources/apps/"; + + SetupShares(); + VECSOURCES shares; + m_rootDir.GetSources(shares); + bool bIsSourceName = false; + int iIndex = CUtil::GetMatchingSource(dir, shares, bIsSourceName); + if (iIndex > -1) + { + if (iIndex < (int)shares.size() && shares[iIndex].m_iHasLock == 2) + { + CFileItem item(shares[iIndex]); + if (!g_passwordManager.IsItemUnlocked(&item,"programs")) + return ""; + } + if (bIsSourceName) + return shares[iIndex].strPath; + return dir; + } + return CGUIMediaWindow::GetStartFolder(dir); +} + +void CGUIWindowPrograms::OnInfo(int iItem) +{ + if (iItem < 0 || iItem >= m_vecItems->Size()) + return; +} diff --git a/pool/shard001/C++/0023977_sitl_optical_flow.cpp b/pool/shard001/C++/0023977_sitl_optical_flow.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f3455db8954d3d59cc69052c004d08c7f8d872cf --- /dev/null +++ b/pool/shard001/C++/0023977_sitl_optical_flow.cpp @@ -0,0 +1,132 @@ +/* + SITL handling + + This simulates a optical flow sensor + + Andrew Tridgell November 2011 + */ + +#include +#include + +#if CONFIG_HAL_BOARD == HAL_BOARD_SITL + +#include "AP_HAL_SITL.h" + +using namespace HALSITL; + +extern const AP_HAL::HAL& hal; + +#include +#include +#include +#include +#include + +#define MAX_OPTFLOW_DELAY 20 +static uint8_t next_optflow_index; +static uint8_t optflow_delay; +static OpticalFlow::OpticalFlow_state optflow_data[MAX_OPTFLOW_DELAY]; + +/* + update the optical flow with new data + */ +void SITL_State::_update_flow(void) +{ + Vector3f gyro; + static uint32_t last_flow_ms; + + if (!_optical_flow || + !_sitl->flow_enable) { + return; + } + + // update at the requested rate + uint32_t now = AP_HAL::millis(); + if (now - last_flow_ms < 1000*(1.0f/_sitl->flow_rate)) { + return; + } + last_flow_ms = now; + + gyro(radians(_sitl->state.rollRate), + radians(_sitl->state.pitchRate), + radians(_sitl->state.yawRate)); + + OpticalFlow::OpticalFlow_state state; + + // NED velocity vector in m/s + Vector3f velocity(_sitl->state.speedN, + _sitl->state.speedE, + _sitl->state.speedD); + + // a rotation matrix following DCM conventions + Matrix3f rotmat; + rotmat.from_euler(radians(_sitl->state.rollDeg), + radians(_sitl->state.pitchDeg), + radians(_sitl->state.yawDeg)); + + + state.device_id = 1; + state.surface_quality = 51; + + // sensor position offset in body frame + Vector3f posRelSensorBF = _sitl->optflow_pos_offset; + + // for effiency only do offset correction if offset is non-zero + bool correctForOffset = !posRelSensorBF.is_zero(); + + // estimate range to centre of image + float range; + if (rotmat.c.z > 0.05f && height_agl() > 0) { + if (!correctForOffset) { + range = height_agl() / rotmat.c.z; + } else { + Vector3f relPosSensorEF = rotmat * posRelSensorBF; + range = (height_agl() - relPosSensorEF.z) / rotmat.c.z; + } + } else { + range = 1e38f; + } + + // Calculate relative velocity in sensor frame assuming no misalignment between sensor and vehicle body axes + Vector3f relVelSensor = rotmat.mul_transpose(velocity); + + // correct relative velocity for rotation rates and sensor offset + if (correctForOffset) { + relVelSensor += gyro % posRelSensorBF; + } + + // Divide velocity by range and add body rates to get predicted sensed angular + // optical rates relative to X and Y sensor axes assuming no misalignment or scale + // factor error. Note - these are instantaneous values. The sensor sums these values across the interval from the last + // poll to provide a delta angle across the interface + state.flowRate.x = -relVelSensor.y/range + gyro.x; + state.flowRate.y = relVelSensor.x/range + gyro.y; + + // The flow sensors body rates are assumed to be the same as the vehicle body rates (ie no misalignment) + // Note - these are instantaneous values. The sensor sums these values across the interval from the last + // poll to provide a delta angle across the interface. + state.bodyRate = Vector2f(gyro.x, gyro.y); + + optflow_data[next_optflow_index++] = state; + if (next_optflow_index >= optflow_delay+1) { + next_optflow_index = 0; + } + + state = optflow_data[next_optflow_index]; + + if (_sitl->flow_delay != optflow_delay) { + // cope with updates to the delay control + if (_sitl->flow_delay > MAX_OPTFLOW_DELAY) { + _sitl->flow_delay = MAX_OPTFLOW_DELAY; + } + optflow_delay = _sitl->flow_delay; + for (uint8_t i=0; isetHIL(state); +} + +#endif diff --git a/pool/shard001/C++/0023985_dtkWidgetsTagCloud.cpp b/pool/shard001/C++/0023985_dtkWidgetsTagCloud.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6caf8c1e454a2feee1776342ff3daf164ce65a61 --- /dev/null +++ b/pool/shard001/C++/0023985_dtkWidgetsTagCloud.cpp @@ -0,0 +1,250 @@ +/* dtkWidgetsTagCloud.cpp --- + * + * Author: Julien Wintz + * Created: Mon Apr 15 12:00:34 2013 (+0200) + * Version: + * Last-Updated: mar. avril 8 14:54:47 2014 (+0200) + * By: Thibaud Kloczko + * Update #: 33 + */ + +/* Change Log: + * + */ + +#include "dtkWidgetsTag.h" +#include "dtkWidgetsTagCloud.h" + +// ///////////////////////////////////////////////////////////////// +// Helper functions +// ///////////////////////////////////////////////////////////////// + +bool dtkWidgetsTagAlphaLessThan(const dtkWidgetsTag &t1, const dtkWidgetsTag &t2) { + return t1.text() < t2.text(); +} + +bool dtkWidgetsTagNumLessThan(const dtkWidgetsTag &t1, const dtkWidgetsTag &t2) { + return t1.count() < t2.count(); +} + +bool dtkWidgetsTagAlphaMoreThan(const dtkWidgetsTag &t1, const dtkWidgetsTag &t2) { + return t1.text() >= t2.text(); +} + +bool dtkWidgetsTagNumMoreThan(const dtkWidgetsTag &t1, const dtkWidgetsTag &t2) { + return t1.count() >= t2.count(); +} + +// ///////////////////////////////////////////////////////////////// +// dtkWidgetsTagCloudHasher +// ///////////////////////////////////////////////////////////////// + +class dtkWidgetsTagCloudHasher +{ +public: + dtkWidgetsTagCloudHasher(int buckets, int min, int max) { + if (buckets < 1) + qDebug() << "dtkWidgetsTagCloudHasher: Must have at least one bucket."; + + this->buckets = buckets; + this->min = min; + this->max = max+1; + + this->width = ((double)(this->max-this->min))/((double)(this->buckets)); + } + + int bucket(dtkWidgetsTag tag) { + return ((float)(tag.count()-this->min))/((float)(this->width)); + } + +private: + int min, max, buckets; + +private: + double width; +}; + +// /////////////////////////////////////////////////////////////////// +// dtkWidgetsTagCloudPrivate +// /////////////////////////////////////////////////////////////////// + +class dtkWidgetsTagCloudPrivate +{ +public: + QList tags; + + int averageFontSize; + int fontSizeRange; + int mincount; + int maxcount; + int tagCount; + + dtkWidgetsTagCloud::SortingType sortingType; + dtkWidgetsTagCloud::SortingOrder sortingOrder; +}; + +// ///////////////////////////////////////////////////////////////// +// dtkWidgetsTagCloud +// ///////////////////////////////////////////////////////////////// + +/*! + \class dtkWidgetsTagCloud + + \inmodule dtkWidgets + + \brief The dtkWidgetsTagCloud class provides a configurable tag + cloud. + + \l {Core Module} {Core Module} ... +*/ + +dtkWidgetsTagCloud::dtkWidgetsTagCloud(QWidget *parent) : QTextBrowser(parent) +{ + d = new dtkWidgetsTagCloudPrivate; + + d->averageFontSize = 0; + d->fontSizeRange = 0; + + d->sortingType = Alpha; + d->sortingOrder = Asc; + + this->setFrameShape(QFrame::NoFrame); + + connect(this, SIGNAL(anchorClicked(const QUrl&)), this, SLOT(onLinkClicked(const QUrl&))); +} + +dtkWidgetsTagCloud::~dtkWidgetsTagCloud(void) +{ + delete d; + + d = NULL; +} + +void dtkWidgetsTagCloud::addTag(QString text, int count) +{ + d->tags << dtkWidgetsTag(text, count); +} + +void dtkWidgetsTagCloud::addTag(QString text, int count, QStringList items) +{ + d->tags << dtkWidgetsTag(text, count, items); +} + +void dtkWidgetsTagCloud::addTag(QString text, int count, QStringList items, QString color) +{ + d->tags << dtkWidgetsTag(text, count, items, color); +} + +void dtkWidgetsTagCloud::addTag(dtkWidgetsTag tag) +{ + d->tags << tag; +} + +void dtkWidgetsTagCloud::setFontSize(int size) +{ + d->averageFontSize = (size > 0) ? size : 0; +} + +void dtkWidgetsTagCloud::setFontRange(int range) +{ + d->fontSizeRange = (range > 0) ? range: 0; +} + +void dtkWidgetsTagCloud::setSortingType(SortingType type) +{ + d->sortingType = type; +} + +void dtkWidgetsTagCloud::setSortingOrder(SortingOrder order) +{ + d->sortingOrder = order; +} + +void dtkWidgetsTagCloud::sort(void) +{ + if(d->sortingType == Alpha && d->sortingOrder == Asc) + qSort(d->tags.begin(), d->tags.end(), dtkWidgetsTagAlphaLessThan); + + if(d->sortingType == Alpha && d->sortingOrder == Desc) + qSort(d->tags.begin(), d->tags.end(), dtkWidgetsTagAlphaMoreThan); + + if(d->sortingType == Num && d->sortingOrder == Asc) + qSort(d->tags.begin(), d->tags.end(), dtkWidgetsTagNumLessThan); + + if(d->sortingType == Num && d->sortingOrder == Desc) + qSort(d->tags.begin(), d->tags.end(), dtkWidgetsTagNumMoreThan); +} + +void dtkWidgetsTagCloud::clear(void) +{ + d->tags.clear(); + + this->render(); +} + +void dtkWidgetsTagCloud::render(void) +{ + if (d->averageFontSize <= 0) + qDebug() << "AverageFontSize must be non-zero and non-negative."; + + if (d->fontSizeRange <= 0) + qDebug() << "FontSizeRange must be non-zero and non-negative."; + + if (d->tags.isEmpty()) + return; + + d->mincount = 100000000; + d->maxcount = 0; + d->tagCount = 0; + + foreach (dtkWidgetsTag tag, d->tags) { + + if (tag.count() < d->mincount) + d->mincount = tag.count(); + + if (tag.count() > d->maxcount) + d->maxcount = tag.count(); + + d->tagCount++; + } + + dtkWidgetsTagCloudHasher hasher(d->fontSizeRange, d->mincount, d->maxcount); + + int baseFontSize = d->averageFontSize - ((double)(d->fontSizeRange-1)/2); + + QString cloud; cloud.append(QString("
\n")); + + foreach (dtkWidgetsTag tag, d->tags) { + + int fontSize = baseFontSize + hasher.bucket(tag); + + QString color = ""; + + if (!tag.color().isEmpty()) { + color = "color: "; + color += (!tag.color().startsWith("#")) ? "#" : ""; + color += tag.color(); + color += ";"; + } else { + color = "color: #6a769d;"; + } + + QString count = QString::number(tag.count()) + " item" + ((tag.count() != 1) ? "s" : ""); + + cloud.append(QString("%1 ") + .arg(tag.text()) + .arg(count) + .arg(tag.items().first()) + .arg(fontSize) + .arg(color)); + } + + cloud.append("
\n"); + + this->setHtml(cloud); +} + +void dtkWidgetsTagCloud::onLinkClicked(const QUrl& url) +{ + emit tagClicked(url.host()); +} diff --git a/pool/shard001/C++/0023987_VerifyInvokeHTTPTest.cpp b/pool/shard001/C++/0023987_VerifyInvokeHTTPTest.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fae79b50c96d7be0198def1f9150f2158b603767 --- /dev/null +++ b/pool/shard001/C++/0023987_VerifyInvokeHTTPTest.cpp @@ -0,0 +1,201 @@ +/** + * + * 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. + */ + +#undef NDEBUG +#include "TestBase.h" +#include "HTTPHandlers.h" +#include "HTTPClient.h" +#include "InvokeHTTP.h" +#include "processors/LogAttribute.h" +#include "core/state/ProcessorController.h" + +#include "../tests/TestServer.h" +#include "CivetServer.h" +#include "HTTPIntegrationBase.h" + +class VerifyInvokeHTTP : public CoapIntegrationBase { +public: + VerifyInvokeHTTP() + : CoapIntegrationBase(6000) { + } + + virtual void testSetup() override { + LogTestController::getInstance().setDebug(); + LogTestController::getInstance().setDebug(); + LogTestController::getInstance().setTrace(); + LogTestController::getInstance().setTrace(); + } + + virtual void cleanup() override { + } + + void setProperties(std::shared_ptr proc) { + std::string url = scheme + "://localhost:" + getWebPort() + path; + proc->setProperty(minifi::processors::InvokeHTTP::URL.getName(), url); + } + + void setupFlow(const std::string& flow_yml_path) { + testSetup(); + + std::shared_ptr test_repo = std::make_shared(); + std::shared_ptr test_flow_repo = std::make_shared(); + + configuration->set(minifi::Configure::nifi_flow_configuration_file, flow_yml_path); + + std::shared_ptr content_repo = std::make_shared(); + content_repo->initialize(configuration); + std::shared_ptr stream_factory = minifi::io::StreamFactory::getInstance(configuration); + std::unique_ptr yaml_ptr = std::unique_ptr( + new core::YamlConfiguration(test_repo, test_repo, content_repo, stream_factory, configuration, flow_yml_path)); + + flowController_ = std::make_shared(test_repo, test_flow_repo, configuration, std::move(yaml_ptr), content_repo, DEFAULT_ROOT_GROUP_NAME, true); + flowController_->load(); + + const auto components = flowController_->getComponents("InvokeHTTP"); + assert(!components.empty()); + + const auto stateController = components.at(0); + assert(stateController); + const auto processorController = std::dynamic_pointer_cast(stateController); + assert(processorController); + setProperties(processorController->getProcessor()); + } + + virtual void run(std::string flow_yml_path) override { + setupFlow(flow_yml_path); + startFlowController(); + + waitToVerifyProcessor(); + shutdownBeforeFlowController(); + stopFlowController(); + } + + void startFlowController() { + flowController_->start(); + } + + void stopFlowController() { + flowController_->unload(); + flowController_->stopC2(); + + runAssertions(); + cleanup(); + } +}; + +class VerifyInvokeHTTPOKResponse : public VerifyInvokeHTTP { +public: + virtual void runAssertions() override { + assert(LogTestController::getInstance().contains("key:invokehttp.status.code value:201")); + assert(LogTestController::getInstance().contains("response code 201")); + } +}; + +class VerifyCouldNotConnectInvokeHTTP : public VerifyInvokeHTTP { +public: + virtual void runAssertions() override { + assert(LogTestController::getInstance().contains("key:invoke_http value:failure")); + } +}; + +class VerifyNoRetryInvokeHTTP : public VerifyInvokeHTTP { +public: + virtual void runAssertions() override { + assert(LogTestController::getInstance().contains("key:invokehttp.status.message value:HTTP/1.1 404 Not Found")); + assert(LogTestController::getInstance().contains("isSuccess: 0, response code 404")); + } +}; + +class VerifyRetryInvokeHTTP : public VerifyInvokeHTTP { +public: + virtual void runAssertions() override { + assert(LogTestController::getInstance().contains("key:invokehttp.status.message value:HTTP/1.1 501 Not Implemented")); + assert(LogTestController::getInstance().contains("isSuccess: 0, response code 501")); + } +}; + +class VerifyRWTimeoutInvokeHTTP : public VerifyInvokeHTTP { +public: + virtual void runAssertions() override { + assert(LogTestController::getInstance().contains("key:invoke_http value:failure")); + assert(LogTestController::getInstance().contains("limit (1000ms) reached, terminating connection")); + } +}; + +void run(VerifyInvokeHTTP& harness, + const std::string& url, + const std::string& test_file_location, + const std::string& key_dir, + ServerAwareHandler * handler) { + + harness.setKeyDir(key_dir); + harness.setUrl(url, handler); + harness.run(test_file_location); +} + +int main(int argc, char ** argv) { + std::string key_dir, test_file_location, url; + if (argc > 1) { + test_file_location = argv[1]; + url = "http://localhost:0/minifi"; + if (argc > 2) { + key_dir = argv[2]; + url = "https://localhost:0/minifi"; + } + } + + // Stop civet server to simulate + // unreachable remote end point + { + InvokeHTTPCouldNotConnectHandler handler; + VerifyCouldNotConnectInvokeHTTP harness; + harness.setKeyDir(key_dir); + harness.setUrl(url, &handler); + harness.setupFlow(test_file_location); + harness.shutdownBeforeFlowController(); + harness.startFlowController(); + harness.waitToVerifyProcessor(); + harness.stopFlowController(); + } + + { + InvokeHTTPResponseOKHandler handler; + VerifyInvokeHTTPOKResponse harness; + run(harness, url, test_file_location, key_dir, &handler); + } + + { + InvokeHTTPResponse404Handler handler; + VerifyNoRetryInvokeHTTP harness; + run(harness, url, test_file_location, key_dir, &handler); + } + + { + InvokeHTTPResponse501Handler handler; + VerifyRetryInvokeHTTP harness; + run(harness, url, test_file_location, key_dir, &handler); + } + + { + TimeoutingHTTPHandler handler({std::chrono::milliseconds(4000)}); + VerifyRWTimeoutInvokeHTTP harness; + run(harness, url, test_file_location, key_dir, &handler); + } + + return 0; +} diff --git a/pool/shard001/C++/0023989_unix-system-wall-clock-ms.cc b/pool/shard001/C++/0023989_unix-system-wall-clock-ms.cc new file mode 100644 index 0000000000000000000000000000000000000000..68f70fb98bbe5e6f5995cd79be8a5e6f86739bae --- /dev/null +++ b/pool/shard001/C++/0023989_unix-system-wall-clock-ms.cc @@ -0,0 +1,162 @@ +/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ +/* + * Copyright (c) 2005 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 "system-wall-clock-ms.h" +#include "abort.h" +#include + +namespace ns3 { + +class SystemWallClockMsPrivate { +public: + void Start (void); + int64_t End (void); + int64_t GetElapsedReal (void) const; + int64_t GetElapsedUser (void) const; + int64_t GetElapsedSystem (void) const; + +private: + struct tms m_startTimes; + clock_t m_startTime; + int64_t m_elapsedReal; + int64_t m_elapsedUser; + int64_t m_elapsedSystem; +}; + +void +SystemWallClockMsPrivate::Start (void) +{ + m_startTime = times (&m_startTimes); +} + +int64_t +SystemWallClockMsPrivate::End (void) +{ + // + // We need to return the number of milliseconds that have elapsed in some + // reasonably portable way. The underlying function that we will use returns + // a number of elapsed ticks. We can look up the number of ticks per second + // from the system configuration. + // + // Conceptually, we need to find the number of elapsed clock ticks and then + // multiply the result by the milliseconds per clock tick (or divide by clock + // ticks per millisecond). Integer dividing by clock ticks per millisecond + // is bad since this number is fractional on most machines and would result + // in divide by zero errors due to integer rounding. + // + // Multiplying by milliseconds per clock tick works up to a clock resolution + // of 1000 ticks per second. If we go past this point, we begin to get zero + // elapsed times when millisecondsPerTick becomes fractional and another + // rounding error appears. + // + // So rounding errors using integers can bite you from both direction. Since + // all of our targets have math coprocessors, why not just use doubles + // internally? Works fine, lasts a long time. + // + // If millisecondsPerTick becomes fractional, and an elapsed time greater than + // a milliscond is measured, the function will work as expected. If an elapsed + // time is measured that turns out to be less than a millisecond, we'll just + // return zero which would, I think, also will be expected. + // + static int64_t ticksPerSecond = sysconf (_SC_CLK_TCK); + static double millisecondsPerTick = 1000. / ticksPerSecond; + + // + // If sysconf () fails, we have no idea how to do the required conversion to ms. + // + NS_ABORT_MSG_IF (ticksPerSecond == -1, "SystemWallClockMsPrivate(): Cannot sysconf (_SC_CLK_TCK)"); + + struct tms endTimes; + clock_t endTime = times (&endTimes); + + double tmp; + + tmp = static_cast (endTime - m_startTime) * millisecondsPerTick; + m_elapsedReal = static_cast (tmp); + + tmp = static_cast (endTimes.tms_utime - m_startTimes.tms_utime) * millisecondsPerTick; + m_elapsedUser = static_cast (tmp); + + tmp = static_cast (endTimes.tms_stime - m_startTimes.tms_stime) * millisecondsPerTick; + m_elapsedSystem = static_cast (tmp); + + return m_elapsedReal; +} + +int64_t +SystemWallClockMsPrivate::GetElapsedReal (void) const +{ + return m_elapsedReal; +} + +int64_t +SystemWallClockMsPrivate::GetElapsedUser (void) const +{ + return m_elapsedUser; +} + +int64_t +SystemWallClockMsPrivate::GetElapsedSystem (void) const +{ + return m_elapsedSystem; +} + +SystemWallClockMs::SystemWallClockMs () + : m_priv (new SystemWallClockMsPrivate ()) +{ +} + +SystemWallClockMs::~SystemWallClockMs () +{ + delete m_priv; + m_priv = 0; +} + +void +SystemWallClockMs::Start (void) +{ + m_priv->Start (); +} + +int64_t +SystemWallClockMs::End (void) +{ + return m_priv->End (); +} + +int64_t +SystemWallClockMs::GetElapsedReal (void) const +{ + return m_priv->GetElapsedReal (); +} + +int64_t +SystemWallClockMs::GetElapsedUser (void) const +{ + return m_priv->GetElapsedUser (); +} + +int64_t +SystemWallClockMs::GetElapsedSystem (void) const +{ + return m_priv->GetElapsedSystem (); +} + +} // namespace ns3 diff --git a/pool/shard001/C++/0024012_moc_fillpits.cpp b/pool/shard001/C++/0024012_moc_fillpits.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6ec15a184a6b57dcfe4e6c45a0f6fb1a52bed5c5 --- /dev/null +++ b/pool/shard001/C++/0024012_moc_fillpits.cpp @@ -0,0 +1,133 @@ +/**************************************************************************** +** Meta object code from reading C++ file 'fillpits.h' +** +** Created by: The Qt Meta Object Compiler version 67 (Qt 5.1.1) +** +** WARNING! All changes made in this file will be lost! +*****************************************************************************/ + +#include "2RasterProcessing/1FillPits/fillpits.h" +#include +#include +#if !defined(Q_MOC_OUTPUT_REVISION) +#error "The header file 'fillpits.h' doesn't include ." +#elif Q_MOC_OUTPUT_REVISION != 67 +#error "This file was generated using the moc from 5.1.1. It" +#error "cannot be used with the include files from this version of Qt." +#error "(The moc has changed too much.)" +#endif + +QT_BEGIN_MOC_NAMESPACE +struct qt_meta_stringdata_FillPits_t { + QByteArrayData data[8]; + char stringdata[163]; +}; +#define QT_MOC_LITERAL(idx, ofs, len) \ + Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ + offsetof(qt_meta_stringdata_FillPits_t, stringdata) + ofs \ + - idx * sizeof(QByteArrayData) \ + ) +static const qt_meta_stringdata_FillPits_t qt_meta_stringdata_FillPits = { + { +QT_MOC_LITERAL(0, 0, 8), +QT_MOC_LITERAL(1, 9, 24), +QT_MOC_LITERAL(2, 34, 0), +QT_MOC_LITERAL(3, 35, 29), +QT_MOC_LITERAL(4, 65, 24), +QT_MOC_LITERAL(5, 90, 26), +QT_MOC_LITERAL(6, 117, 25), +QT_MOC_LITERAL(7, 143, 18) + }, + "FillPits\0on_pushButtonDEM_clicked\0\0" + "on_pushButtonFillPits_clicked\0" + "on_pushButtonRun_clicked\0" + "on_pushButtonClose_clicked\0" + "on_pushButtonHelp_clicked\0pushButtonSetFocus\0" +}; +#undef QT_MOC_LITERAL + +static const uint qt_meta_data_FillPits[] = { + + // content: + 7, // revision + 0, // classname + 0, 0, // classinfo + 6, 14, // methods + 0, 0, // properties + 0, 0, // enums/sets + 0, 0, // constructors + 0, // flags + 0, // signalCount + + // slots: name, argc, parameters, tag, flags + 1, 0, 44, 2, 0x08, + 3, 0, 45, 2, 0x08, + 4, 0, 46, 2, 0x08, + 5, 0, 47, 2, 0x08, + 6, 0, 48, 2, 0x08, + 7, 0, 49, 2, 0x08, + + // slots: parameters + QMetaType::Void, + QMetaType::Void, + QMetaType::Void, + QMetaType::Void, + QMetaType::Void, + QMetaType::Void, + + 0 // eod +}; + +void FillPits::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) +{ + if (_c == QMetaObject::InvokeMetaMethod) { + FillPits *_t = static_cast(_o); + switch (_id) { + case 0: _t->on_pushButtonDEM_clicked(); break; + case 1: _t->on_pushButtonFillPits_clicked(); break; + case 2: _t->on_pushButtonRun_clicked(); break; + case 3: _t->on_pushButtonClose_clicked(); break; + case 4: _t->on_pushButtonHelp_clicked(); break; + case 5: _t->pushButtonSetFocus(); break; + default: ; + } + } + Q_UNUSED(_a); +} + +const QMetaObject FillPits::staticMetaObject = { + { &QDialog::staticMetaObject, qt_meta_stringdata_FillPits.data, + qt_meta_data_FillPits, qt_static_metacall, 0, 0} +}; + + +const QMetaObject *FillPits::metaObject() const +{ + return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; +} + +void *FillPits::qt_metacast(const char *_clname) +{ + if (!_clname) return 0; + if (!strcmp(_clname, qt_meta_stringdata_FillPits.stringdata)) + return static_cast(const_cast< FillPits*>(this)); + return QDialog::qt_metacast(_clname); +} + +int FillPits::qt_metacall(QMetaObject::Call _c, int _id, void **_a) +{ + _id = QDialog::qt_metacall(_c, _id, _a); + if (_id < 0) + return _id; + if (_c == QMetaObject::InvokeMetaMethod) { + if (_id < 6) + qt_static_metacall(this, _c, _id, _a); + _id -= 6; + } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { + if (_id < 6) + *reinterpret_cast(_a[0]) = -1; + _id -= 6; + } + return _id; +} +QT_END_MOC_NAMESPACE diff --git a/pool/shard001/C++/0024017_print_web_view_helper_linux.cc b/pool/shard001/C++/0024017_print_web_view_helper_linux.cc new file mode 100644 index 0000000000000000000000000000000000000000..312acd2d832ce0f8e5048f1458768b7d7a978a9f --- /dev/null +++ b/pool/shard001/C++/0024017_print_web_view_helper_linux.cc @@ -0,0 +1,199 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/renderer/printing/print_web_view_helper.h" + +#include "base/logging.h" +#include "base/memory/scoped_ptr.h" +#include "chrome/common/print_messages.h" +#include "content/public/renderer/render_thread.h" +#include "printing/metafile.h" +#include "printing/metafile_impl.h" +#include "printing/metafile_skia_wrapper.h" +#include "printing/page_size_margins.h" +#include "skia/ext/platform_device.h" +#include "skia/ext/vector_canvas.h" +#include "third_party/WebKit/public/web/WebFrame.h" + +#if !defined(OS_CHROMEOS) && !defined(OS_ANDROID) +#include "base/process/process_handle.h" +#else +#include "base/file_descriptor_posix.h" +#endif // !defined(OS_CHROMEOS) && !defined(OS_ANDROID) + +namespace printing { + +using WebKit::WebFrame; +using WebKit::WebNode; + +bool PrintWebViewHelper::RenderPreviewPage( + int page_number, + const PrintMsg_Print_Params& print_params) { + PrintMsg_PrintPage_Params page_params; + page_params.params = print_params; + page_params.page_number = page_number; + scoped_ptr draft_metafile; + Metafile* initial_render_metafile = print_preview_context_.metafile(); + if (print_preview_context_.IsModifiable() && is_print_ready_metafile_sent_) { + draft_metafile.reset(new PreviewMetafile); + initial_render_metafile = draft_metafile.get(); + } + + base::TimeTicks begin_time = base::TimeTicks::Now(); + PrintPageInternal(page_params, + print_preview_context_.GetPrintCanvasSize(), + print_preview_context_.prepared_frame(), + initial_render_metafile); + print_preview_context_.RenderedPreviewPage( + base::TimeTicks::Now() - begin_time); + if (draft_metafile.get()) { + draft_metafile->FinishDocument(); + } else if (print_preview_context_.IsModifiable() && + print_preview_context_.generate_draft_pages()) { + DCHECK(!draft_metafile.get()); + draft_metafile.reset( + print_preview_context_.metafile()->GetMetafileForCurrentPage()); + } + return PreviewPageRendered(page_number, draft_metafile.get()); +} + +bool PrintWebViewHelper::PrintPagesNative(WebKit::WebFrame* frame, + const WebKit::WebNode& node, + int page_count, + const gfx::Size& canvas_size) { + NativeMetafile metafile; + if (!metafile.Init()) + return false; + + const PrintMsg_PrintPages_Params& params = *print_pages_params_; + std::vector printed_pages; + + if (params.pages.empty()) { + for (int i = 0; i < page_count; ++i) { + printed_pages.push_back(i); + } + } else { + // TODO(vitalybuka): redesign to make more code cross platform. + for (size_t i = 0; i < params.pages.size(); ++i) { + if (params.pages[i] >= 0 && params.pages[i] < page_count) { + printed_pages.push_back(params.pages[i]); + } + } + } + + if (printed_pages.empty()) + return false; + + PrintMsg_PrintPage_Params page_params; + page_params.params = params.params; + for (size_t i = 0; i < printed_pages.size(); ++i) { + page_params.page_number = printed_pages[i]; + PrintPageInternal(page_params, canvas_size, frame, &metafile); + } + + // WebKit::printEnd() for PDF should be called before metafile is closed. + FinishFramePrinting(); + + metafile.FinishDocument(); + + // Get the size of the resulting metafile. + uint32 buf_size = metafile.GetDataSize(); + DCHECK_GT(buf_size, 0u); + +#if defined(OS_CHROMEOS) || defined(OS_ANDROID) + int sequence_number = -1; + base::FileDescriptor fd; + + // Ask the browser to open a file for us. + Send(new PrintHostMsg_AllocateTempFileForPrinting(routing_id(), + &fd, + &sequence_number)); + if (!metafile.SaveToFD(fd)) + return false; + + // Tell the browser we've finished writing the file. + Send(new PrintHostMsg_TempFileForPrintingWritten(routing_id(), + sequence_number)); + return true; +#else + PrintHostMsg_DidPrintPage_Params printed_page_params; + printed_page_params.data_size = 0; + printed_page_params.document_cookie = params.params.document_cookie; + + { + scoped_ptr shared_mem( + content::RenderThread::Get()->HostAllocateSharedMemoryBuffer( + buf_size).release()); + if (!shared_mem.get()) { + NOTREACHED() << "AllocateSharedMemoryBuffer failed"; + return false; + } + + if (!shared_mem->Map(buf_size)) { + NOTREACHED() << "Map failed"; + return false; + } + metafile.GetData(shared_mem->memory(), buf_size); + printed_page_params.data_size = buf_size; + shared_mem->GiveToProcess(base::GetCurrentProcessHandle(), + &(printed_page_params.metafile_data_handle)); + } + + for (size_t i = 0; i < printed_pages.size(); ++i) { + printed_page_params.page_number = printed_pages[i]; + Send(new PrintHostMsg_DidPrintPage(routing_id(), printed_page_params)); + // Send the rest of the pages with an invalid metafile handle. + printed_page_params.metafile_data_handle.fd = -1; + } + return true; +#endif // defined(OS_CHROMEOS) +} + +void PrintWebViewHelper::PrintPageInternal( + const PrintMsg_PrintPage_Params& params, + const gfx::Size& canvas_size, + WebFrame* frame, + Metafile* metafile) { + PageSizeMargins page_layout_in_points; + double scale_factor = 1.0f; + ComputePageLayoutInPointsForCss(frame, params.page_number, params.params, + ignore_css_margins_, &scale_factor, + &page_layout_in_points); + gfx::Size page_size; + gfx::Rect content_area; + GetPageSizeAndContentAreaFromPageLayout(page_layout_in_points, &page_size, + &content_area); + gfx::Rect canvas_area = + params.params.display_header_footer ? gfx::Rect(page_size) : content_area; + + SkDevice* device = metafile->StartPageForVectorCanvas(page_size, canvas_area, + scale_factor); + if (!device) + return; + + // The printPage method take a reference to the canvas we pass down, so it + // can't be a stack object. + skia::RefPtr canvas = + skia::AdoptRef(new skia::VectorCanvas(device)); + MetafileSkiaWrapper::SetMetafileOnCanvas(*canvas, metafile); + skia::SetIsDraftMode(*canvas, is_print_ready_metafile_sent_); + + if (params.params.display_header_footer) { + // |page_number| is 0-based, so 1 is added. + // TODO(vitalybuka) : why does it work only with 1.25? + PrintHeaderAndFooter(canvas.get(), params.page_number + 1, + print_preview_context_.total_page_count(), + scale_factor / 1.25, + page_layout_in_points, *header_footer_info_, + params.params); + } + RenderPageContent(frame, params.page_number, canvas_area, content_area, + scale_factor, canvas.get()); + + // Done printing. Close the device context to retrieve the compiled metafile. + if (!metafile->FinishPage()) + NOTREACHED() << "metafile failed"; +} + +} // namespace printing diff --git a/pool/shard001/C++/0024018_CoreScreen_real.cpp b/pool/shard001/C++/0024018_CoreScreen_real.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f9a0421de42034a224ea9e300d5405b46a24db0d --- /dev/null +++ b/pool/shard001/C++/0024018_CoreScreen_real.cpp @@ -0,0 +1,213 @@ +/* + (c) Copyright 2012-2013 DirectFB integrated media GmbH + (c) Copyright 2001-2013 The world wide DirectFB Open Source Community (directfb.org) + (c) Copyright 2000-2004 Convergence (integrated media) GmbH + + All rights reserved. + + Written by Denis Oliver Kropp , + Andreas Shimokawa , + Marek Pikarski , + Sven Neumann , + Ville Syrjälä and + Claudio Ciccani . + + 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., 59 Temple Place - Suite 330, + Boston, MA 02111-1307, USA. +*/ + + + +#include + +#include "CoreScreen.h" + +extern "C" { +#include + +#include +#include +#include +#include + +#include +} + +D_DEBUG_DOMAIN( DirectFB_CoreScreen, "DirectFB/CoreScreen", "DirectFB CoreScreen" ); + +/*********************************************************************************************************************/ + +namespace DirectFB { + + + +DFBResult +IScreen_Real::SetPowerMode( + DFBScreenPowerMode mode +) +{ + D_DEBUG_AT( DirectFB_CoreScreen, "IScreen_Real::%s()\n", __FUNCTION__ ); + + return dfb_screen_set_powermode( obj, mode ); +} + + +DFBResult +IScreen_Real::WaitVSync( + +) +{ + D_DEBUG_AT( DirectFB_CoreScreen, "IScreen_Real::%s()\n", __FUNCTION__ ); + + return dfb_screen_wait_vsync( obj ); +} + + +DFBResult +IScreen_Real::GetVSyncCount( + u64 *ret_count +) +{ + DFBResult ret; + unsigned long count; + + D_DEBUG_AT( DirectFB_CoreScreen, "IScreen_Real::%s()\n", __FUNCTION__ ); + + ret = dfb_screen_get_vsync_count( obj, &count ); + if (ret) + return ret; + + *ret_count = count; + + return DFB_OK; +} + + +DFBResult +IScreen_Real::TestMixerConfig( + u32 mixer, + const DFBScreenMixerConfig *config, + DFBScreenMixerConfigFlags *ret_failed +) +{ + D_DEBUG_AT( DirectFB_CoreScreen, "IScreen_Real::%s()\n", __FUNCTION__ ); + + D_ASSERT( config != NULL ); + + return dfb_screen_test_mixer_config( obj, mixer, config, ret_failed ); +} + + +DFBResult +IScreen_Real::SetMixerConfig( + u32 mixer, + const DFBScreenMixerConfig *config +) +{ + D_DEBUG_AT( DirectFB_CoreScreen, "IScreen_Real::%s()\n", __FUNCTION__ ); + + D_ASSERT( config != NULL ); + + return dfb_screen_set_mixer_config( obj, mixer, config ); +} + + +DFBResult +IScreen_Real::TestEncoderConfig( + u32 encoder, + const DFBScreenEncoderConfig *config, + DFBScreenEncoderConfigFlags *ret_failed +) +{ + D_DEBUG_AT( DirectFB_CoreScreen, "IScreen_Real::%s()\n", __FUNCTION__ ); + + D_ASSERT( config != NULL ); + + return dfb_screen_test_encoder_config( obj, encoder, config, ret_failed ); +} + + +DFBResult +IScreen_Real::SetEncoderConfig( + u32 encoder, + const DFBScreenEncoderConfig *config +) +{ + D_DEBUG_AT( DirectFB_CoreScreen, "IScreen_Real::%s()\n", __FUNCTION__ ); + + D_ASSERT( config != NULL ); + + return dfb_screen_set_encoder_config( obj, encoder, config ); +} + + +DFBResult +IScreen_Real::TestOutputConfig( + u32 output, + const DFBScreenOutputConfig *config, + DFBScreenOutputConfigFlags *ret_failed +) +{ + D_DEBUG_AT( DirectFB_CoreScreen, "IScreen_Real::%s()\n", __FUNCTION__ ); + + D_ASSERT( config != NULL ); + + return dfb_screen_test_output_config( obj, output, config, ret_failed ); +} + + +DFBResult +IScreen_Real::SetOutputConfig( + u32 output, + const DFBScreenOutputConfig *config +) +{ + D_DEBUG_AT( DirectFB_CoreScreen, "IScreen_Real::%s()\n", __FUNCTION__ ); + + D_ASSERT( config != NULL ); + + return dfb_screen_set_output_config( obj, output, config ); +} + + +DFBResult +IScreen_Real::GetScreenSize( + DFBDimension *ret_size +) +{ + D_DEBUG_AT( DirectFB_CoreScreen, "IScreen_Real::%s()\n", __FUNCTION__ ); + + D_ASSERT( ret_size != NULL ); + + return dfb_screen_get_screen_size( obj, &ret_size->w, &ret_size->h ); +} + + +DFBResult +IScreen_Real::GetLayerDimension( + CoreLayer *layer, + DFBDimension *ret_size +) +{ + D_DEBUG_AT( DirectFB_CoreScreen, "IScreen_Real::%s()\n", __FUNCTION__ ); + + D_ASSERT( layer != NULL ); + D_ASSERT( ret_size != NULL ); + + return dfb_screen_get_layer_dimension( obj, layer, &ret_size->w, &ret_size->h ); +} + + +} diff --git a/pool/shard001/C++/0024021_benchmark_hash.cpp b/pool/shard001/C++/0024021_benchmark_hash.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6435b6b3a8c5e7752dde17f7bcb823088fc50bde --- /dev/null +++ b/pool/shard001/C++/0024021_benchmark_hash.cpp @@ -0,0 +1,69 @@ + +// +// This source file is part of appleseed. +// Visit http://appleseedhq.net/ for additional information and resources. +// +// This software is released under the MIT license. +// +// Copyright (c) 2017 Francois Beaune, The appleseedhq Organization +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// + +// appleseed.foundation headers. +#include "foundation/math/hash.h" +#include "foundation/platform/types.h" +#include "foundation/utility/benchmark.h" + +using namespace foundation; + +BENCHMARK_SUITE(Foundation_Math_Hash) +{ + const uint32 N = 1000; + + struct Fixture + { + uint32 m_uint_result; + float m_float_result; + + Fixture() + : m_uint_result(0) + , m_float_result(0.0f) + { + } + }; + + BENCHMARK_CASE_F(HashUInt32, Fixture) + { + for (uint32 i = 0; i < N; ++i) + m_uint_result += hash_uint32(i); + } + + BENCHMARK_CASE_F(HashUInt32Pixar, Fixture) + { + for (uint32 i = 0; i < N; ++i) + m_float_result += hash_uint32_pixar(i, 12345678); + } + + BENCHMARK_CASE_F(MixUInt32, Fixture) + { + for (uint32 i = 0; i < N; ++i) + m_uint_result += mix_uint32(i, m_uint_result); + } +} diff --git a/pool/shard001/C++/0024025_main.cpp b/pool/shard001/C++/0024025_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6c5dd810b41b3ee863cb4f774babef92c718ae24 --- /dev/null +++ b/pool/shard001/C++/0024025_main.cpp @@ -0,0 +1,139 @@ +/* + * Sepheroth - main.cpp + * Copyright (C) 2014 Dave Moore + * + * This file is part of Sepheroth. + * + * Sepheroth is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * (This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Additional permission under GNU GPL version 3 section 7: + * + * If you modify this Program, or any covered work, by linking or combining it + * with the libraries referred to in README (or a modified version of said + * libraries), containing parts covered by the terms of said libraries, the + * licensors of this Program grant you additional permission to convey the + * resulting work. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "libtcod.hpp" +#include "defines.hpp" +#include "application.hpp" +#include "error.hpp" + +/* Global Debug flag */ +bool g_debug_mode{}; + +/* Global Debug counter */ +uint32_t g_debug_counter{}; + +/* Output a line to the console */ +void output_to_console(const std::string text) +{ + log_debug_message(__FILE__, __FUNCTION__); + + std::cout << text << std::endl; +} + +/* Debug logging function */ +void log_debug_message(std::string file_path, + const std::string function_name) +{ + if (g_debug_mode) { + time_t time_now{time(nullptr)}; + std::stringstream output_message{}; + std::ofstream log_file{}; + const size_t last_slash_index{file_path.find_last_of("\\/")}; + + tm local_time = *localtime(&time_now); + + output_message << "(" << std::setfill('0'); + output_message << std::setw(7) << g_debug_counter << ") ["; + output_message << std::setw(2) << local_time.tm_hour << ":"; + output_message << std::setw(2) << local_time.tm_min << ":"; + output_message << std::setw(2) << local_time.tm_sec; + output_message << std::setfill(' ') << "]: "; + + if (std::string::npos != last_slash_index) + file_path.erase(0, last_slash_index + 1); + + output_message << file_path << ": "; + output_message << function_name + + "()"; + + log_file.open(LOG_FILENAME, std::ios_base::app); + log_file << output_message.str() << std::endl; + log_file.close(); + + if (log_file.fail()) { + g_debug_mode = false; + output_to_console(get_error_message(__FUNCTION__, + ERROR_NO_WRITE_LOGGING_FILE)); + } + + ++g_debug_counter; + } +} + +/* Output a message as a modal dialog */ +void show_error(const std::string text) +{ + log_debug_message(__FILE__, __FUNCTION__); + + GtkWidget* dialog{}; + + dialog = gtk_message_dialog_new(nullptr, GTK_DIALOG_DESTROY_WITH_PARENT, + GTK_MESSAGE_ERROR, + GTK_BUTTONS_CLOSE, "%s", + CSTR(text)); + + gtk_window_set_position(GTK_WINDOW(dialog), GTK_WIN_POS_CENTER); + gtk_window_set_title(GTK_WINDOW(dialog), ERRORINFO); + gtk_dialog_run (GTK_DIALOG(dialog)); + gtk_widget_destroy(dialog); +} + +/* Main entry point into the program */ +int main (int argc, char *argv[]) +{ + int8_t exit_code{}; + auto *app = new Application(argc, argv); + GtkWidget *splash_screen{}; + + if (app->check_for_parameter(CLP_RUNTESTS)) + exit_code = app->run_unit_tests(); + else if (app->check_for_parameter(CLP_VERSION)) + exit_code = app->display_version_info(); + else if (app->check_for_parameter(CLP_LICENSE)) + exit_code = app->display_license_info(); + else { + app->initialise_GTK(); + app->display_startup_info(); + app->display_splash_screen(splash_screen); + app->display_console(FONT_FILENAME, CONSOLE_WIDTH, + CONSOLE_HEIGHT); + exit_code = app->start_game_engine(); + } + + delete app; + return exit_code; +} + diff --git a/pool/shard001/C++/0024029_MatrixUtil.cpp b/pool/shard001/C++/0024029_MatrixUtil.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1568d6bd93580495074ceadee241fcfb1b6f573f --- /dev/null +++ b/pool/shard001/C++/0024029_MatrixUtil.cpp @@ -0,0 +1,99 @@ +#include +#include +#include + +#include "MatrixUtil.h" + +void MatrixUtil::matrixRemoveRow(Eigen::MatrixXd & matrix, unsigned int rowToRemove) +{ + unsigned int numRows = matrix.rows()-1; + unsigned int numCols = matrix.cols(); + + if( rowToRemove < numRows ) + matrix.block(rowToRemove,0,numRows-rowToRemove,numCols) = matrix.block(rowToRemove+1,0,numRows-rowToRemove,numCols); + + matrix.conservativeResize(numRows,numCols); +} + +void MatrixUtil::matrixRemoveColumn(Eigen::MatrixXd& matrix, unsigned int colToRemove) +{ + unsigned int numRows = matrix.rows(); + unsigned int numCols = matrix.cols()-1; + + if( colToRemove < numCols ) + matrix.block(0,colToRemove,numRows,numCols-colToRemove) = matrix.block(0,colToRemove+1,numRows,numCols-colToRemove); + + matrix.conservativeResize(numRows,numCols); +} + +Eigen::MatrixXd MatrixUtil::loadMatrix(std::string filename, char delimiter) +{ + std::ifstream ifs(filename, std::ifstream::in); + if (!ifs) + { + throw std::runtime_error("Cannot read file '" + filename + "'!"); + } + + // Read number of columns from first line + std::string delim(1, delimiter); + std::string line; + std::getline(ifs, line); + std::vector strs; + boost::split(strs, line, boost::is_any_of(delim)); + auto cols = boost::lexical_cast(strs.back()); + + Eigen::MatrixXd mat = Eigen::MatrixXd::Zero(0, cols); + + // Read matrix entries from rest of file + unsigned i = 0; + while (std::getline(ifs, line)) + { + mat.conservativeResize(i+1, cols); + + strs.clear(); + boost::split(strs, line, boost::is_any_of(delim)); + + for (unsigned j = 0; j < cols; j++) + { + auto val = boost::lexical_cast(strs[j]); + mat(i, j) = val; + } + i++; + } + + ifs.close(); + + return mat; +} + +void MatrixUtil::saveMatrix(const Eigen::MatrixXd & mat, std::string filename, char delimiter) +{ + std::ofstream ofs(filename, std::ifstream::out); + + if (!ofs) + { + throw std::runtime_error("Cannot open file '" + filename + "' for writing!"); + } + + unsigned rows = mat.rows(); + unsigned cols = mat.cols(); + + // Write first line with number of dimensions + ofs << cols << '\n'; + + // Write rest of matrix to file + for (unsigned i = 0; i < rows; i++) + { + for (unsigned j = 0; j < cols; j++) + { + ofs << mat(i, j); + if (j < cols - 1) + { + ofs << delimiter; + } + } + ofs << '\n'; + } + + ofs.close(); +} diff --git a/pool/shard001/C++/0024030_perf.cpp b/pool/shard001/C++/0024030_perf.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4a9d153737e9a9cb1cd49c185eecc3b23620032d --- /dev/null +++ b/pool/shard001/C++/0024030_perf.cpp @@ -0,0 +1,255 @@ +/* Copyright 2016-present Facebook, Inc. + * Licensed under the Apache License, Version 2.0 */ + +#include "watchman_system.h" +#include "watchman.h" +#include +#include +#include +#include "ChildProcess.h" +#include "Logging.h" +#include "watchman_perf.h" + +using namespace watchman; +using Options = ChildProcess::Options; +using Environment = ChildProcess::Environment; + +namespace { +class PerfLogThread { + folly::Synchronized samples_; + std::thread thread_; + std::condition_variable cond_; + + void loop() noexcept; + + public: + PerfLogThread() : thread_([this] { loop(); }) {} + + ~PerfLogThread() { + cond_.notify_all(); + thread_.join(); + } + + void addSample(json_ref&& sample) { + auto wlock = samples_.lock(); + if (!*wlock) { + *wlock = json_array(); + } + json_array_append_new(*wlock, std::move(sample)); + cond_.notify_one(); + } +}; + +PerfLogThread& getPerfThread() { + // Get the perf logging thread, starting it on the first call. + // Meyer's singleton! + static PerfLogThread perfThread; + return perfThread; +} +} + +watchman_perf_sample::watchman_perf_sample(const char* description) + : description(description) { + gettimeofday(&time_begin, nullptr); +#ifdef HAVE_SYS_RESOURCE_H + getrusage(RUSAGE_SELF, &usage_begin); +#endif +} + +bool watchman_perf_sample::finish() { + gettimeofday(&time_end, nullptr); + w_timeval_sub(time_end, time_begin, &duration); +#ifdef HAVE_SYS_RESOURCE_H + getrusage(RUSAGE_SELF, &usage_end); + + // Compute the delta for the usage + w_timeval_sub(usage_end.ru_utime, usage_begin.ru_utime, &usage.ru_utime); + w_timeval_sub(usage_end.ru_stime, usage_begin.ru_stime, &usage.ru_stime); + +#define DIFFU(n) usage.n = usage_end.n - usage_begin.n + DIFFU(ru_maxrss); + DIFFU(ru_ixrss); + DIFFU(ru_idrss); + DIFFU(ru_minflt); + DIFFU(ru_majflt); + DIFFU(ru_nswap); + DIFFU(ru_inblock); + DIFFU(ru_oublock); + DIFFU(ru_msgsnd); + DIFFU(ru_msgrcv); + DIFFU(ru_nsignals); + DIFFU(ru_nvcsw); + DIFFU(ru_nivcsw); +#undef DIFFU +#endif + + if (!will_log) { + if (wall_time_elapsed_thresh == 0) { + auto thresh = cfg_get_json("perf_sampling_thresh"); + if (thresh) { + if (thresh.isNumber()) { + wall_time_elapsed_thresh = json_number_value(thresh); + } else { + wall_time_elapsed_thresh = json_number_value( + thresh.get_default(description, json_real(0.0))); + } + } + } + + if (wall_time_elapsed_thresh > 0 && + w_timeval_diff(time_begin, time_end) > wall_time_elapsed_thresh) { + will_log = true; + } + } + + return will_log; +} + +void watchman_perf_sample::add_meta(const char* key, json_ref&& val) { + if (!meta_data) { + meta_data = json_object(); + } + meta_data.set(key, std::move(val)); +} + +void watchman_perf_sample::add_root_meta( + const std::shared_ptr& root) { + // Note: if the root lock isn't held, we may read inaccurate numbers for + // some of these properties. We're ok with that, and don't want to force + // the root lock to be re-acquired just for this. + auto meta = json_object( + {{"path", w_string_to_json(root->root_path)}, + {"recrawl_count", json_integer(root->recrawlInfo.rlock()->recrawlCount)}, + {"case_sensitive", json_boolean(root->case_sensitive == CaseSensitivity::CaseSensitive)}}); + + // During recrawl, the view may be re-assigned. Protect against + // reading a nullptr. + auto view = root->view(); + if (view) { + meta.set({{"watcher", w_string_to_json(view->getName())}}); + } + + add_meta("root", std::move(meta)); +} + +void watchman_perf_sample::set_wall_time_thresh(double thresh) { + wall_time_elapsed_thresh = thresh; +} + +void watchman_perf_sample::force_log() { + will_log = true; +} + +void PerfLogThread::loop() noexcept { + json_ref samples; + json_ref perf_cmd; + int64_t sample_batch; + + w_set_thread_name("perflog"); + + auto stateDir = w_string_piece(watchman_state_file).dirName().asWString(); + + perf_cmd = cfg_get_json("perf_logger_command"); + if (perf_cmd.isString()) { + perf_cmd = json_array({perf_cmd}); + } + if (!perf_cmd.isArray()) { + w_log( + W_LOG_FATAL, + "perf_logger_command must be either a string or an array of strings\n"); + } + + sample_batch = cfg_get_int("perf_logger_command_max_samples_per_call", 4); + + while (!w_is_stopping()) { + { + auto wlock = samples_.lock(); + if (!*wlock) { + cond_.wait(wlock.getUniqueLock()); + } + + samples = nullptr; + std::swap(samples, *wlock); + } + + if (samples) { + while (json_array_size(samples) > 0) { + int i = 0; + auto cmd = json_array(); + + json_array_extend(cmd, perf_cmd); + + while (i < sample_batch && json_array_size(samples) > 0) { + char *stringy = json_dumps(json_array_get(samples, 0), 0); + if (stringy) { + json_array_append_new( + cmd, typed_string_to_json(stringy, W_STRING_MIXED)); + free(stringy); + } + json_array_remove(samples, 0); + i++; + } + + ChildProcess::Options opts; + opts.environment().set({{"WATCHMAN_STATE_DIR", stateDir}, + {"WATCHMAN_SOCK", get_sock_name()}}); + opts.open(STDIN_FILENO, "/dev/null", O_RDONLY, 0666); + opts.open(STDOUT_FILENO, "/dev/null", O_WRONLY, 0666); + opts.open(STDERR_FILENO, "/dev/null", O_WRONLY, 0666); + + try { + ChildProcess proc(cmd, std::move(opts)); + proc.wait(); + } catch (const std::exception& exc) { + watchman::log( + watchman::ERR, "failed to spawn perf logger: ", exc.what(), "\n"); + } + } + } + } +} + +void watchman_perf_sample::log() { + char *dumped = NULL; + + if (!will_log) { + return; + } + + // Assemble a perf blob + auto info = json_object( + {{"description", typed_string_to_json(description)}, + {"meta", meta_data}, + {"pid", json_integer(::getpid())}, + {"version", typed_string_to_json(PACKAGE_VERSION, W_STRING_UNICODE)}}); + +#ifdef WATCHMAN_BUILD_INFO + info.set( + "buildinfo", typed_string_to_json(WATCHMAN_BUILD_INFO, W_STRING_UNICODE)); +#endif + +#define ADDTV(name, tv) info.set(name, json_real(w_timeval_abs_seconds(tv))) + ADDTV("elapsed_time", duration); + ADDTV("start_time", time_begin); +#ifdef HAVE_SYS_RESOURCE_H + ADDTV("user_time", usage.ru_utime); + ADDTV("system_time", usage.ru_stime); +#endif // HAVE_SYS_RESOURCE_H +#undef ADDTV + + // Log to the log file + dumped = json_dumps(info, 0); + w_log(W_LOG_ERR, "PERF: %s\n", dumped); + free(dumped); + + if (!cfg_get_json("perf_logger_command")) { + return; + } + + // Send this to our logging thread for async processing + auto& perfThread = getPerfThread(); + perfThread.addSample(std::move(info)); +} + +/* vim:ts=2:sw=2:et: + */ diff --git a/pool/shard001/C++/0024044_window_shopnumber.cpp b/pool/shard001/C++/0024044_window_shopnumber.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0fc6758f17247bfef66ad5be39c91c90901af77e --- /dev/null +++ b/pool/shard001/C++/0024044_window_shopnumber.cpp @@ -0,0 +1,90 @@ +/* + * This file is part of EasyRPG Player. + * + * EasyRPG Player 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. + * + * EasyRPG Player 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 EasyRPG Player. If not, see . + */ + +// Headers +#include +#include "game_system.h" +#include "input.h" +#include "util_macro.h" +#include "window_shopnumber.h" +#include "bitmap.h" +#include "font.h" +#include "reader_util.h" + +Window_ShopNumber::Window_ShopNumber(int ix, int iy, int iwidth, int iheight) : + Window_Base(ix, iy, iwidth, iheight), + item_max(1), price(0), number(1), item_id(0) { + + SetContents(Bitmap::Create(width - 16, height - 16)); + contents->Clear(); +} + +void Window_ShopNumber::SetData(int item_id, int item_max, int price) { + this->item_id = item_id; + this->item_max = min(item_max, 99); + this->price = price; + number = 1; +} + +void Window_ShopNumber::Refresh() { + contents->Clear(); + + int y = 34; + // (Shop) items are guaranteed to be valid + DrawItemName(*ReaderUtil::GetElement(Data::items, item_id), 0, y); + + std::stringstream ss; + ss << number; + + contents->TextDraw(132, y, Font::ColorDefault, "x"); + contents->TextDraw(132 + 30, y, Font::ColorDefault, ss.str(), Text::AlignRight); + SetCursorRect(Rect(132 + 14, y - 2, 20, 16)); + + DrawCurrencyValue(GetTotal(), contents->GetWidth(), y + 32); +} + +int Window_ShopNumber::GetNumber() const { + return number; +} + +void Window_ShopNumber::Update() { + Window_Base::Update(); + + if (active) { + int last_number = number; + if (Input::IsRepeated(Input::RIGHT) && number < item_max) { + number++; + } else if (Input::IsRepeated(Input::LEFT) && number > 1) { + number--; + } else if ((Input::IsRepeated(Input::UP) || Input::IsTriggered(Input::SCROLL_UP)) + && number < item_max) { + number = min(number + 10, item_max); + } else if ((Input::IsRepeated(Input::DOWN) || Input::IsTriggered(Input::SCROLL_DOWN)) + && number > 1) { + number = max(number - 10, 1); + } + + if (last_number != number) { + Game_System::SePlay(Game_System::GetSystemSE(Game_System::SFX_Cursor)); + Refresh(); + } + } +} + +int Window_ShopNumber::GetTotal() const { + return price * number; +} diff --git a/pool/shard001/C++/0024048_compression_trainer_dump.cpp b/pool/shard001/C++/0024048_compression_trainer_dump.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f5b8f340fb2fbb9e94b0d6d4d4c242f9195790bd --- /dev/null +++ b/pool/shard001/C++/0024048_compression_trainer_dump.cpp @@ -0,0 +1,182 @@ + +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#ifdef LIBREVERSE_DEBUG +#include +#include +#endif + +#include "Compression_Dump_Algorithm.h" +#include "Compression_Dump_Algorithm_Factory.h" +#include "Optimizer_Types.h" + +#ifdef LIBREVERSE_DEBUG +using namespace reverse::trace; +#endif /* LIBREVERSE_DEBUG */ + +using namespace reverse::classifier; +using namespace reverse::optimizer; + +void help ( boost::program_options::options_description& desc ) +{ + std::cout << desc << std::endl << std::endl + << "Support type values:" << std::endl + << " windows_pe" << std::endl; + exit ( 0 ); +} + +int main (int ac, char** av) +{ + // Get start directory name from options. + // IF not present start with present directory ('.') + boost::program_options::options_description desc("Allowed options"); + desc.add_options() + ("help", "produce help message") + ("compiler_name", boost::program_options::value(), "Unique string name describing the compiler") + ("compiler_id", boost::program_options::value(), "Unique numerical id describing the compiler") + ("source_type", boost::program_options::value(), "Type of input files [required]" ) + ("directory", boost::program_options::value(), "Directory to start searching"); + + boost::program_options::variables_map vm; + + try { + boost::program_options::store(boost::program_options::parse_command_line(ac, av, desc), vm); + boost::program_options::notify(vm); + } + catch ( boost::program_options::unknown_option& ) + { + help ( desc ); + } + catch ( boost::program_options::invalid_command_line_syntax& ic ) + { + std::cout << ic.what() << std::endl; + help ( desc ); + } + + if (vm.count("help")) { + help ( desc ); + } + + std::string directory_string = "."; + + if (vm.count("directory")) + { + std::cout << "Directory to find files was set to....: " + << vm["directory"].as() << "." << std::endl; + + directory_string = vm["directory"].as(); + } + else + { + help ( desc ); + } + + std::string compiler_name_string = ""; + + if (vm.count("compiler_name")) + { + std::cout << "Compiler name was set to................: " + << vm["compiler_name"].as() << "." << std::endl; + + compiler_name_string = vm["compiler_name"].as(); + } + else + { + std::cout << "Compiler name tag must be specified. Use the flag --compiler_name to set the tag" << std::endl; + help ( desc ); + } + + boost::uint32_t compiler_id = 0; + if ( vm.count ( "compiler_id" ) ) + { + std::cout << "Compiler id was set to................: " + << vm["compiler_id"].as() << "." << std::endl; + + compiler_id = vm["compiler_id"].as(); + } + else + { + std::cout << "Compiler id tag must be specified. Use the flag --compiler_id to set the tag" << std::endl; + help ( desc ); + } + + std::string source_type = ""; + if ( vm.count ( "source_type" ) ) + { + std::cout << "Source_type was set to................: " + << vm["source_type"].as() << "." << std::endl; + + source_type = vm["source_type"].as(); + } + else + { + std::cout << "Source type tag must be specified. Use the flag --source_type to set the tag" << std::endl; + help ( desc ); + } + +#ifdef LIBREVERSE_DEBUG + Trace_State::Instance().set_Trace_Level ( reverse::api::TraceLevel::DATA ); + Trace_State::Instance().set_Trace_Area_Mask ( reverse::api::TraceArea::IO ); + Trace_State::Instance().open_Trace_File (); +#endif + + // open output file + std::stringstream filename; + filename << boost::str ( boost::format ( "test_data_%1%.xml") % compiler_name_string ); + + std::ofstream xml_file ( (filename.str()).c_str() ); + xml_file << "" << std::endl; + xml_file << "" << std::endl; + + GRNN_Data_Types::Value_Type source_value = GRNN_Data_Types::get_Type(source_type); + + if ( source_value == GRNN_Data_Types::UNKNOWN ) + { + std::cout << "Invalid input source type" << std::endl; + help ( desc ); + } + + try + { + // Get the algorithm for this file type + reverse::optimizer_types::Compression_Dump_Algorithm::ptr_t alg_ptr = + ( Compression_Dump_Algorithm_Factory::Instance() ).get_Algorithm ( source_value ); + + // Get list of target files found recursively from all directories below starting directory. + std::vector target_files; + boost::filesystem::path dir_path ( directory_string ); + + alg_ptr->find_Files ( dir_path, target_files ); + + // For each file found + for ( std::vector::const_iterator cpos = target_files.begin(); + cpos != target_files.end(); + ++cpos ) + { + xml_file << alg_ptr->process ( compiler_id, *cpos ); + } + + // close output file + xml_file << "" << std::endl; + xml_file.close(); + +#ifdef LIBREVERSE_DEBUG + Trace_State::Instance().close_Trace_File (); +#endif + } + catch ( std::exception& ) + { + std::cout << "Unsupported file type. Contact reverse developers if you believe they should support the target file type" << std::endl; + } + + return 0; +} diff --git a/pool/shard001/C++/0024049_PatternMultiTopicsConsumerImpl.cc b/pool/shard001/C++/0024049_PatternMultiTopicsConsumerImpl.cc new file mode 100644 index 0000000000000000000000000000000000000000..95f8a36ec2b2cb11518650c1a55850c7ccd71d65 --- /dev/null +++ b/pool/shard001/C++/0024049_PatternMultiTopicsConsumerImpl.cc @@ -0,0 +1,235 @@ +/** + * 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 "PatternMultiTopicsConsumerImpl.h" + +DECLARE_LOG_OBJECT() + +using namespace pulsar; + +PatternMultiTopicsConsumerImpl::PatternMultiTopicsConsumerImpl(ClientImplPtr client, + const std::string pattern, + const std::vector& topics, + const std::string& subscriptionName, + const ConsumerConfiguration& conf, + const LookupServicePtr lookupServicePtr_) + : MultiTopicsConsumerImpl(client, topics, subscriptionName, TopicName::get(pattern), conf, + lookupServicePtr_), + patternString_(pattern), + pattern_(std::regex(pattern)), + autoDiscoveryTimer_(), + autoDiscoveryRunning_(false) {} + +const std::regex PatternMultiTopicsConsumerImpl::getPattern() { return pattern_; } + +void PatternMultiTopicsConsumerImpl::resetAutoDiscoveryTimer() { + autoDiscoveryRunning_ = false; + autoDiscoveryTimer_->expires_from_now(seconds(conf_.getPatternAutoDiscoveryPeriod())); + autoDiscoveryTimer_->async_wait( + boost::bind(&PatternMultiTopicsConsumerImpl::autoDiscoveryTimerTask, this, _1)); +} + +void PatternMultiTopicsConsumerImpl::autoDiscoveryTimerTask(const boost::system::error_code& err) { + if (err == boost::asio::error::operation_aborted) { + LOG_DEBUG(getName() << "Timer cancelled: " << err.message()); + return; + } else if (err) { + LOG_ERROR(getName() << "Timer error: " << err.message()); + return; + } + + if (state_ != Ready) { + LOG_ERROR("Error in autoDiscoveryTimerTask consumer state not ready: " << state_); + resetAutoDiscoveryTimer(); + return; + } + + if (autoDiscoveryRunning_) { + LOG_DEBUG("autoDiscoveryTimerTask still running, cancel this running. "); + return; + } + + autoDiscoveryRunning_ = true; + + // already get namespace from pattern. + assert(namespaceName_); + + lookupServicePtr_->getTopicsOfNamespaceAsync(namespaceName_) + .addListener(boost::bind(&PatternMultiTopicsConsumerImpl::timerGetTopicsOfNamespace, this, _1, _2)); +} + +void PatternMultiTopicsConsumerImpl::timerGetTopicsOfNamespace(const Result result, + const NamespaceTopicsPtr topics) { + if (result != ResultOk) { + LOG_ERROR("Error in Getting topicsOfNameSpace. result: " << result); + resetAutoDiscoveryTimer(); + return; + } + + NamespaceTopicsPtr newTopics = PatternMultiTopicsConsumerImpl::topicsPatternFilter(*topics, pattern_); + // get old topics in consumer: + NamespaceTopicsPtr oldTopics = boost::make_shared>(); + for (std::map::iterator it = topicsPartitions_.begin(); it != topicsPartitions_.end(); + it++) { + oldTopics->push_back(it->first); + } + NamespaceTopicsPtr topicsAdded = topicsListsMinus(*newTopics, *oldTopics); + NamespaceTopicsPtr topicsRemoved = topicsListsMinus(*oldTopics, *newTopics); + + // callback method when removed topics all un-subscribed. + ResultCallback topicsRemovedCallback = [this](Result result) { + if (result != ResultOk) { + LOG_ERROR("Failed to unsubscribe topics: " << result); + } + resetAutoDiscoveryTimer(); + }; + + // callback method when added topics all subscribed. + ResultCallback topicsAddedCallback = [this, topicsRemoved, topicsRemovedCallback](Result result) { + if (result == ResultOk) { + // call to unsubscribe all removed topics. + onTopicsRemoved(topicsRemoved, topicsRemovedCallback); + } else { + resetAutoDiscoveryTimer(); + } + }; + + // call to subscribe new added topics, then in its callback do unsubscribe + onTopicsAdded(topicsAdded, topicsAddedCallback); +} + +void PatternMultiTopicsConsumerImpl::onTopicsAdded(NamespaceTopicsPtr addedTopics, ResultCallback callback) { + // start call subscribeOneTopicAsync for each single topic + + if (addedTopics->empty()) { + LOG_DEBUG("no topics need subscribe"); + callback(ResultOk); + return; + } + int topicsNumber = addedTopics->size(); + + boost::shared_ptr> topicsNeedCreate = boost::make_shared>(topicsNumber); + // subscribe for each passed in topic + for (std::vector::const_iterator itr = addedTopics->begin(); itr != addedTopics->end(); + itr++) { + MultiTopicsConsumerImpl::subscribeOneTopicAsync(*itr).addListener( + boost::bind(&PatternMultiTopicsConsumerImpl::handleOneTopicAdded, this, _1, *itr, + topicsNeedCreate, callback)); + } +} + +void PatternMultiTopicsConsumerImpl::handleOneTopicAdded(const Result result, const std::string& topic, + boost::shared_ptr> topicsNeedCreate, + ResultCallback callback) { + int previous = topicsNeedCreate->fetch_sub(1); + assert(previous > 0); + + if (result != ResultOk) { + LOG_ERROR("Failed when subscribed to topic " << topic << " Error - " << result); + callback(result); + return; + } + + if (topicsNeedCreate->load() == 0) { + LOG_DEBUG("Subscribed all new added topics"); + callback(result); + } +} + +void PatternMultiTopicsConsumerImpl::onTopicsRemoved(NamespaceTopicsPtr removedTopics, + ResultCallback callback) { + // start call subscribeOneTopicAsync for each single topic + if (removedTopics->empty()) { + LOG_DEBUG("no topics need unsubscribe"); + callback(ResultOk); + return; + } + int topicsNumber = removedTopics->size(); + + boost::shared_ptr> topicsNeedUnsub = boost::make_shared>(topicsNumber); + ResultCallback oneTopicUnsubscribedCallback = [this, topicsNeedUnsub, callback](Result result) { + int previous = topicsNeedUnsub->fetch_sub(1); + assert(previous > 0); + + if (result != ResultOk) { + LOG_ERROR("Failed when unsubscribe to one topic. Error - " << result); + callback(result); + return; + } + + if (topicsNeedUnsub->load() == 0) { + LOG_DEBUG("unSubscribed all needed topics"); + callback(result); + } + }; + + // unsubscribe for each passed in topic + for (std::vector::const_iterator itr = removedTopics->begin(); itr != removedTopics->end(); + itr++) { + MultiTopicsConsumerImpl::unsubscribeOneTopicAsync(*itr, oneTopicUnsubscribedCallback); + } +} + +NamespaceTopicsPtr PatternMultiTopicsConsumerImpl::topicsPatternFilter(const std::vector& topics, + const std::regex& pattern) { + NamespaceTopicsPtr topicsResultPtr = boost::make_shared>(); + + for (std::vector::const_iterator itr = topics.begin(); itr != topics.end(); itr++) { + if (std::regex_match(*itr, pattern)) { + topicsResultPtr->push_back(*itr); + } + } + return topicsResultPtr; +} + +NamespaceTopicsPtr PatternMultiTopicsConsumerImpl::topicsListsMinus(std::vector& list1, + std::vector& list2) { + NamespaceTopicsPtr topicsResultPtr = boost::make_shared>(); + std::remove_copy_if(list1.begin(), list1.end(), std::back_inserter(*topicsResultPtr), + [&list2](const std::string& arg) { + return (std::find(list2.begin(), list2.end(), arg) != list2.end()); + }); + + return topicsResultPtr; +} + +void PatternMultiTopicsConsumerImpl::start() { + MultiTopicsConsumerImpl::start(); + + LOG_DEBUG("PatternMultiTopicsConsumerImpl start autoDiscoveryTimer_."); + + // Init autoDiscoveryTimer task only once, wait for the timeout to happen + if (!autoDiscoveryTimer_ && conf_.getPatternAutoDiscoveryPeriod() > 0) { + autoDiscoveryTimer_ = client_->getIOExecutorProvider()->get()->createDeadlineTimer(); + autoDiscoveryTimer_->expires_from_now(seconds(conf_.getPatternAutoDiscoveryPeriod())); + autoDiscoveryTimer_->async_wait( + boost::bind(&PatternMultiTopicsConsumerImpl::autoDiscoveryTimerTask, this, _1)); + } +} + +void PatternMultiTopicsConsumerImpl::shutdown() { + Lock lock(mutex_); + state_ = Closed; + autoDiscoveryTimer_->cancel(); + multiTopicsConsumerCreatedPromise_.setFailed(ResultAlreadyClosed); +} + +void PatternMultiTopicsConsumerImpl::closeAsync(ResultCallback callback) { + MultiTopicsConsumerImpl::closeAsync(callback); + autoDiscoveryTimer_->cancel(); +} diff --git a/pool/shard001/C++/0024053_poly_item.cc b/pool/shard001/C++/0024053_poly_item.cc new file mode 100644 index 0000000000000000000000000000000000000000..c724ddf21d06cc4e5d65aa062f999f119ce1f13e --- /dev/null +++ b/pool/shard001/C++/0024053_poly_item.cc @@ -0,0 +1,159 @@ +/* + * Copyright (C) 2012 Carl Hetherington + * Copyright (C) 2013-2017 Paul Davis + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#include + +#include "pbd/compose.h" + +#include "canvas/poly_item.h" +#include "canvas/canvas.h" + +using namespace std; +using namespace ArdourCanvas; + +PolyItem::PolyItem (Canvas* c) + : Item (c) +{ +} + +PolyItem::PolyItem (Item* parent) + : Item (parent) +{ +} + +void +PolyItem::compute_bounding_box () const +{ + + if (!_points.empty()) { + + Rect bbox; + Points::const_iterator i = _points.begin(); + + bbox.x0 = bbox.x1 = i->x; + bbox.y0 = bbox.y1 = i->y; + + ++i; + + while (i != _points.end()) { + bbox.x0 = min (bbox.x0, i->x); + bbox.y0 = min (bbox.y0, i->y); + bbox.x1 = max (bbox.x1, i->x); + bbox.y1 = max (bbox.y1, i->y); + ++i; + } + + _bounding_box = bbox.expand (_outline_width + 0.5); + + + } else { + _bounding_box = Rect (); + } + + _bounding_box_dirty = false; +} + +void +PolyItem::render_path (Rect const & /* area */, Cairo::RefPtr context) const +{ + if (_points.size() < 2) { + return; + } + + Points::const_iterator i = _points.begin(); + Duple c (item_to_window (Duple (i->x, i->y))); + const double pixel_adjust = (_outline_width == 1.0 ? 0.5 : 0.0); + + context->move_to (c.x + pixel_adjust, c.y + pixel_adjust); + ++i; + + while (i != _points.end()) { + c = item_to_window (Duple (i->x, i->y)); + context->line_to (c.x + pixel_adjust, c.y + pixel_adjust); + ++i; + } +} + +void +PolyItem::render_curve (Rect const & area, Cairo::RefPtr context, Points const & first_control_points, Points const & second_control_points) const +{ + if (_points.size() <= 2) { + render_path (area, context); + return; + } + + Points::const_iterator cp1 = first_control_points.begin(); + Points::const_iterator cp2 = second_control_points.begin(); + Points::const_iterator p = _points.begin(); + const double pixel_adjust = (_outline_width == 1.0 ? 0.5 : 0.0); + + Duple c = item_to_window (Duple (p->x, p->y)); + context->move_to (c.x + pixel_adjust, c.y + pixel_adjust); + ++p; + + while (p != _points.end()) { + + Duple c1 = item_to_window (Duple (cp1->x, cp1->y)); + Duple c2 = item_to_window (Duple (cp2->x, cp2->y)); + + c = item_to_window (Duple (p->x, p->y)); + + context->curve_to (c1.x + pixel_adjust, + c1.y + pixel_adjust, + c2.x + pixel_adjust, + c2.y + pixel_adjust, + c.x + pixel_adjust, + c.y + pixel_adjust); + + ++cp1; + ++cp2; + ++p; + } +} + +void +PolyItem::set (Points const & points) +{ + if (_points != points) { + + begin_change (); + + _points = points; + + _bounding_box_dirty = true; + end_change (); + } +} + +Points const & +PolyItem::get () const +{ + return _points; +} + +void +PolyItem::dump (ostream& o) const +{ + Item::dump (o); + + o << _canvas->indent() << '\t' << _points.size() << " points" << endl; + for (Points::const_iterator i = _points.begin(); i != _points.end(); ++i) { + o << _canvas->indent() << "\t\t" << i->x << ", " << i->y << endl; + } +} diff --git a/pool/shard001/C++/0024058_pure_hashget_v_inp_gen_hw.cpp b/pool/shard001/C++/0024058_pure_hashget_v_inp_gen_hw.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9e8664af0205707a2331451e6ed5503077a5229d --- /dev/null +++ b/pool/shard001/C++/0024058_pure_hashget_v_inp_gen_hw.cpp @@ -0,0 +1,48 @@ +#include +#include +#include +#include +#include + +#pragma pack(push) +#pragma pack(1) + +#include + +//This file will NOT be overwritten by the code generator, if it already +//exists. make clean will also not remove this file. + +pure_hashgetVerifierInpGenHw::pure_hashgetVerifierInpGenHw(Venezia* v_) +{ + v = v_; + compiler_implementation.v = v_; +} + +//Refer to apps_sfdl_gen/pure_hashget_cons.h for constants to use when generating input. +void pure_hashgetVerifierInpGenHw::create_input(mpq_t* input_q, int num_inputs) +{ + struct In input; + struct Out output; + cout << "creating input..." << endl; + char db_file_path[BUFLEN]; + snprintf(db_file_path, BUFLEN - 1, "%s/block_stores/prover_1_%s", FOLDER_STATE, shared_bstore_file_name.c_str()); + HashBlockStore* bs = new ConfigurableBlockStore(db_file_path); + MerkleRAM* ram = new RAMImpl(bs); + setBlockStoreAndRAM(bs, ram); + + srand(time(NULL)); + for (int i = 0; i < NUM_OF_BLOCKS; i++) { + for (int j = 0; j < BLOCKLEN; j++) { + output.blocks[i].block[j] = rand(); + } + hashput(&(input.hashes[i]), &(output.blocks[i])); + hashget(&(output.blocks[i]), &(input.hashes[i])); + } + uint64_t* input_ptr = (uint64_t*)&input; + for (int i = 0; i < num_inputs; i++) { + mpq_set_ui(input_q[i], input_ptr[i], 1); + } + deleteBlockStoreAndRAM(); +} + +#pragma pack(pop) diff --git a/pool/shard001/C++/0024060_qgspythonrunner.cpp b/pool/shard001/C++/0024060_qgspythonrunner.cpp new file mode 100644 index 0000000000000000000000000000000000000000..eed4e0660565d19a221060c8b1262a88d7d2cf83 --- /dev/null +++ b/pool/shard001/C++/0024060_qgspythonrunner.cpp @@ -0,0 +1,60 @@ +/*************************************************************************** + qgspythonrunner.cpp + --------------------- + begin : May 2011 + copyright : (C) 2011 by Martin Dobias + email : wonder dot sk at gmail dot com + *************************************************************************** + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + ***************************************************************************/ +#include "qgspythonrunner.h" +#include "qgslogger.h" + +QgsPythonRunner *QgsPythonRunner::sInstance = nullptr; + +/////////////////////////// +// static methods + +bool QgsPythonRunner::isValid() +{ + return nullptr != sInstance; +} + +bool QgsPythonRunner::run( const QString &command, const QString &messageOnError ) +{ + if ( sInstance ) + { + QgsDebugMsg( "Running " + command ); + return sInstance->runCommand( command, messageOnError ); + } + else + { + QgsDebugMsg( QStringLiteral( "Unable to run Python command: runner not available!" ) ); + return false; + } +} + +bool QgsPythonRunner::eval( const QString &command, QString &result ) +{ + if ( sInstance ) + { + return sInstance->evalCommand( command, result ); + } + else + { + QgsDebugMsg( QStringLiteral( "Unable to run Python command: runner not available!" ) ); + return false; + } +} + +void QgsPythonRunner::setInstance( QgsPythonRunner *runner ) +{ + delete sInstance; + sInstance = runner; +} + diff --git a/pool/shard001/C++/0024066_cow_ptr_test.cc b/pool/shard001/C++/0024066_cow_ptr_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..5b055d7cb4d127dc20f2cf70869134f24a93d429 --- /dev/null +++ b/pool/shard001/C++/0024066_cow_ptr_test.cc @@ -0,0 +1,43 @@ +/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. */ + +#include "paddle/fluid/framework/details/cow_ptr.h" +#include "gtest/gtest.h" + +namespace paddle { +namespace framework { +namespace details { + +TEST(COWPtr, all) { + COWPtr ptr(new int{0}); + ASSERT_EQ(ptr.Data(), 0); + COWPtr ptr2 = ptr; + ASSERT_EQ(ptr2.Data(), 0); + ASSERT_EQ(&ptr2.Data(), &ptr.Data()); + *ptr2.MutableData() = 10; + ASSERT_EQ(ptr.Data(), 0); + ASSERT_EQ(ptr2.Data(), 10); +} + +TEST(COWPtr, change_old) { + COWPtr ptr(new int{0}); + COWPtr ptr2 = ptr; + *ptr.MutableData() = 10; + ASSERT_EQ(ptr2.Data(), 0); + ASSERT_EQ(ptr.Data(), 10); +} + +} // namespace details +} // namespace framework +} // namespace paddle diff --git a/pool/shard001/C++/0024067_greedy-bubble-tree.cc b/pool/shard001/C++/0024067_greedy-bubble-tree.cc new file mode 100644 index 0000000000000000000000000000000000000000..d1beb831ab01b865e872f59201d964a319ef4201 --- /dev/null +++ b/pool/shard001/C++/0024067_greedy-bubble-tree.cc @@ -0,0 +1,152 @@ +// +// Copyright (c) 2014, Adnan Ademovic +// 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 "bubblesmp/greedy-bubble-tree.h" + +#include +#include + +#include + +#include "bubblesmp/environment/environment-feedback.h" +#include "bubblesmp/bubble.h" + +namespace com { +namespace ademovic { +namespace bubblesmp { + +GreedyBubbleTree::~GreedyBubbleTree() {} + +GreedyBubbleTree::GreedyBubbleTree( + unsigned max_bubbles_per_branch, unsigned max_binary_search_depth, + const std::vector& root, + std::shared_ptr bubble_source, + double min_move_size, const IndexSettings& index_settings, + bool use_extended) + : RrtTree(root, index_settings), + max_bubbles_per_branch_(max_bubbles_per_branch), + max_binary_search_depth_(max_binary_search_depth), + bubble_source_(bubble_source), limits_(bubble_source->GetAngleRanges()), + min_move_size_(min_move_size), use_extended_(use_extended) { + CHECK(!bubble_source_->IsCollision(root)) << "Collision at root point"; +} + +bool GreedyBubbleTree::Connect( + TreeNode* node, const std::vector& q_target) { + Bubble* current_bubble = static_cast(node->point.get()); + + if (current_bubble->Contains(q_target)) + return true; + return CanReachBetween(current_bubble->IntersectsHullAt(q_target), q_target, + max_binary_search_depth_); +} + +bool GreedyBubbleTree::CanReachBetween( + const std::vector& q_1, const std::vector& q_2, + unsigned iterations_left) const { + if (iterations_left == 0) + return false; + + iterations_left--; + + unsigned dims = q_1.size(); + std::vector q_mid(dims, 0.0); + for (unsigned i = 0; i < dims; ++i) + q_mid[i] = (q_1[i] + q_2[i]) / 2.0; + std::unique_ptr bubble( + bubble_source_->NewBubble(q_mid, use_extended_)); + + if (bubble->IsCollision()) + return false; + + if (!bubble->Contains(q_1) && !CanReachBetween( + q_1, bubble->IntersectsHullAt(q_1), iterations_left)) + return false; + if (!bubble->Contains(q_2) && !CanReachBetween( + q_2, bubble->IntersectsHullAt(q_2), iterations_left)) + return false; + + return true; +} + +TreeNode* GreedyBubbleTree::AddNode( + const std::vector& q, TreeNode* parent) { + TreeNode* current_node = new TreeNode( + bubble_source_->NewBubble(q, use_extended_), parent); + Bubble* current_bubble = static_cast(current_node->point.get()); + nodes_.emplace_back(current_node); + std::vector position(current_bubble->position()); + std::vector size(current_bubble->size()); + std::vector point(position); + unsigned int axis_count = position.size(); + for (size_t i = 0; i < axis_count; ++i) { + point[i] = std::min(limits_[i].second, position[i] + size[i]); + point_index_->AddPoint(point, current_node); + point[i] = std::max(limits_[i].first, position[i] - size[i]); + point_index_->AddPoint(point, current_node); + point[i] = position[i]; + } + return current_node; +} + +ExtensionResult GreedyBubbleTree::ExtendFrom( + const AttachmentPoint& point, const std::vector& q_target) { + TreeNode* current_node = AddNode(point.position, point.parent); + Bubble* current_bubble = static_cast(current_node->point.get()); + + double move_size_limit = min_move_size_; + + for (int i = 0; i < max_bubbles_per_branch_; ++i) { + current_bubble = static_cast(current_node->point.get()); + if (current_bubble->Contains(q_target)) { + AddNode(q_target, current_node); + return ExtensionResult::REACHED; + } + + std::vector q_next(current_bubble->IntersectsHullAt(q_target)); + std::vector q_prev(current_bubble->position()); + + // Just like Classic RRT has a big step size that would represent the + // resolution of the movement, Bubble RRT has its own as a lower limit, + // whereby the limit is either the big step or embracing the target. + // Embracing the target is checked in the early return above. + // TODO: experiment with more heuristics. + double current_move_size = 0.0; + for (size_t j = 0; j < q_next.size(); ++j) + current_move_size += fabs(q_next[j] - q_prev[j]); + if (move_size_limit < 0.05 * current_move_size) + move_size_limit = 0.05 * current_move_size; + else if (current_move_size < move_size_limit) + return ExtensionResult::TRAPPED; + + current_node = AddNode(q_next, current_node); + } + return ExtensionResult::TRAPPED; +} + +} // namespace bubblesmp +} // namespace ademovic +} // namespace com diff --git a/pool/shard001/C++/0024075_allocator-malloc.cc b/pool/shard001/C++/0024075_allocator-malloc.cc new file mode 100644 index 0000000000000000000000000000000000000000..23050980ac6d3285d581f3a94563c02b75a3ef44 --- /dev/null +++ b/pool/shard001/C++/0024075_allocator-malloc.cc @@ -0,0 +1,64 @@ +#include +#include +#include + +#include "allocator.hh" +#include "support/newlib/malloc_def.hh" + +namespace kernel { + namespace mm { + + static void *s_malloc(size_t size) { + if(!size) { size = 1; } + return kernel::mm::allocator::allocate(size); + } + + static void s_free(void *ptr) { + if(!ptr) { return; } + kernel::mm::allocator::deallocate(ptr); + } + + static void *s_realloc(void *ptr, size_t size) { + if(!ptr) { + return s_malloc(size); + } + if(!size) { + s_free(ptr); + return nullptr; + } + size_t ptr_size = kernel::mm::allocator::get_size(ptr); + if(ptr_size >= size) { + return ptr; + } + void *new_ptr = s_malloc(size); + if(!new_ptr) { + return nullptr; + } + + memcpy(new_ptr, ptr, ptr_size); + s_free(ptr); + return new_ptr; + } + + static void *s_calloc(size_t nmemb, size_t size) { + size *= nmemb; + void *ptr = s_malloc(size); + if(!ptr) { return ptr; } + memset(ptr, 0, size); + return ptr; + } + + // connect to support/malloc_def + struct connecter { + connecter() { + support::malloc_impl = s_malloc; + support::free_impl = s_free; + support::realloc_impl = s_realloc; + support::calloc_impl = s_calloc; + } + }; + + static connecter instance; + + } +} \ No newline at end of file diff --git a/pool/shard001/C++/0024076_away.cpp b/pool/shard001/C++/0024076_away.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3326552bc788070d41d2282b40ad73f5887e52f2 --- /dev/null +++ b/pool/shard001/C++/0024076_away.cpp @@ -0,0 +1,54 @@ +/* + * This file is part of the ZeusiRCd distribution (https://github.com/Pryancito/zeusircd). + * Copyright (c) 2019 Rodrigo Santidrian AKA Pryan. + * + * 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 . +*/ + +#include "ZeusiRCd.h" +#include "module.h" +#include "Utils.h" + +std::string& ltrim(std::string& str, const std::string& chars = "\t\n\v\f\r "); +std::string& rtrim(std::string& str, const std::string& chars = "\t\n\v\f\r "); +std::string& trim(std::string& str, const std::string& chars = "\t\n\v\f\r "); + +class CMD_Away : public Module +{ + public: + CMD_Away() : Module("AWAY", 50, false) {}; + ~CMD_Away() {}; + virtual void command(User *user, std::string message) override { + std::vector results; + Utils::split(message, results, " "); + if (!user->bSentNick) { + user->SendAsServer("461 ZeusiRCd :" + Utils::make_string(user->mLang, "You havent used the NICK command yet, you have limited access.")); + return; + } else if (results.size() == 1) { + user->away("", false); + user->SendAsServer("305 " + user->mNickName + " :AWAY OFF"); + return; + } else { + std::string away = ""; + for (unsigned int i = 1; i < results.size(); ++i) { away.append(results[i] + " "); } + trim(away); + user->away(away, true); + user->SendAsServer("306 " + user->mNickName + " :AWAY ON " + away); + return; + } + } +}; + +extern "C" Widget* factory(void) { + return static_cast(new CMD_Away); +} diff --git a/pool/shard001/C++/0024078_fearmonger.cc b/pool/shard001/C++/0024078_fearmonger.cc new file mode 100644 index 0000000000000000000000000000000000000000..d10e9e08a5d45f44cf8287561154a2fdf9f02bdc --- /dev/null +++ b/pool/shard001/C++/0024078_fearmonger.cc @@ -0,0 +1,192 @@ +/** + * @file + * @brief player methods dealing with mesmerisation. +**/ + +#include "AppHdr.h" + +#include "player.h" + +#include "coord.h" +#include "env.h" +#include "fprop.h" +#include "mon-util.h" +#include "monster.h" +#include "state.h" +#include "areas.h" + +// Add a monster to the list of fearmongers. +bool player::add_fearmonger(const monster* mon) +{ + if (is_sanctuary(pos())) + { + if (can_see(mon)) + { + mprf("%s's aura of fear is muted, and has no effect on you.", + mon->name(DESC_THE).c_str()); + } + else + mpr("The fearful aura is strangely muted, and has no effect on you."); + + return false; + } + + if (!duration[DUR_AFRAID]) + { + set_duration(DUR_AFRAID, 7, 12); + fearmongers.push_back(mon->mindex()); + mprf(MSGCH_WARN, "You are terrified of %s!", + mon->name(DESC_THE).c_str()); + } + else + { + increase_duration(DUR_AFRAID, 5, 12); + if (!afraid_of(mon)) + fearmongers.push_back(mon->mindex()); + } + + return true; +} + +// Whether player is afraid. +bool player::afraid() const +{ + ASSERT(duration[DUR_AFRAID] > 0 == !fearmongers.empty()); + return (duration[DUR_AFRAID] > 0); +} + +// Whether player is afraid of the given monster. +bool player::afraid_of(const monster* mon) const +{ + for (unsigned int i = 0; i < fearmongers.size(); i++) + if (fearmongers[i] == mon->mindex()) + return true; + return false; +} + +// Checks whether a fearmonger keeps you from moving to +// target, and returns one if it exists. +monster* player::get_fearmonger(const coord_def &target) const +{ + for (unsigned int i = 0; i < fearmongers.size(); i++) + { + monster* mon = &menv[fearmongers[i]]; + const int olddist = grid_distance(pos(), mon->pos()); + const int newdist = grid_distance(target, mon->pos()); + + if (olddist > newdist) + return mon; + } + return NULL; +} + +monster* player::get_any_fearmonger() const +{ + if (!fearmongers.empty()) + return &menv[fearmongers[0]]; + else + return NULL; +} + +// Removes a monster from the list of fearmongers if present. +void player::remove_fearmonger(const monster* mon) +{ + for (unsigned int i = 0; i < fearmongers.size(); i++) + if (fearmongers[i] == mon->mindex()) + { + fearmongers.erase(fearmongers.begin() + i); + _removed_fearmonger(); + return; + } +} + +// Clear the list of fearmongers. Doesn't message. +void player::clear_fearmongers() +{ + fearmongers.clear(); + duration[DUR_AFRAID] = 0; +} + +// Possibly end fear if a loud noise happened. +void player::fearmongers_check_noise(int loudness, bool axe) +{ + if (axe) + return; + + if (loudness >= 20 && beheld()) + { + mprf("For a moment, your terror fades away!"); + clear_fearmongers(); + _removed_fearmonger(); + } +} + +static void _removed_fearmonger_msg(const monster* mon) +{ + return; +} + +// Update all fearmongers' status after changes. +void player::update_fearmongers() +{ + if (!afraid()) + return; + bool removed = false; + for (int i = fearmongers.size() - 1; i >= 0; i--) + { + const monster* mon = &menv[fearmongers[i]]; + if (!_possible_fearmonger(mon)) + { + fearmongers.erase(fearmongers.begin() + i); + removed = true; + _removed_fearmonger_msg(mon); + } + } + if (removed) + _removed_fearmonger(); +} + +// Update a single fearmonger. +void player::update_fearmonger(const monster* mon) +{ + if (_possible_fearmonger(mon)) + return; + for (unsigned int i = 0; i < fearmongers.size(); i++) + if (fearmongers[i] == mon->mindex()) + { + fearmongers.erase(fearmongers.begin() + i); + _removed_fearmonger_msg(mon); + _removed_fearmonger(); + return; + } +} + +// Helper function that resets the duration and messages if the player +// is no longer afraid. +void player::_removed_fearmonger() +{ + if (fearmongers.empty()) + { + duration[DUR_AFRAID] = 0; + mpr("You are no longer terrified.", + MSGCH_DURATION); + } +} + +// Helper function that checks whether the given monster is a possible +// fearmonger. +bool player::_possible_fearmonger(const monster* mon) const +{ + if (crawl_state.game_is_arena()) + return false; + + return (mon->alive() + && !silenced(pos()) && !silenced(mon->pos()) + && see_cell(mon->pos()) && mon->see_cell(pos()) + && !mon->submerged() && !mon->confused() + && !mon->asleep() && !mon->cannot_move() + && !mon->wont_attack() && !mon->pacified() + && !mon->berserk_or_insane() + && !mons_is_fleeing(mon) + && !is_sanctuary(pos())); +} diff --git a/pool/shard001/C++/0024084_CWE476_NULL_Pointer_Dereference__struct_72a.cpp b/pool/shard001/C++/0024084_CWE476_NULL_Pointer_Dereference__struct_72a.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c3f432729dbeb2053216137ed8f257f96a386d81 --- /dev/null +++ b/pool/shard001/C++/0024084_CWE476_NULL_Pointer_Dereference__struct_72a.cpp @@ -0,0 +1,122 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE476_NULL_Pointer_Dereference__struct_72a.cpp +Label Definition File: CWE476_NULL_Pointer_Dereference.label.xml +Template File: sources-sinks-72a.tmpl.cpp +*/ +/* + * @description + * CWE: 476 NULL Pointer Dereference + * BadSource: Set data to NULL + * GoodSource: Initialize data + * Sinks: + * GoodSink: Check for NULL before attempting to print data + * BadSink : Print 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 CWE476_NULL_Pointer_Dereference__struct_72 +{ + +#ifndef OMITBAD + +/* bad function declaration */ +void badSink(vector dataVector); + +void bad() +{ + twoIntsStruct * data; + vector dataVector; + /* POTENTIAL FLAW: Set data to NULL */ + data = NULL; + /* 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() +{ + twoIntsStruct * data; + vector dataVector; + /* FIX: Initialize data */ + { + twoIntsStruct tmpData; + tmpData.intOne = 0; + tmpData.intTwo = 0; + data = &tmpData; + } + /* 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() +{ + twoIntsStruct * data; + vector dataVector; + /* POTENTIAL FLAW: Set data to NULL */ + data = NULL; + 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 CWE476_NULL_Pointer_Dereference__struct_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/shard001/C++/0024091_invalidexpr.cpp b/pool/shard001/C++/0024091_invalidexpr.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7aeed32a9868d50027c00023b0083cef4183edf1 --- /dev/null +++ b/pool/shard001/C++/0024091_invalidexpr.cpp @@ -0,0 +1,47 @@ +/* + * 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 "exo/exo.h" + +#include "exo/errors/exceptions.h" + +namespace exo +{ + namespace exceptions + { + const char* InvalidExpr::what() + { + msg = "Invalid expression"; + + if( const std::string *fileName = boost::get_error_info( *this ) ) { + msg.append( " in " ).append( *fileName ); + } + + if( const int *lineNo = boost::get_error_info( *this ) ) { + msg.append( "#" ).append( std::to_string( *lineNo ) ); + } + + if( const long long *colNo = boost::get_error_info( *this ) ) { + msg.append( ":" ).append( std::to_string( *colNo ) ); + } + + if( std::string const *message = boost::get_error_info(*this) ) { + msg.append( " - " ).append( *message ); + } + + return( msg.c_str() ); + }; + } +} diff --git a/pool/shard001/C++/0024097_AppWatcher.cpp b/pool/shard001/C++/0024097_AppWatcher.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4cb74c351817ea93a700f494c6a3419c91e90b79 --- /dev/null +++ b/pool/shard001/C++/0024097_AppWatcher.cpp @@ -0,0 +1,140 @@ +#include +#include +#include +#include +#include "AppWatcher.h" + +AppWatcher::AppWatcher(){ + init(); +} + +AppWatcher::AppWatcher(Config::AppWatcher conf){ + config = conf; + init(); + start(); +} + +AppWatcher::~AppWatcher(){ + if(!stream) + return; + stop(); + process(); + //stream->rdbuf()->kill(SIGTERM); +} + +void AppWatcher::init(){ +} + +void AppWatcher::sendLog(const std::string &m){ + auto now = std::chrono::system_clock::now(); + auto in_time_t = std::chrono::system_clock::to_time_t(now); + std::stringstream ss; + ss << std::put_time(std::localtime(&in_time_t), "%X"); + + std::string msg = "\n[" + ss.str() + "]\n" + m; + + //std::cout << msg << std::endl; + { + std::ofstream outfile; + outfile.open(getLogFilePath(), std::ios_base::app); + outfile << msg; + } + + if(onLog) + onLog(msg); +} + +std::string AppWatcher::getLogFilePath(){ + auto path = getexepath()+"logs/"; + createDirectory(path); + + auto now = std::chrono::system_clock::now(); + auto in_time_t = std::chrono::system_clock::to_time_t(now); + + std::stringstream ss; + ss << std::put_time(std::localtime(&in_time_t), "%Y-%m-%d"); + + path += ss.str(); + path += "-"; + path += getName(); + path += ".txt"; + return path; +} + +void AppWatcher::start(){ + bShouldRun = true; +} + +void AppWatcher::stop(){ + bShouldRun = false; +} + +void AppWatcher::process(){ + // check if the stream is running; + if(!stream || !stream->is_open() || stream->rdbuf()->exited()){ + if(bShouldRun){ + + //start again + if(config.path.empty()) + return; + + std::string path = getDirectory(config.path); + if(path.empty()) + path = "/usr/bin/"; + + sendLog("start "+getName()+"\n----------------------------------------------------------------------------------------------------------------\n"); + + stream = std::make_shared("cd "+ path +" && "+config.path+" "+config.arguments); + } + }else if(stream){ + if(!bShouldRun){ + + // get pending messages + if(stream->rdbuf()->in_avail()){ + std::string msg; + std::string str; + while (*stream >> str) { + msg += str+"\n"; + } + sendLog(msg); + } + + // kill process + stream->rdbuf()->kill(SIGTERM); + stream.reset(); + } + } + + if(stream){ + + std::string msg; + int count = 0; + while(stream->rdbuf()->in_avail() && count < 32){ + std::string line; + std::getline(*stream, line); + msg += line; + msg += "\n"; + count ++; + } + + if(!msg.empty()) + sendLog(msg); + } +} + +std::string AppWatcher::getPath(){ + if(!fileExists(config.path)) + return "/usr/bin/"+config.path; + return config.path; +} + +std::string AppWatcher::getName(){ + if(config.path.empty()) + return "Not set"; + return getFilename(config.path); +} + +const std::string &AppWatcher::getArgs(){ + return config.arguments; +} + diff --git a/pool/shard001/C++/0024107_printout.cpp b/pool/shard001/C++/0024107_printout.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4956d81e80b0c1d99d4f7179241605f267140a8b --- /dev/null +++ b/pool/shard001/C++/0024107_printout.cpp @@ -0,0 +1,54 @@ +// From the software distribution accompanying the textbook +// "A Practical Introduction to Data Structures and Algorithm Analysis, +// Third Edition (C++)" by Clifford A. Shaffer. +// Source code Copyright (C) 2007-2011 by Clifford A. Shaffer. + +// A simple program to print out some data from a (presumably) sorted file. +// The program prints the first record from each block of 4096 bytes. +// A record is assumed to have a two-byte key value and a two-byte data value. +// It prints 8 records per line. +// It also prints the time required to run the program. + +#include "book.h" + +#include + +using std::fstream; +using std::ios; + +// A block is 4096 bytes, or 1024 logical records +#define NumRec 1024 + +typedef short E; + +int main(int argc, char** argv) { + int filesize; // Number of blocks printed, from commmandline argument + E Array[NumRec*2]; // Each record is a key and data field + fstream myfile; + + clock_t start = clock(); + if (argc < 3) { + cout << "Usage: printout \n"; + cout << "Size is measured in blocks of 4096 bytes.\n"; + exit(-1); + } + + myfile.open(argv[1], ios::in | ios::binary); + if (!myfile) { + cout << "Unable to open file :" << argv[1] << ":\n"; + exit(-1); + } + filesize = atoi(argv[2]); + + for (int count=0; count + + 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 "config.h" + +#include +#include +#include +#include +#include +#include +#ifdef HAVE_LINUX_LOWLATENCY_DO___NOT___USE +#include +#include // memcpy +#endif + +#include "llserial.h" + +static speed_t getbaud(int baud) { + switch(baud) + { + case 9600: + return B9600; + case 19200: + return B19200; + case 38400: + return B38400; + case 115200: + return B115200; + default: + return 0; + } +} + +LLserial::~LLserial () {} + +bool +LLserial::setup() +{ + if(!FDdriver::setup()) + return false; + + dev = cfg->value("device",""); + if(dev.size() == 0) + { + ERRORPRINTF (t, E_ERROR | 22, "Missing device= config"); + return false; + } + baudrate = cfg->value("baudrate", (int)default_baudrate()); + if (getbaud(baudrate) == 0) + { + ERRORPRINTF (t, E_ERROR | 22, "Wrong baudrate= config"); + return false; + } + + return true; +} + +void +LLserial::start() +{ + struct termios t1; + int term_baudrate; + + fd = open (dev.c_str(), O_RDWR | O_NOCTTY | O_NDELAY | O_SYNC); + if (fd == -1) + { + ERRORPRINTF (t, E_ERROR | 22, "Opening %s failed: %s", dev, strerror(errno)); + goto ex1; + } + + if (!set_low_latency (fd, &sold)) + { + ERRORPRINTF (t, E_ERROR | 22, "low_latency %s failed: %s", dev, strerror(errno)); + goto ex2; + } + + close (fd); + + fd = open (dev.c_str(), O_RDWR | O_NOCTTY | O_SYNC); + if (fd == -1) + { + ERRORPRINTF (t, E_ERROR | 23, "Opening %s failed: %s", dev, strerror(errno)); + goto ex1; + } + + if (tcgetattr (fd, &old)) + { + ERRORPRINTF (t, E_ERROR | 24, "tcgetattr %s failed: %s", dev, strerror(errno)); + goto ex3; + } + + if (tcgetattr (fd, &t1)) + { + ERRORPRINTF (t, E_ERROR | 25, "tcgetattr %s failed: %s", dev, strerror(errno)); + goto ex3; + } + + termios_settings(t1); + term_baudrate = getbaud(baudrate); + if (term_baudrate == -1) + { + ERRORPRINTF (t, E_ERROR | 58, "baudrate %d not recognized", baudrate); + goto ex3; + } + TRACEPRINTF(t, 0, "Opened %s with baud %d", dev, baudrate); + cfsetospeed (&t1, term_baudrate); + cfsetispeed (&t1, 0); + + if (tcsetattr (fd, TCSAFLUSH, &t1)) + { + ERRORPRINTF (t, E_ERROR | 26, "tcsetattr %s failed: %s", dev, strerror(errno)); + goto ex3; + } + + TRACEPRINTF (t, 2, "Opened"); + FDdriver::start(); + return; + +ex3: + restore_low_latency (fd, &sold); +ex2: + close (fd); + fd = -1; +ex1: + stopped(); +} + +void +LLserial::stop() +{ + if (fd >= 0) + restore_low_latency (fd, &sold); + FDdriver::stop(); +} + diff --git a/pool/shard001/C++/0024112_draw_motor_settings.cpp b/pool/shard001/C++/0024112_draw_motor_settings.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7da477bd51f3178b4432c40ce8f7ab71b20f7b8f --- /dev/null +++ b/pool/shard001/C++/0024112_draw_motor_settings.cpp @@ -0,0 +1,247 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * 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 "../../../../inc/MarlinConfigPre.h" + +#if HAS_TFT_LVGL_UI + +#include "lv_conf.h" +#include "draw_ui.h" + +#include "../../../../MarlinCore.h" + +static lv_obj_t * scr; + +#define ID_MOTOR_RETURN 1 +#define ID_MOTOR_STEPS 2 +#define ID_MOTOR_STEPS_ARROW 3 +#define ID_MOTOR_TMC_CURRENT 4 +#define ID_MOTOR_TMC_CURRENT_ARROW 5 +#define ID_MOTOR_STEP_MODE 6 +#define ID_MOTOR_STEP_MODE_ARROW 7 + +static void event_handler(lv_obj_t * obj, lv_event_t event) { + switch (obj->mks_obj_id) { + case ID_MOTOR_RETURN: + if (event == LV_EVENT_CLICKED) { + + } + else if (event == LV_EVENT_RELEASED) { + lv_clear_motor_settings(); + draw_return_ui(); + } + break; + case ID_MOTOR_STEPS: + if (event == LV_EVENT_CLICKED) { + + } + else if (event == LV_EVENT_RELEASED) { + lv_clear_motor_settings(); + lv_draw_step_settings(); + } + break; + case ID_MOTOR_STEPS_ARROW: + if (event == LV_EVENT_CLICKED) { + + } + else if (event == LV_EVENT_RELEASED) { + lv_clear_motor_settings(); + lv_draw_step_settings(); + } + break; + #if HAS_TRINAMIC_CONFIG + case ID_MOTOR_TMC_CURRENT: + if (event == LV_EVENT_CLICKED) { + + } + else if (event == LV_EVENT_RELEASED) { + lv_clear_motor_settings(); + lv_draw_tmc_current_settings(); + } + break; + case ID_MOTOR_TMC_CURRENT_ARROW: + if (event == LV_EVENT_CLICKED) { + + } + else if (event == LV_EVENT_RELEASED) { + lv_clear_motor_settings(); + lv_draw_tmc_current_settings(); + } + break; + #if HAS_STEALTHCHOP + case ID_MOTOR_STEP_MODE: + if (event == LV_EVENT_CLICKED) { + + } + else if (event == LV_EVENT_RELEASED) { + lv_clear_motor_settings(); + lv_draw_tmc_step_mode_settings(); + } + break; + case ID_MOTOR_STEP_MODE_ARROW: + if (event == LV_EVENT_CLICKED) { + + } + else if (event == LV_EVENT_RELEASED) { + lv_clear_motor_settings(); + lv_draw_tmc_step_mode_settings(); + } + break; + #endif + #endif + } +} + +void lv_draw_motor_settings(void) { + lv_obj_t *buttonBack, *label_Back; + lv_obj_t *buttonSteps, *labelSteps, *buttonStepsNarrow; + #if HAS_TRINAMIC_CONFIG + lv_obj_t *buttonTMCcurrent, *labelTMCcurrent, *buttonTMCcurrentNarrow; + lv_obj_t * line2; + #if HAS_STEALTHCHOP + lv_obj_t *buttonStepMode, *labelStepMode, *buttonStepModeNarrow; + lv_obj_t * line3; + #endif + #endif + lv_obj_t * line1; + if (disp_state_stack._disp_state[disp_state_stack._disp_index] != MOTOR_SETTINGS_UI) { + disp_state_stack._disp_index++; + disp_state_stack._disp_state[disp_state_stack._disp_index] = MOTOR_SETTINGS_UI; + } + disp_state = MOTOR_SETTINGS_UI; + + scr = lv_obj_create(NULL, NULL); + + lv_obj_set_style(scr, &tft_style_scr); + lv_scr_load(scr); + lv_obj_clean(scr); + + lv_obj_t * title = lv_label_create(scr, NULL); + lv_obj_set_style(title, &tft_style_label_rel); + lv_obj_set_pos(title, TITLE_XPOS, TITLE_YPOS); + lv_label_set_text(title, machine_menu.MotorConfTitle); + + lv_refr_now(lv_refr_get_disp_refreshing()); + + LV_IMG_DECLARE(bmp_para_back); + LV_IMG_DECLARE(bmp_para_arrow); + + buttonSteps = lv_btn_create(scr, NULL); /*Add a button the current screen*/ + lv_obj_set_pos(buttonSteps, PARA_UI_POS_X, PARA_UI_POS_Y); /*Set its position*/ + lv_obj_set_size(buttonSteps, PARA_UI_SIZE_X, PARA_UI_SIZE_Y); /*Set its size*/ + //lv_obj_set_event_cb(buttonMachine, event_handler); + lv_obj_set_event_cb_mks(buttonSteps, event_handler, ID_MOTOR_STEPS, NULL, 0); + lv_btn_set_style(buttonSteps, LV_BTN_STYLE_REL, &tft_style_label_rel); /*Set the button's released style*/ + lv_btn_set_style(buttonSteps, LV_BTN_STYLE_PR, &tft_style_label_pre); /*Set the button's pressed style*/ + lv_btn_set_layout(buttonSteps, LV_LAYOUT_OFF); + labelSteps = lv_label_create(buttonSteps, NULL); /*Add a label to the button*/ + + buttonStepsNarrow = lv_imgbtn_create(scr, NULL); + lv_obj_set_pos(buttonStepsNarrow, PARA_UI_POS_X + PARA_UI_SIZE_X, PARA_UI_POS_Y + PARA_UI_ARROW_V); + lv_obj_set_event_cb_mks(buttonStepsNarrow, event_handler, ID_MOTOR_STEPS_ARROW, "bmp_arrow.bin", 0); + lv_imgbtn_set_src(buttonStepsNarrow, LV_BTN_STATE_REL, &bmp_para_arrow); + lv_imgbtn_set_src(buttonStepsNarrow, LV_BTN_STATE_PR, &bmp_para_arrow); + lv_imgbtn_set_style(buttonStepsNarrow, LV_BTN_STATE_PR, &tft_style_label_pre); + lv_imgbtn_set_style(buttonStepsNarrow, LV_BTN_STATE_REL, &tft_style_label_rel); + lv_btn_set_layout(buttonStepsNarrow, LV_LAYOUT_OFF); + + line1 = lv_line_create(lv_scr_act(), NULL); + lv_ex_line(line1, line_points[0]); + #if HAS_TRINAMIC_CONFIG + buttonTMCcurrent = lv_btn_create(scr, NULL); /*Add a button the current screen*/ + lv_obj_set_pos(buttonTMCcurrent, PARA_UI_POS_X, PARA_UI_POS_Y * 2); /*Set its position*/ + lv_obj_set_size(buttonTMCcurrent, PARA_UI_SIZE_X, PARA_UI_SIZE_Y); /*Set its size*/ + //lv_obj_set_event_cb(buttonMachine, event_handler); + lv_obj_set_event_cb_mks(buttonTMCcurrent, event_handler, ID_MOTOR_TMC_CURRENT, NULL, 0); + lv_btn_set_style(buttonTMCcurrent, LV_BTN_STYLE_REL, &tft_style_label_rel); /*Set the button's released style*/ + lv_btn_set_style(buttonTMCcurrent, LV_BTN_STYLE_PR, &tft_style_label_pre); /*Set the button's pressed style*/ + lv_btn_set_layout(buttonTMCcurrent, LV_LAYOUT_OFF); + labelTMCcurrent = lv_label_create(buttonTMCcurrent, NULL); /*Add a label to the button*/ + + buttonTMCcurrentNarrow = lv_imgbtn_create(scr, NULL); + lv_obj_set_pos(buttonTMCcurrentNarrow, PARA_UI_POS_X + PARA_UI_SIZE_X, PARA_UI_POS_Y * 2 + PARA_UI_ARROW_V); + lv_obj_set_event_cb_mks(buttonTMCcurrentNarrow, event_handler, ID_MOTOR_TMC_CURRENT_ARROW, "bmp_arrow.bin", 0); + lv_imgbtn_set_src(buttonTMCcurrentNarrow, LV_BTN_STATE_REL, &bmp_para_arrow); + lv_imgbtn_set_src(buttonTMCcurrentNarrow, LV_BTN_STATE_PR, &bmp_para_arrow); + lv_imgbtn_set_style(buttonTMCcurrentNarrow, LV_BTN_STATE_PR, &tft_style_label_pre); + lv_imgbtn_set_style(buttonTMCcurrentNarrow, LV_BTN_STATE_REL, &tft_style_label_rel); + lv_btn_set_layout(buttonTMCcurrentNarrow, LV_LAYOUT_OFF); + + line2 = lv_line_create(lv_scr_act(), NULL); + lv_ex_line(line2, line_points[1]); + + #if HAS_STEALTHCHOP + buttonStepMode = lv_btn_create(scr, NULL); /*Add a button the current screen*/ + lv_obj_set_pos(buttonStepMode, PARA_UI_POS_X, PARA_UI_POS_Y * 3); /*Set its position*/ + lv_obj_set_size(buttonStepMode, PARA_UI_SIZE_X, PARA_UI_SIZE_Y); /*Set its size*/ + //lv_obj_set_event_cb(buttonMachine, event_handler); + lv_obj_set_event_cb_mks(buttonStepMode, event_handler, ID_MOTOR_STEP_MODE, NULL, 0); + lv_btn_set_style(buttonStepMode, LV_BTN_STYLE_REL, &tft_style_label_rel); /*Set the button's released style*/ + lv_btn_set_style(buttonStepMode, LV_BTN_STYLE_PR, &tft_style_label_pre); /*Set the button's pressed style*/ + lv_btn_set_layout(buttonStepMode, LV_LAYOUT_OFF); + labelStepMode = lv_label_create(buttonStepMode, NULL); /*Add a label to the button*/ + + buttonStepModeNarrow = lv_imgbtn_create(scr, NULL); + lv_obj_set_pos(buttonStepModeNarrow, PARA_UI_POS_X + PARA_UI_SIZE_X, PARA_UI_POS_Y * 3 + PARA_UI_ARROW_V); + lv_obj_set_event_cb_mks(buttonStepModeNarrow, event_handler, ID_MOTOR_STEP_MODE_ARROW, "bmp_arrow.bin", 0); + lv_imgbtn_set_src(buttonStepModeNarrow, LV_BTN_STATE_REL, &bmp_para_arrow); + lv_imgbtn_set_src(buttonStepModeNarrow, LV_BTN_STATE_PR, &bmp_para_arrow); + lv_imgbtn_set_style(buttonStepModeNarrow, LV_BTN_STATE_PR, &tft_style_label_pre); + lv_imgbtn_set_style(buttonStepModeNarrow, LV_BTN_STATE_REL, &tft_style_label_rel); + lv_btn_set_layout(buttonStepModeNarrow, LV_LAYOUT_OFF); + + line3 = lv_line_create(lv_scr_act(), NULL); + lv_ex_line(line3, line_points[2]); + #endif + #endif // HAS_TRINAMIC_CONFIG + + buttonBack = lv_imgbtn_create(scr, NULL); + lv_obj_set_event_cb_mks(buttonBack, event_handler, ID_MOTOR_RETURN, "bmp_back70x40.bin", 0); + lv_imgbtn_set_src(buttonBack, LV_BTN_STATE_REL, &bmp_para_back); + lv_imgbtn_set_src(buttonBack, LV_BTN_STATE_PR, &bmp_para_back); + lv_imgbtn_set_style(buttonBack, LV_BTN_STATE_PR, &tft_style_label_pre); + lv_imgbtn_set_style(buttonBack, LV_BTN_STATE_REL, &tft_style_label_rel); + + lv_obj_set_pos(buttonBack, PARA_UI_BACL_POS_X, PARA_UI_BACL_POS_Y); + lv_btn_set_layout(buttonBack, LV_LAYOUT_OFF); + label_Back = lv_label_create(buttonBack, NULL); + + if (gCfgItems.multiple_language != 0) { + lv_label_set_text(label_Back, common_menu.text_back); + lv_obj_align(label_Back, buttonBack, LV_ALIGN_CENTER, 0, 0); + + lv_label_set_text(labelSteps, machine_menu.StepsConf); + lv_obj_align(labelSteps, buttonSteps, LV_ALIGN_IN_LEFT_MID, 0, 0); + #if HAS_TRINAMIC_CONFIG + lv_label_set_text(labelTMCcurrent, machine_menu.TMCcurrentConf); + lv_obj_align(labelTMCcurrent, buttonTMCcurrent, LV_ALIGN_IN_LEFT_MID, 0, 0); + #if HAS_STEALTHCHOP + lv_label_set_text(labelStepMode, machine_menu.TMCStepModeConf); + lv_obj_align(labelStepMode, buttonStepMode, LV_ALIGN_IN_LEFT_MID, 0, 0); + #endif + #endif + } + +} + +void lv_clear_motor_settings() { lv_obj_del(scr); } + +#endif // HAS_TFT_LVGL_UI diff --git a/pool/shard001/C++/0024116_FullscreenController.cpp b/pool/shard001/C++/0024116_FullscreenController.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3eca065f1b4b06e2d56de048d519248cda9b1f25 --- /dev/null +++ b/pool/shard001/C++/0024116_FullscreenController.cpp @@ -0,0 +1,204 @@ +/* + * 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 "config.h" +#include "web/FullscreenController.h" + +#include "core/dom/Document.h" +#include "core/dom/Fullscreen.h" +#include "core/frame/LocalFrame.h" +#include "core/html/HTMLMediaElement.h" +#include "core/html/HTMLVideoElement.h" +#include "platform/LayoutTestSupport.h" +#include "platform/RuntimeEnabledFeatures.h" +#include "public/platform/WebLayerTreeView.h" +#include "public/web/WebFrameClient.h" +#include "web/WebLocalFrameImpl.h" +#include "web/WebSettingsImpl.h" +#include "web/WebViewImpl.h" + +namespace blink { + +PassOwnPtrWillBeRawPtr FullscreenController::create(WebViewImpl* webViewImpl) +{ + return adoptPtrWillBeNoop(new FullscreenController(webViewImpl)); +} + +FullscreenController::FullscreenController(WebViewImpl* webViewImpl) + : m_webViewImpl(webViewImpl) + , m_exitFullscreenPageScaleFactor(0) + , m_isCancelingFullScreen(false) +{ +} + +void FullscreenController::didEnterFullScreen() +{ + if (!m_provisionalFullScreenElement) + return; + + RefPtrWillBeRawPtr element = m_provisionalFullScreenElement.release(); + Document& document = element->document(); + m_fullScreenFrame = document.frame(); + + if (!m_fullScreenFrame) + return; + + if (!m_exitFullscreenPageScaleFactor) { + m_exitFullscreenPageScaleFactor = m_webViewImpl->pageScaleFactor(); + m_exitFullscreenScrollOffset = m_webViewImpl->mainFrame()->scrollOffset(); + m_exitFullscreenPinchViewportOffset = m_webViewImpl->pinchViewportOffset(); + + updatePageScaleConstraints(false); + m_webViewImpl->setPageScaleFactor(1.0f); + m_webViewImpl->setMainFrameScrollOffset(IntPoint()); + m_webViewImpl->setPinchViewportOffset(FloatPoint()); + } + + Fullscreen::from(document).didEnterFullScreenForElement(element.get()); + ASSERT(Fullscreen::currentFullScreenElementFrom(document) == element); + + if (RuntimeEnabledFeatures::overlayFullscreenVideoEnabled()) { + if (isHTMLVideoElement(element)) { + HTMLVideoElement* videoElement = toHTMLVideoElement(element); + if (HTMLMediaElement::isMediaStreamURL(videoElement->sourceURL().string())) + return; + if (videoElement->webMediaPlayer() + // FIXME: There is no embedder-side handling in layout test mode. + && !LayoutTestSupport::isRunningLayoutTest()) { + videoElement->webMediaPlayer()->enterFullscreen(); + } + if (m_webViewImpl->layerTreeView()) + m_webViewImpl->layerTreeView()->setHasTransparentBackground(true); + } + } +} + +void FullscreenController::didExitFullScreen() +{ + if (!m_fullScreenFrame) + return; + + if (Document* document = m_fullScreenFrame->document()) { + if (Fullscreen* fullscreen = Fullscreen::fromIfExists(*document)) { + if (fullscreen->webkitCurrentFullScreenElement()) { + // When the client exits from full screen we have to call fullyExitFullscreen to notify + // the document. While doing that, suppress notifications back to the client. + m_isCancelingFullScreen = true; + Fullscreen::fullyExitFullscreen(*document); + m_isCancelingFullScreen = false; + + if (RuntimeEnabledFeatures::overlayFullscreenVideoEnabled() && m_webViewImpl->layerTreeView()) + m_webViewImpl->layerTreeView()->setHasTransparentBackground(m_webViewImpl->isTransparent()); + + if (m_exitFullscreenPageScaleFactor) { + updatePageScaleConstraints(true); + m_webViewImpl->setPageScaleFactor(m_exitFullscreenPageScaleFactor); + m_webViewImpl->setMainFrameScrollOffset(IntPoint(m_exitFullscreenScrollOffset)); + m_webViewImpl->setPinchViewportOffset(m_exitFullscreenPinchViewportOffset); + m_exitFullscreenPageScaleFactor = 0; + m_exitFullscreenScrollOffset = IntSize(); + } + + fullscreen->didExitFullScreenForElement(0); + } + } + } + + m_fullScreenFrame.clear(); +} + +void FullscreenController::enterFullScreenForElement(Element* element) +{ + // We are already transitioning to fullscreen for a different element. + if (m_provisionalFullScreenElement) { + m_provisionalFullScreenElement = element; + return; + } + + // We are already in fullscreen mode. + if (m_fullScreenFrame) { + m_provisionalFullScreenElement = element; + didEnterFullScreen(); + return; + } + + // We need to transition to fullscreen mode. + WebLocalFrameImpl* frame = WebLocalFrameImpl::fromFrame(element->document().frame()); + if (frame && frame->client()) { + frame->client()->enterFullscreen(); + m_provisionalFullScreenElement = element; + } +} + +void FullscreenController::exitFullScreenForElement(Element* element) +{ + ASSERT(element); + + // The client is exiting full screen, so don't send a notification. + if (m_isCancelingFullScreen) + return; + + WebLocalFrameImpl* frame = WebLocalFrameImpl::fromFrame(element->document().frame()); + if (frame && frame->client()) + frame->client()->exitFullscreen(); +} + +void FullscreenController::updateSize() +{ + if (!isFullscreen()) + return; + + updatePageScaleConstraints(false); + + LayoutFullScreen* layoutObject = Fullscreen::from(*m_fullScreenFrame->document()).fullScreenLayoutObject(); + if (layoutObject) + layoutObject->updateStyle(); +} + +void FullscreenController::updatePageScaleConstraints(bool removeConstraints) +{ + PageScaleConstraints fullscreenConstraints; + if (!removeConstraints) { + fullscreenConstraints = PageScaleConstraints(1.0, 1.0, 1.0); + fullscreenConstraints.layoutSize = IntSize(m_webViewImpl->size()); + } + m_webViewImpl->pageScaleConstraintsSet().setFullscreenConstraints(fullscreenConstraints); + m_webViewImpl->pageScaleConstraintsSet().computeFinalConstraints(); + m_webViewImpl->updateMainFrameLayoutSize(); +} + +DEFINE_TRACE(FullscreenController) +{ + visitor->trace(m_provisionalFullScreenElement); + visitor->trace(m_fullScreenFrame); +} + +} // namespace blink + diff --git a/pool/shard001/C++/0024122_frameeditview.cpp b/pool/shard001/C++/0024122_frameeditview.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cc32251500d97bd241833f0938e3d32bd82d1509 --- /dev/null +++ b/pool/shard001/C++/0024122_frameeditview.cpp @@ -0,0 +1,130 @@ +#include "frameeditview.hpp" +#include +#include +#include +#include + +FrameEditView::FrameEditView(QWidget* parent) + : + QGraphicsView(parent), + m_background(nullptr), + m_frame(nullptr), + m_isDragging(false), + m_startDragPosition(0, 0), + m_numScheduledScalings(0) +{ + setScene(&m_scene); + setRenderHint(QPainter::Antialiasing, true); + centerOn(viewport()->rect().center()); +} + +FrameEditView::~FrameEditView() +{ + m_scene.clear(); + m_background = nullptr; + m_frame = nullptr; +} + +void FrameEditView::setSpritesheet(const QPixmap &spritesheet) +{ + if(m_background) + m_scene.removeItem(m_background); + m_background = m_scene.addPixmap(spritesheet); + m_background->setZValue(-1); +} + +void FrameEditView::setRect(const QRect& rect) +{ + if(m_frame) + { + m_scene.removeItem(m_frame); + delete m_frame; + } + + m_frame = new MovableRect(rect); + connect(m_frame, &MovableRect::rectModified, this, [this](const QRect &rect) + { + emit rectModified(rect); + }); + connect(m_frame, &MovableRect::rectPressed, this, [this]{ m_isDragging = false;}); + m_scene.addItem(m_frame); + m_frame->moveBy(rect.x(), rect.y()); +} + +MovableRect* FrameEditView::getRect() +{ + return m_frame; +} + +void FrameEditView::mousePressEvent(QMouseEvent *event) +{ + if(!m_frame->isUnderMouse() && event->button() == Qt::LeftButton) + { + m_isDragging = true; + m_startDragPosition = event->pos(); + } + QGraphicsView::mousePressEvent(event); +} + +void FrameEditView::mouseMoveEvent(QMouseEvent *event) +{ + if(m_isDragging) + { + QPointF center = mapToScene(viewport()->rect().center()); + + QPointF oldP = mapToScene(m_startDragPosition); + QPointF newP = mapToScene(event->pos()); + QPointF tr = newP - oldP; + + centerOn(center.x() - tr.x(), center.y() - tr.y()); + + m_startDragPosition = event->pos(); + } + QGraphicsView::mouseMoveEvent(event); +} + +void FrameEditView::mouseReleaseEvent(QMouseEvent *event) +{ + if(event->button() == Qt::MiddleButton) + m_isDragging = false; + QGraphicsView::mouseReleaseEvent(event); +} + +void FrameEditView::resizeEvent(QResizeEvent* event) +{ + if(m_background) + setSceneRect(0, 0, m_background->sceneBoundingRect().width(), m_background->sceneBoundingRect().height()); + QGraphicsView::resizeEvent(event); +} + +// Scrolling stuff +void FrameEditView::wheelEvent(QWheelEvent *event) +{ + const int numDegrees = event->delta() / 8; + const int numSteps = numDegrees / 15; + m_numScheduledScalings += numSteps; + if (m_numScheduledScalings * numSteps < 0) + m_numScheduledScalings = numSteps; + + QTimeLine *anim = new QTimeLine(350, this); + anim->setUpdateInterval(20); + + connect(anim, &QTimeLine::valueChanged, this, &FrameEditView::scalingTime); + connect(anim, &QTimeLine::finished, this, &FrameEditView::animFinished); + anim->start(); +} + +void FrameEditView::scalingTime(qreal) +{ + const auto factor = 1.0 + qreal(m_numScheduledScalings) / 300.0; + scale(factor, factor); +} + +void FrameEditView::animFinished() +{ + if (m_numScheduledScalings > 0) + m_numScheduledScalings--; + else + m_numScheduledScalings++; + sender()->deleteLater(); +} diff --git a/pool/shard001/C++/0024132_hash_zlob_random_int_find_timing.cc b/pool/shard001/C++/0024132_hash_zlob_random_int_find_timing.cc new file mode 100644 index 0000000000000000000000000000000000000000..82abb640bb0e6e111dcdd846c5d4857ad52cdf88 --- /dev/null +++ b/pool/shard001/C++/0024132_hash_zlob_random_int_find_timing.cc @@ -0,0 +1,119 @@ +// -*- C++ -*- + +// Copyright (C) 2005, 2006, 2009 Free Software Foundation, Inc. +// +// This file is part of the GNU ISO C++ Library. This library is free +// software; you can redistribute it and/or modify it under the terms +// of the GNU General Public License as published by the Free Software +// Foundation; either version 3, or (at your option) any later +// version. + +// This library is distributed in the hope that it will be useful, but +// WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with this library; see the file COPYING3. If not see +// . + + +// Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. + +// Permission to use, copy, modify, sell, and distribute this software +// is hereby granted without fee, provided that the above copyright +// notice appears in all copies, and that both that copyright notice +// and this permission notice appear in supporting documentation. None +// of the above authors, nor IBM Haifa Research Laboratories, make any +// representation about the suitability of this software for any +// purpose. It is provided "as is" without express or implied +// warranty. + +/** + * @file hash_zlob_random_int_find_timing_test.cpp + * Contains test for finding random integers. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +void +usage(); + +int +main(int argc, char* a_p_argv[]) +{ + using namespace __gnu_pbds::test; + + size_t vn = 200; + size_t vs = 200; + size_t vm = 2100; + try + { + xml_test_performance_formatter fmt("Size", "Average time (sec.)"); + + typedef std::vector > vec_t; + vec_t a_v(vm); + twister_rand_gen g; + + for (size_t i = 0; i < vm; ++i) + { + int k = static_cast(g.get_unsigned_long()); + a_v[i] = std::make_pair(k << 8, 0); + if ((a_v[i].first& 127) != 0) + throw std::logic_error("Fucked!"); + } + + vec_t::const_iterator b = a_v.begin(); + typedef find_test test_t; + test_t tst(b, b, vn, vs, vm, vn, vs, vm); + { + typedef native_hash_map native_t; + tst(native_t()); + } + + { + typedef hash_common_types::performance_tl tl_t; + tl_t tl; + __gnu_cxx::typelist::apply(tst, tl); + } + } + catch (...) + { + std::cerr << "Test failed" << std::endl; + return -1; + } + return 0; +} + +void +usage() +{ + using namespace std; + cerr << "usage: hash_zlob_random_int_find_timing_test " << + endl << endl; + + cerr << + "This test checks the performance of various associative containers " + "using their find method. " << endl; + cerr << "Specifically, it does the following:" << endl; + cerr << "* Creates a vector of zero low-order bit random integers " << endl; + cerr << "* Inserts the elements into the container" << endl; + cerr << "* Performs a sequence of find operations. At each iteration, " + "it finds, for each integer in the vector, its entry in the " + "container, using the find method"; + cerr << "* Repeats the above test a number of times" << endl; + + cerr << endl << endl; + + cerr << "vn = minimum size of the vector" << endl; + cerr << "vs = step size of the vector" << endl; + cerr << "vm = maximum size of the vector" << endl; +} diff --git a/pool/shard001/C++/0024136_file2_dot.cc b/pool/shard001/C++/0024136_file2_dot.cc new file mode 100644 index 0000000000000000000000000000000000000000..c577450a41915c6dc5b858a573e9c5b6de1744b9 --- /dev/null +++ b/pool/shard001/C++/0024136_file2_dot.cc @@ -0,0 +1,68 @@ +/* + * @BEGIN LICENSE + * + * Psi4: an open-source quantum chemistry software package + * + * Copyright (c) 2007-2017 The Psi4 Developers. + * + * The copyrights for code used from other parties are included in + * the corresponding files. + * + * 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. + * + * @END LICENSE + */ + +/*! \file + \ingroup DPD + \brief Enter brief description of file here +*/ +#include +#include "psi4/libqt/qt.h" +#include "dpd.h" + +namespace psi { + +double DPD::file2_dot(dpdfile2 *FileA, dpdfile2 *FileB) +{ + int h, nirreps, my_irrep; + double dot; + + nirreps = FileA->params->nirreps; + my_irrep = FileA->my_irrep; + + dot = 0.0; + + file2_mat_init(FileA); + file2_mat_init(FileB); + file2_mat_rd(FileA); + file2_mat_rd(FileB); + + for(h=0; h < nirreps; h++) { + + dot += dot_block(FileA->matrix[h], FileB->matrix[h], + FileA->params->rowtot[h], + FileA->params->coltot[h^my_irrep], 1.0); + + } + + file2_mat_close(FileA); + file2_mat_close(FileB); + + return dot; + +} + +} diff --git a/pool/shard001/C++/0024142_log_codecs.cc b/pool/shard001/C++/0024142_log_codecs.cc new file mode 100644 index 0000000000000000000000000000000000000000..f0081d09c42e040713acd4cfe2ba037fd29ee2fe --- /dev/null +++ b/pool/shard001/C++/0024142_log_codecs.cc @@ -0,0 +1,205 @@ +//-------------------------------------------------------------------------- +// Copyright (C) 2014-2016 Cisco and/or its affiliates. All rights reserved. +// Copyright (C) 2013-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. +//-------------------------------------------------------------------------- +// alert_codecs.cc author Josh Rosenbaum + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include +#include + +#include +#include + +#include "main/snort_types.h" +#include "main/snort_config.h" +#include "framework/logger.h" +#include "framework/module.h" +#include "protocols/packet.h" +#include "protocols/packet_manager.h" +#include "detection/signature.h" +#include "log/text_log.h" +#include "log/log_text.h" +#include "utils/stats.h" + +static THREAD_LOCAL TextLog* test_file = nullptr; + +#define S_NAME "log_codecs" +#define F_NAME S_NAME ".txt" +#define LOG_CODECS_HELP "log protocols in packet by layer" + +//------------------------------------------------------------------------- +// module stuff +//------------------------------------------------------------------------- + +static const unsigned ALERT_FLAG_MSG = 0x01; + +static const Parameter ex_params[] = +{ + { "file", Parameter::PT_BOOL, nullptr, "false", + "output to " F_NAME " instead of stdout" }, + + { "msg", Parameter::PT_BOOL, nullptr, "false", + "include alert msg" }, + + { nullptr, Parameter::PT_MAX, nullptr, nullptr, nullptr } +}; + +namespace +{ +class LogCodecModule : public Module +{ +public: + LogCodecModule() : Module(S_NAME, LOG_CODECS_HELP, ex_params) { } + + bool set(const char*, Value&, SnortConfig*) override; + bool begin(const char*, int, SnortConfig*) override; + +public: + bool print_to_file; + uint8_t flags; +}; +} // namespace + +bool LogCodecModule::set(const char*, Value& v, SnortConfig*) +{ + if ( v.is("file") ) + { + if ( v.get_bool() ) + print_to_file = true; + } + else if ( v.is("msg") ) + { + if ( v.get_bool() ) + flags |= ALERT_FLAG_MSG; + } + else + return false; + + return true; +} + +bool LogCodecModule::begin(const char*, int, SnortConfig*) +{ + flags = 0; + print_to_file = false; + return true; +} + +//------------------------------------------------------------------------- +// logger stuff +//------------------------------------------------------------------------- + +namespace +{ +class CodecLogger : public Logger +{ +public: + CodecLogger(LogCodecModule* m); + + void open() override; + void close() override; + virtual void log(Packet*, const char*, Event*) override; + +public: + std::string file; + uint8_t flags; +}; +} // namespace + +CodecLogger::CodecLogger(LogCodecModule* m) +{ + file = m->print_to_file ? F_NAME : "stdout"; + flags = m->flags; +} + +void CodecLogger::open() +{ + test_file = TextLog_Init(file.c_str()); +} + +void CodecLogger::close() +{ TextLog_Term(test_file); } + +void CodecLogger::log(Packet* p, const char* msg, Event* e) +{ + TextLog_Print(test_file, "pkt:" STDu64 "\t", pc.total_from_daq); + + if (e != NULL) + { + TextLog_Print(test_file, " gid:%lu sid:%lu rev:%lu\t", + (unsigned long)e->sig_info->generator, + (unsigned long)e->sig_info->id, + (unsigned long)e->sig_info->rev); + } + + if (flags & ALERT_FLAG_MSG) + { + if (msg != NULL) + TextLog_Print(test_file, "%s\t", msg); + } + + TextLog_NewLine(test_file); + PacketManager::log_protocols(test_file, p); + TextLog_NewLine(test_file); + + if ( p->dsize and SnortConfig::output_app_data() ) + LogNetData(test_file, p->data, p->dsize, p); + + TextLog_NewLine(test_file); +} + +//------------------------------------------------------------------------- +// api stuff +//------------------------------------------------------------------------- + +static Module* mod_ctor() +{ return new LogCodecModule; } + +static void mod_dtor(Module* m) +{ delete m; } + +static Logger* codec_log_ctor(SnortConfig*, Module* mod) +{ return new CodecLogger((LogCodecModule*)mod); } + +static void codec_log_dtor(Logger* p) +{ delete p; } + +static const LogApi log_codecs_api = +{ + { + PT_LOGGER, + sizeof(LogApi), + LOGAPI_VERSION, + 0, + API_RESERVED, + API_OPTIONS, + S_NAME, + LOG_CODECS_HELP, + mod_ctor, + mod_dtor + }, + OUTPUT_TYPE_FLAG__LOG, + codec_log_ctor, + codec_log_dtor +}; + +const BaseApi* log_codecs = &log_codecs_api.base; + diff --git a/pool/shard001/C++/0024144_global_confirm_info_bar.cc b/pool/shard001/C++/0024144_global_confirm_info_bar.cc new file mode 100644 index 0000000000000000000000000000000000000000..eb4c945793b99ddf94fc0a475eb5cde479328220 --- /dev/null +++ b/pool/shard001/C++/0024144_global_confirm_info_bar.cc @@ -0,0 +1,210 @@ +// 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 "chrome/browser/devtools/global_confirm_info_bar.h" + +#include + +#include "base/macros.h" +#include "chrome/browser/ui/browser.h" +#include "chrome/browser/ui/tabs/tab_strip_model.h" +#include "components/infobars/core/infobar.h" +#include "ui/gfx/image/image.h" + +// InfoBarDelegateProxy ------------------------------------------------------- + +class GlobalConfirmInfoBar::DelegateProxy : public ConfirmInfoBarDelegate { + public: + explicit DelegateProxy(base::WeakPtr global_info_bar); + ~DelegateProxy() override; + void Detach(); + + private: + friend class GlobalConfirmInfoBar; + + // ConfirmInfoBarDelegate overrides + infobars::InfoBarDelegate::InfoBarIdentifier GetIdentifier() const override; + base::string16 GetMessageText() const override; + int GetButtons() const override; + base::string16 GetButtonLabel(InfoBarButton button) const override; + bool Accept() override; + bool Cancel() override; + base::string16 GetLinkText() const override; + GURL GetLinkURL() const override; + bool LinkClicked(WindowOpenDisposition disposition) override; + bool EqualsDelegate(infobars::InfoBarDelegate* delegate) const override; + void InfoBarDismissed() override; + + infobars::InfoBar* info_bar_; + base::WeakPtr global_info_bar_; + + DISALLOW_COPY_AND_ASSIGN(DelegateProxy); +}; + +GlobalConfirmInfoBar::DelegateProxy::DelegateProxy( + base::WeakPtr global_info_bar) + : info_bar_(nullptr), + global_info_bar_(global_info_bar) { +} + +GlobalConfirmInfoBar::DelegateProxy::~DelegateProxy() { +} + +infobars::InfoBarDelegate::InfoBarIdentifier +GlobalConfirmInfoBar::DelegateProxy::GetIdentifier() const { + return global_info_bar_ ? global_info_bar_->delegate_->GetIdentifier() + : INVALID; +} + +base::string16 GlobalConfirmInfoBar::DelegateProxy::GetMessageText() const { + return global_info_bar_ ? global_info_bar_->delegate_->GetMessageText() + : base::string16(); +} + +int GlobalConfirmInfoBar::DelegateProxy::GetButtons() const { + return global_info_bar_ ? global_info_bar_->delegate_->GetButtons() + : 0; +} + +base::string16 GlobalConfirmInfoBar::DelegateProxy::GetButtonLabel( + InfoBarButton button) const { + return global_info_bar_ ? global_info_bar_->delegate_->GetButtonLabel(button) + : base::string16(); +} + +bool GlobalConfirmInfoBar::DelegateProxy::Accept() { + base::WeakPtr info_bar = global_info_bar_; + if (info_bar) + info_bar->delegate_->Accept(); + // Could be destroyed after this point. + if (info_bar) + info_bar->Close(); + return true; +} + +bool GlobalConfirmInfoBar::DelegateProxy::Cancel() { + base::WeakPtr info_bar = global_info_bar_; + if (info_bar) + info_bar->delegate_->Cancel(); + // Could be destroyed after this point. + if (info_bar) + info_bar->Close(); + return true; +} + +base::string16 GlobalConfirmInfoBar::DelegateProxy::GetLinkText() const { + return global_info_bar_ ? global_info_bar_->delegate_->GetLinkText() + : base::string16(); +} + +GURL GlobalConfirmInfoBar::DelegateProxy::GetLinkURL() const { + return global_info_bar_ ? global_info_bar_->delegate_->GetLinkURL() + : GURL(); +} + +bool GlobalConfirmInfoBar::DelegateProxy::LinkClicked( + WindowOpenDisposition disposition) { + return global_info_bar_ ? + global_info_bar_->delegate_->LinkClicked(disposition) : false; +} + +bool GlobalConfirmInfoBar::DelegateProxy::EqualsDelegate( + infobars::InfoBarDelegate* delegate) const { + return delegate == this; +} + +void GlobalConfirmInfoBar::DelegateProxy::InfoBarDismissed() { + base::WeakPtr info_bar = global_info_bar_; + if (info_bar) + info_bar->delegate_->InfoBarDismissed(); + // Could be destroyed after this point. + if (info_bar) + info_bar->Close(); +} + +void GlobalConfirmInfoBar::DelegateProxy::Detach() { + global_info_bar_.reset(); +} + +// GlobalConfirmInfoBar ------------------------------------------------------- + +// static +base::WeakPtr GlobalConfirmInfoBar::Show( + scoped_ptr delegate) { + GlobalConfirmInfoBar* info_bar = + new GlobalConfirmInfoBar(std::move(delegate)); + return info_bar->weak_factory_.GetWeakPtr(); +} + +void GlobalConfirmInfoBar::Close() { + delete this; +} + +GlobalConfirmInfoBar::GlobalConfirmInfoBar( + scoped_ptr delegate) + : delegate_(std::move(delegate)), + browser_tab_strip_tracker_(this, nullptr, nullptr), + weak_factory_(this) { + browser_tab_strip_tracker_.Init( + BrowserTabStripTracker::InitWith::BROWSERS_IN_ACTIVE_DESKTOP); +} + +GlobalConfirmInfoBar::~GlobalConfirmInfoBar() { + while (!proxies_.empty()) { + auto it = proxies_.begin(); + it->second->Detach(); + it->first->RemoveObserver(this); + it->first->RemoveInfoBar(it->second->info_bar_); + proxies_.erase(it); + } +} + +void GlobalConfirmInfoBar::TabInsertedAt(content::WebContents* web_contents, + int index, + bool foreground) { + InfoBarService* infobar_service = + InfoBarService::FromWebContents(web_contents); + // WebContents from the tab strip must have the infobar service. + DCHECK(infobar_service); + if (proxies_.find(infobar_service) != proxies_.end()) + return; + + scoped_ptr proxy( + new GlobalConfirmInfoBar::DelegateProxy(weak_factory_.GetWeakPtr())); + GlobalConfirmInfoBar::DelegateProxy* proxy_ptr = proxy.get(); + infobars::InfoBar* added_bar = infobar_service->AddInfoBar( + infobar_service->CreateConfirmInfoBar(std::move(proxy))); + + proxy_ptr->info_bar_ = added_bar; + DCHECK(added_bar); + proxies_[infobar_service] = proxy_ptr; + infobar_service->AddObserver(this); +} + +void GlobalConfirmInfoBar::TabChangedAt(content::WebContents* web_contents, + int index, + TabChangeType change_type) { + InfoBarService* infobar_service = + InfoBarService::FromWebContents(web_contents); + auto it = proxies_.find(infobar_service); + if (it == proxies_.end()) + TabInsertedAt(web_contents, index, false); +} + +void GlobalConfirmInfoBar::OnInfoBarRemoved(infobars::InfoBar* info_bar, + bool animate) { + // Do not process alien infobars. + for (auto it : proxies_) { + if (it.second->info_bar_ == info_bar) { + OnManagerShuttingDown(info_bar->owner()); + break; + } + } +} + +void GlobalConfirmInfoBar::OnManagerShuttingDown( + infobars::InfoBarManager* manager) { + manager->RemoveObserver(this); + proxies_.erase(manager); +} diff --git a/pool/shard001/C++/0024148_CD_Animation2D.cpp b/pool/shard001/C++/0024148_CD_Animation2D.cpp new file mode 100644 index 0000000000000000000000000000000000000000..002ad8e40d00baa092176f710342ff86a79de67c --- /dev/null +++ b/pool/shard001/C++/0024148_CD_Animation2D.cpp @@ -0,0 +1,78 @@ +/* + Copyright 2017 Ahnaf Siddiqui + + 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 "CD_Animation2D.h" + +#include "duSwapVector.h" +#include "D_AnimatorSheet.h" +#include "CD_Renderer2D.h" +using namespace Diamond; + +// TODO: refator engine so that animator is given an animation object +// instead of an animation pointer! +// for now, we have memory leaks if user doesn't free animations! +static SwapVector animationSheets; +static SwapVector animatorSheets; + +void dAnimation2DDestroyAll() { + for (auto i = animationSheets.begin(); i != animationSheets.end(); ++i) { + delete *i; + } + animationSheets.clear(); + animatorSheets.clear(); +} + +tCD_Handle dAnimation2DLoadAnimationSheet( + tCD_Handle spritesheet, tD_delta frameLength, int numFrames, int rows, int cols +) { + auto sheet = new AnimationSheet(); + sheet->sprite_sheet = dRenderer2DGetTexture(spritesheet).get(); + sheet->frame_length = frameLength; + sheet->num_frames = numFrames; + sheet->rows = rows; + sheet->columns = cols; + return animationSheets.insert(sheet); +} + +void dAnimation2DDestroyAnimationSheet(tCD_Handle animationSheet) { + delete animationSheets[animationSheet]; + animationSheets.erase(animationSheet); +} + +tCD_Handle dAnimation2DMakeAnimatorSheet( + tCD_Handle renderComponent, tCD_Handle animationSheet +) { + return animatorSheets.emplace(dRenderComponent2DGetRenderComponent(renderComponent).get(), + animationSheets[animationSheet]); +} + +void dAnimation2DDestroyAnimatorSheet(tCD_Handle animatorSheet) { + animatorSheets.erase(animatorSheet); +} + +// Sets the given animator's animation to the given animation sheet +void dAnimation2DSetAnimationSheet( + tCD_Handle animatorSheet, tCD_Handle animationSheet +) { + animatorSheets[animatorSheet].setAnimation(animationSheets[animationSheet]); +} + +// Updates all animations for the current frame +void dAnimation2DUpdate(tD_delta delta) { + for (auto i = animatorSheets.begin(); i != animatorSheets.end(); ++i) { + i->update(delta); + } +} diff --git a/pool/shard001/C++/0024158_mp-r0drv-darwin.cpp b/pool/shard001/C++/0024158_mp-r0drv-darwin.cpp new file mode 100644 index 0000000000000000000000000000000000000000..48d0e097c0006e044d078429f63458d9969f2858 --- /dev/null +++ b/pool/shard001/C++/0024158_mp-r0drv-darwin.cpp @@ -0,0 +1,272 @@ +/* $Id: mp-r0drv-darwin.cpp $ */ +/** @file + * IPRT - Multiprocessor, Ring-0 Driver, Darwin. + */ + +/* + * Copyright (C) 2008-2011 Oracle Corporation + * + * This file is part of VirtualBox Open Source Edition (OSE), as + * available from http://www.virtualbox.org. This file is free software; + * you can redistribute it and/or modify it under the terms of the GNU + * General Public License (GPL) as published by the Free Software + * Foundation, in version 2 as it comes in the "COPYING" file of the + * VirtualBox OSE distribution. VirtualBox OSE is distributed in the + * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. + * + * The contents of this file may alternatively be used under the terms + * of the Common Development and Distribution License Version 1.0 + * (CDDL) only, as it comes in the "COPYING.CDDL" file of the + * VirtualBox OSE distribution, in which case the provisions of the + * CDDL are applicable instead of those of the GPL. + * + * You may elect to license modified versions of this file under the + * terms and conditions of either the GPL or the CDDL or both. + */ + + +/******************************************************************************* +* Header Files * +*******************************************************************************/ +#include "the-darwin-kernel.h" +#include "internal/iprt.h" +#include + +#if defined(RT_ARCH_AMD64) || defined(RT_ARCH_X86) +# include +#endif +#include +#include +#include "r0drv/mp-r0drv.h" + + +/******************************************************************************* +* Global Variables * +*******************************************************************************/ +static int32_t volatile g_cMaxCpus = -1; + + +static int rtMpDarwinInitMaxCpus(void) +{ + int32_t cCpus = -1; + size_t oldLen = sizeof(cCpus); + int rc = sysctlbyname("hw.ncpu", &cCpus, &oldLen, NULL, NULL); + if (rc) + { + printf("IPRT: sysctlbyname(hw.ncpu) failed with rc=%d!\n", rc); + cCpus = 64; /* whatever */ + } + + ASMAtomicWriteS32(&g_cMaxCpus, cCpus); + return cCpus; +} + + +DECLINLINE(int) rtMpDarwinMaxCpus(void) +{ + int cCpus = g_cMaxCpus; + if (RT_UNLIKELY(cCpus <= 0)) + return rtMpDarwinInitMaxCpus(); + return cCpus; +} + + +RTDECL(RTCPUID) RTMpCpuId(void) +{ + return cpu_number(); +} + + +RTDECL(int) RTMpCpuIdToSetIndex(RTCPUID idCpu) +{ + return idCpu < RTCPUSET_MAX_CPUS ? (int)idCpu : -1; +} + + +RTDECL(RTCPUID) RTMpCpuIdFromSetIndex(int iCpu) +{ + return (unsigned)iCpu < RTCPUSET_MAX_CPUS ? (RTCPUID)iCpu : NIL_RTCPUID; +} + + +RTDECL(RTCPUID) RTMpGetMaxCpuId(void) +{ + return rtMpDarwinMaxCpus() - 1; +} + + +RTDECL(bool) RTMpIsCpuPossible(RTCPUID idCpu) +{ + return idCpu < RTCPUSET_MAX_CPUS + && idCpu < (RTCPUID)rtMpDarwinMaxCpus(); +} + + +RTDECL(PRTCPUSET) RTMpGetSet(PRTCPUSET pSet) +{ + RTCPUID idCpu; + + RTCpuSetEmpty(pSet); + idCpu = RTMpGetMaxCpuId(); + do + { + if (RTMpIsCpuPossible(idCpu)) + RTCpuSetAdd(pSet, idCpu); + } while (idCpu-- > 0); + return pSet; +} + + +RTDECL(RTCPUID) RTMpGetCount(void) +{ + return rtMpDarwinMaxCpus(); +} + + +RTDECL(PRTCPUSET) RTMpGetOnlineSet(PRTCPUSET pSet) +{ + /** @todo darwin R0 MP */ + return RTMpGetSet(pSet); +} + + +RTDECL(RTCPUID) RTMpGetOnlineCount(void) +{ + /** @todo darwin R0 MP */ + return RTMpGetCount(); +} + + +RTDECL(bool) RTMpIsCpuOnline(RTCPUID idCpu) +{ + /** @todo darwin R0 MP */ + return RTMpIsCpuPossible(idCpu); +} + + +RTDECL(uint32_t) RTMpGetCurFrequency(RTCPUID idCpu) +{ + /** @todo darwin R0 MP (rainy day) */ + return 0; +} + + +RTDECL(uint32_t) RTMpGetMaxFrequency(RTCPUID idCpu) +{ + /** @todo darwin R0 MP (rainy day) */ + return 0; +} + + +RTDECL(bool) RTMpIsCpuWorkPending(void) +{ + /** @todo (not used on non-Windows platforms yet). */ + return false; +} + + +/** + * Wrapper between the native darwin per-cpu callback and PFNRTWORKER + * for the RTMpOnAll API. + * + * @param pvArg Pointer to the RTMPARGS package. + */ +static void rtmpOnAllDarwinWrapper(void *pvArg) +{ + PRTMPARGS pArgs = (PRTMPARGS)pvArg; + pArgs->pfnWorker(cpu_number(), pArgs->pvUser1, pArgs->pvUser2); +} + + +RTDECL(int) RTMpOnAll(PFNRTMPWORKER pfnWorker, void *pvUser1, void *pvUser2) +{ + RT_ASSERT_INTS_ON(); + + RTMPARGS Args; + Args.pfnWorker = pfnWorker; + Args.pvUser1 = pvUser1; + Args.pvUser2 = pvUser2; + Args.idCpu = NIL_RTCPUID; + Args.cHits = 0; + mp_rendezvous_no_intrs(rtmpOnAllDarwinWrapper, &Args); + return VINF_SUCCESS; +} + + +/** + * Wrapper between the native darwin per-cpu callback and PFNRTWORKER + * for the RTMpOnOthers API. + * + * @param pvArg Pointer to the RTMPARGS package. + */ +static void rtmpOnOthersDarwinWrapper(void *pvArg) +{ + PRTMPARGS pArgs = (PRTMPARGS)pvArg; + RTCPUID idCpu = cpu_number(); + if (pArgs->idCpu != idCpu) + pArgs->pfnWorker(idCpu, pArgs->pvUser1, pArgs->pvUser2); +} + + +RTDECL(int) RTMpOnOthers(PFNRTMPWORKER pfnWorker, void *pvUser1, void *pvUser2) +{ + RT_ASSERT_INTS_ON(); + + int rc; + RTMPARGS Args; + Args.pfnWorker = pfnWorker; + Args.pvUser1 = pvUser1; + Args.pvUser2 = pvUser2; + Args.idCpu = RTMpCpuId(); + Args.cHits = 0; + mp_rendezvous_no_intrs(rtmpOnOthersDarwinWrapper, &Args); + return VINF_SUCCESS; +} + + +/** + * Wrapper between the native darwin per-cpu callback and PFNRTWORKER + * for the RTMpOnSpecific API. + * + * @param pvArg Pointer to the RTMPARGS package. + */ +static void rtmpOnSpecificDarwinWrapper(void *pvArg) +{ + PRTMPARGS pArgs = (PRTMPARGS)pvArg; + RTCPUID idCpu = cpu_number(); + if (pArgs->idCpu == idCpu) + { + pArgs->pfnWorker(idCpu, pArgs->pvUser1, pArgs->pvUser2); + ASMAtomicIncU32(&pArgs->cHits); + } +} + + +RTDECL(int) RTMpOnSpecific(RTCPUID idCpu, PFNRTMPWORKER pfnWorker, void *pvUser1, void *pvUser2) +{ + RT_ASSERT_INTS_ON(); + + int rc; + RTMPARGS Args; + Args.pfnWorker = pfnWorker; + Args.pvUser1 = pvUser1; + Args.pvUser2 = pvUser2; + Args.idCpu = idCpu; + Args.cHits = 0; + mp_rendezvous_no_intrs(rtmpOnSpecificDarwinWrapper, &Args); + return Args.cHits == 1 + ? VINF_SUCCESS + : VERR_CPU_NOT_FOUND; +} + + +RTDECL(int) RTMpPokeCpu(RTCPUID idCpu) +{ + RT_ASSERT_INTS_ON(); + + if (g_pfnR0DarwinCpuInterrupt == NULL) + return VERR_NOT_SUPPORTED; + g_pfnR0DarwinCpuInterrupt(idCpu); + return VINF_SUCCESS; +} + diff --git a/pool/shard001/C++/0024167_Color.cpp b/pool/shard001/C++/0024167_Color.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ead98140b0584a0b0dc4a07d824bdad9d4dfdaf8 --- /dev/null +++ b/pool/shard001/C++/0024167_Color.cpp @@ -0,0 +1,125 @@ +#include "../../../image.h" +#include "../../imageManager.h" +#include "Color.h" + +Color::Color(QQuickItem *parent) + : QQuickItem(parent), ImageProccessor() {} + +QVariantList Color::splitRGB(const QString &uri) { + const cv::Mat *image = ImageManager::get(uri); + if (image) { + if (image->channels() > 2) { + cv::Mat dst[] = { + cv::Mat(image->size(), CV_8UC1), + cv::Mat(image->size(), CV_8UC1), + cv::Mat(image->size(), CV_8UC1) + }; + int from_to[] = { 0,2, 1,1, 2,0 }; + cv::mixChannels(image, 1, &dst[0], 3, from_to, 3); + bool backup = m_resultNew; + m_resultNew = true; + QVariantList result; + result.push_back(putImage(dst[0], uri)); + result.push_back(putImage(dst[1], uri)); + result.push_back(putImage(dst[2], uri)); + m_resultNew = backup; + return result; + } + } + return QVariantList(); +} + +QVariantList Color::splitHSI(const QString &uri) { + const cv::Mat *image = ImageManager::get(uri); + if (image) { + if (image->channels() > 2) { + cv::Mat hls; + cv::cvtColor(*image, hls, cv::COLOR_BGR2HLS); + cv::Mat dst[] = { + cv::Mat(image->size(), CV_8UC1), + cv::Mat(image->size(), CV_8UC1), + cv::Mat(image->size(), CV_8UC1) + }; + int from_to[] = { 0,0, 1,2, 2,1 }; + cv::mixChannels(&hls, 1, &dst[0], 3, from_to, 3); + normalize(dst[0], dst[0], 0, 255, cv::NORM_MINMAX, -1, cv::Mat()); + normalize(dst[1], dst[1], 0, 255, cv::NORM_MINMAX, -1, cv::Mat()); + bool backup = m_resultNew; + m_resultNew = true; + QVariantList result; + result.push_back(putImage(dst[0], uri)); + result.push_back(putImage(dst[1], uri)); + result.push_back(putImage(dst[2], uri)); + m_resultNew = backup; + return result; + } + } + return QVariantList(); +} + +QVariantList Color::splitCMYK(const QString &uri) { + QVariantList result; + const cv::Mat *image = ImageManager::get(uri); + if (image) { + if (image->channels() > 2) { + cv::Mat c, m, y, k; + polka::bgr2cmyk(*image, c, m, y, k); + bool backup = m_resultNew; + m_resultNew = true; + result.push_back(putImage(c, uri)); + result.push_back(putImage(m, uri)); + result.push_back(putImage(y, uri)); + result.push_back(putImage(k, uri)); + m_resultNew = backup; + } + } + return result; +} + +QString Color::colorSlicing(const QString &uri, const QColor &color, float width, bool sphere) { + const cv::Mat *image = ImageManager::get(uri); + if (image) { + cv::Mat dst(image->size(), image->type()); + uchar *psrc = image->data; + uchar *pdst = dst.data; + float blue = static_cast(color.blue()); + float green = static_cast(color.green()); + float red = static_cast(color.red()); + if (image->channels() > 2) { + size_t count = image->rows * image->cols; + if (sphere) { + float r2 = width * width; + for (size_t i = 0; i < count; i++, psrc += 3, pdst += 3) { + if (std::powf(static_cast(psrc[0] - green), 2.0) + + std::powf(static_cast(psrc[1] - blue), 2.0) + + std::powf(static_cast(psrc[2] - red), 2.0) > r2) { + pdst[0] = 128; + pdst[1] = 128; + pdst[2] = 128; + } else { + pdst[0] = psrc[0]; + pdst[1] = psrc[1]; + pdst[2] = psrc[2]; + } + } + } else { + float hf = width / 2; + for (size_t i = 0; i < count; i++, psrc += 3, pdst += 3) { + if (std::abs(static_cast(psrc[0]) - green) > hf || + std::abs(static_cast(psrc[1]) - blue) > hf || + std::abs(static_cast(psrc[2]) - red) > hf) { + pdst[0] = 128; + pdst[1] = 128; + pdst[2] = 128; + } else { + pdst[0] = psrc[0]; + pdst[1] = psrc[1]; + pdst[2] = psrc[2]; + } + } + } + } + return putImage(dst, uri); + } + return QString(); +} diff --git a/pool/shard001/C++/0024169_qrcodedialog.cpp b/pool/shard001/C++/0024169_qrcodedialog.cpp new file mode 100644 index 0000000000000000000000000000000000000000..76dd07c286886d5c1f608e49a390f5fd3eb5c75e --- /dev/null +++ b/pool/shard001/C++/0024169_qrcodedialog.cpp @@ -0,0 +1,173 @@ +#include "qrcodedialog.h" +#include "ui_qrcodedialog.h" + +#include "bitcoinunits.h" +#include "guiconstants.h" +#include "guiutil.h" +#include "optionsmodel.h" + +#include +#if QT_VERSION < 0x050000 +#include +#endif + +#include + +QRCodeDialog::QRCodeDialog(const QString &addr, const QString &label, bool enableReq, QWidget *parent) : + QDialog(parent), + ui(new Ui::QRCodeDialog), + model(0), + address(addr) +{ + ui->setupUi(this); + + setWindowTitle(QString("%1").arg(address)); + + ui->chkReqPayment->setVisible(enableReq); + ui->lblAmount->setVisible(enableReq); + ui->lnReqAmount->setVisible(enableReq); + + ui->lnLabel->setText(label); + + ui->btnSaveAs->setEnabled(false); + + genCode(); +} + +QRCodeDialog::~QRCodeDialog() +{ + delete ui; +} + +void QRCodeDialog::setModel(OptionsModel *model) +{ + this->model = model; + + if (model) + connect(model, SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); + + // update the display unit, to not use the default ("BTC") + updateDisplayUnit(); +} + +void QRCodeDialog::genCode() +{ + QString uri = getURI(); + + if (uri != "") + { + ui->lblQRCode->setText(""); + + QRcode *code = QRcode_encodeString(uri.toUtf8().constData(), 0, QR_ECLEVEL_L, QR_MODE_8, 1); + if (!code) + { + ui->lblQRCode->setText(tr("Error encoding URI into QR Code.")); + return; + } + myImage = QImage(code->width + 8, code->width + 8, QImage::Format_RGB32); + myImage.fill(0xffffff); + unsigned char *p = code->data; + for (int y = 0; y < code->width; y++) + { + for (int x = 0; x < code->width; x++) + { + myImage.setPixel(x + 4, y + 4, ((*p & 1) ? 0x0 : 0xffffff)); + p++; + } + } + QRcode_free(code); + + ui->lblQRCode->setPixmap(QPixmap::fromImage(myImage).scaled(300, 300)); + + ui->outUri->setPlainText(uri); + } +} + +QString QRCodeDialog::getURI() +{ + QString ret = QString("lindencoin:%1").arg(address); + int paramCount = 0; + + ui->outUri->clear(); + + if (ui->chkReqPayment->isChecked()) + { + if (ui->lnReqAmount->validate()) + { + // even if we allow a non BTC unit input in lnReqAmount, we generate the URI with BTC as unit (as defined in BIP21) + ret += QString("?amount=%1").arg(BitcoinUnits::format(BitcoinUnits::BTC, ui->lnReqAmount->value())); + paramCount++; + } + else + { + ui->btnSaveAs->setEnabled(false); + ui->lblQRCode->setText(tr("The entered amount is invalid, please check.")); + return QString(""); + } + } + + if (!ui->lnLabel->text().isEmpty()) + { + QString lbl(QUrl::toPercentEncoding(ui->lnLabel->text())); + ret += QString("%1label=%2").arg(paramCount == 0 ? "?" : "&").arg(lbl); + paramCount++; + } + + if (!ui->lnMessage->text().isEmpty()) + { + QString msg(QUrl::toPercentEncoding(ui->lnMessage->text())); + ret += QString("%1message=%2").arg(paramCount == 0 ? "?" : "&").arg(msg); + paramCount++; + } + + // limit URI length to prevent a DoS against the QR-Code dialog + if (ret.length() > MAX_URI_LENGTH) + { + ui->btnSaveAs->setEnabled(false); + ui->lblQRCode->setText(tr("Resulting URI too long, try to reduce the text for label / message.")); + return QString(""); + } + + ui->btnSaveAs->setEnabled(true); + return ret; +} + +void QRCodeDialog::on_lnReqAmount_textChanged() +{ + genCode(); +} + +void QRCodeDialog::on_lnLabel_textChanged() +{ + genCode(); +} + +void QRCodeDialog::on_lnMessage_textChanged() +{ + genCode(); +} + +void QRCodeDialog::on_btnSaveAs_clicked() +{ + QString fn = GUIUtil::getSaveFileName(this, tr("Save QR Code"), QString(), tr("PNG Images (*.png)")); + if (!fn.isEmpty()) + myImage.scaled(EXPORT_IMAGE_SIZE, EXPORT_IMAGE_SIZE).save(fn); +} + +void QRCodeDialog::on_chkReqPayment_toggled(bool fChecked) +{ + if (!fChecked) + // if chkReqPayment is not active, don't display lnReqAmount as invalid + ui->lnReqAmount->setValid(true); + + genCode(); +} + +void QRCodeDialog::updateDisplayUnit() +{ + if (model) + { + // Update lnReqAmount with the current unit + ui->lnReqAmount->setDisplayUnit(model->getDisplayUnit()); + } +} diff --git a/pool/shard001/C++/0024172_function_sum.cpp b/pool/shard001/C++/0024172_function_sum.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a9b020a35f1bbf3267e3fdd0ce3fa05ed9a094ce --- /dev/null +++ b/pool/shard001/C++/0024172_function_sum.cpp @@ -0,0 +1,87 @@ +/** + * \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 + * Radu Ialovoi + */ + +#include "precompiled_header.hpp" +#include "traverse.hpp" + + +/*! + * \brief + * TODO + * + * \param function_parameter& parameters + * container of parameters and context which holds information about the current calculation state + * + * + * \returns + * TODO + * + * \details + * TODO + * + * \see + * internal::Sum | internal::SumSq | internal::Counter | function_stdeva | function_stdevp | function_stdevpa | function_dstdev | function_dstdevp + * + * \author + * Radu Ialovoi + */ +class sum_alg : public error_handling_alg +{ +private: + size_t m_count; + double s; +public: + sum_alg() { + m_count = 0; + s = 0; + } + + void operator()( const variant& arg ) { + m_count++; + s += arg.as_double(); + } + + operator variant() { + // if ( 0 == m_count ) { + // return variant( variant::error_n_a ); + // } + + return ( variant( s ) ); + } +}; + +interpreter_variant function_sum( function_parameter& parameters ) +{ + sum_alg alg; + return interpreter_variant( traverse( parameters, alg ) ); +} diff --git a/pool/shard001/C++/0024176_h2_compress.cc b/pool/shard001/C++/0024176_h2_compress.cc new file mode 100644 index 0000000000000000000000000000000000000000..5b9181586cbbe335ca422afdf5de2a8c56a487ba --- /dev/null +++ b/pool/shard001/C++/0024176_h2_compress.cc @@ -0,0 +1,133 @@ +/* + * + * Copyright 2015 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include "test/core/end2end/end2end_tests.h" + +#include + +#include +#include +#include +#include +#include +#include +#include "src/core/ext/filters/client_channel/client_channel.h" +#include "src/core/ext/filters/http/server/http_server_filter.h" +#include "src/core/ext/transport/chttp2/transport/chttp2_transport.h" +#include "src/core/lib/channel/channel_args.h" +#include "src/core/lib/channel/connected_channel.h" +#include "src/core/lib/surface/channel.h" +#include "src/core/lib/surface/server.h" +#include "test/core/util/port.h" +#include "test/core/util/test_config.h" + +typedef struct fullstack_compression_fixture_data { + char* localaddr; + grpc_channel_args* client_args_compression; + grpc_channel_args* server_args_compression; +} fullstack_compression_fixture_data; + +static grpc_end2end_test_fixture chttp2_create_fixture_fullstack_compression( + grpc_channel_args* client_args, grpc_channel_args* server_args) { + grpc_end2end_test_fixture f; + int port = grpc_pick_unused_port_or_die(); + fullstack_compression_fixture_data* ffd = + static_cast( + gpr_malloc(sizeof(fullstack_compression_fixture_data))); + memset(ffd, 0, sizeof(fullstack_compression_fixture_data)); + + gpr_join_host_port(&ffd->localaddr, "localhost", port); + + memset(&f, 0, sizeof(f)); + f.fixture_data = ffd; + f.cq = grpc_completion_queue_create_for_next(nullptr); + f.shutdown_cq = grpc_completion_queue_create_for_pluck(nullptr); + + return f; +} + +void chttp2_init_client_fullstack_compression(grpc_end2end_test_fixture* f, + grpc_channel_args* client_args) { + fullstack_compression_fixture_data* ffd = + static_cast(f->fixture_data); + if (ffd->client_args_compression != nullptr) { + grpc_core::ExecCtx exec_ctx; + grpc_channel_args_destroy(ffd->client_args_compression); + } + ffd->client_args_compression = grpc_channel_args_set_compression_algorithm( + client_args, GRPC_COMPRESS_GZIP); + f->client = grpc_insecure_channel_create( + ffd->localaddr, ffd->client_args_compression, nullptr); +} + +void chttp2_init_server_fullstack_compression(grpc_end2end_test_fixture* f, + grpc_channel_args* server_args) { + fullstack_compression_fixture_data* ffd = + static_cast(f->fixture_data); + if (ffd->server_args_compression != nullptr) { + grpc_core::ExecCtx exec_ctx; + grpc_channel_args_destroy(ffd->server_args_compression); + } + ffd->server_args_compression = grpc_channel_args_set_compression_algorithm( + server_args, GRPC_COMPRESS_GZIP); + if (f->server) { + grpc_server_destroy(f->server); + } + f->server = grpc_server_create(ffd->server_args_compression, nullptr); + grpc_server_register_completion_queue(f->server, f->cq, nullptr); + GPR_ASSERT(grpc_server_add_insecure_http2_port(f->server, ffd->localaddr)); + grpc_server_start(f->server); +} + +void chttp2_tear_down_fullstack_compression(grpc_end2end_test_fixture* f) { + grpc_core::ExecCtx exec_ctx; + fullstack_compression_fixture_data* ffd = + static_cast(f->fixture_data); + grpc_channel_args_destroy(ffd->client_args_compression); + grpc_channel_args_destroy(ffd->server_args_compression); + gpr_free(ffd->localaddr); + gpr_free(ffd); +} + +/* All test configurations */ +static grpc_end2end_test_config configs[] = { + {"chttp2/fullstack_compression", + FEATURE_MASK_SUPPORTS_DELAYED_CONNECTION | + FEATURE_MASK_SUPPORTS_CLIENT_CHANNEL | + FEATURE_MASK_SUPPORTS_AUTHORITY_HEADER, + chttp2_create_fixture_fullstack_compression, + chttp2_init_client_fullstack_compression, + chttp2_init_server_fullstack_compression, + chttp2_tear_down_fullstack_compression}, +}; + +int main(int argc, char** argv) { + size_t i; + + grpc_test_init(argc, argv); + grpc_end2end_tests_pre_init(); + grpc_init(); + + for (i = 0; i < sizeof(configs) / sizeof(*configs); i++) { + grpc_end2end_tests(argc, argv, configs[i]); + } + + grpc_shutdown(); + + return 0; +} diff --git a/pool/shard001/C++/0024187_Particle.cpp b/pool/shard001/C++/0024187_Particle.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0f46facea5613f8e0f60b7b4835d4d17e4d72f6f --- /dev/null +++ b/pool/shard001/C++/0024187_Particle.cpp @@ -0,0 +1,46 @@ +#include "..\Particle.h" + + + +Particle::Particle(ofVec2f pos) +{ + myPos = pos; + myVel = ofVec2f(ofRandom(-10.f, 10.f), ofRandom(-10.f, 10.f)); + myLifeSpan = INTIAL_LIFE_SPAN; + +} + + +Particle::~Particle() +{ +} + +void Particle::update(float changeInVel) { + + myVel += myAccel; + myPos += myVel * changeInVel; + + if (myLifeSpan > 0) { + myLifeSpan -= 1.f; + } + +} + +void Particle::draw() { + + + if (myLifeSpan > 90) { + ofSetColor(0, 200, 255); + } + else { + ofSetColor(ofRandom(100), ofRandom(255), ofRandom(100)); + } + float size = ofMap(myLifeSpan, 0, 200, 0, 2); + + ofDrawBox(myPos, size); +} + + +void Particle::applyForce(ofVec2f force) { + myAccel = force; +} diff --git a/pool/shard001/C++/0024193_test_miller_rabin.cpp b/pool/shard001/C++/0024193_test_miller_rabin.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bece2284e699d52ae357b69a9e4f7706c68dad6f --- /dev/null +++ b/pool/shard001/C++/0024193_test_miller_rabin.cpp @@ -0,0 +1,87 @@ +/////////////////////////////////////////////////////////////// +// Copyright 2012 John Maddock. Distributed under the Boost +// Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt + +#ifdef _MSC_VER +#define _SCL_SECURE_NO_WARNINGS +#endif + +#include +#include +#include +#include +#include +#include +#include "test.hpp" + +template +void test() +{ + // + // Very simple test program to verify that the GMP's Miller-Rabin + // implementation and this one agree on whether some random numbers + // are prime or not. Of course these are probabilistic tests so there's + // no reason why they should actually agree - except the probability of + // disagreement for 25 trials is almost infinitely small. + // + using namespace boost::random; + using namespace boost::multiprecision; + + typedef I test_type; + + static const unsigned test_bits = + std::numeric_limits::digits && (std::numeric_limits::digits <= 256) + ? std::numeric_limits::digits + : 128; + + independent_bits_engine gen; + // + // We must use a different generator for the tests and number generation, otherwise + // we get false positives. Further we use the same random number engine for the + // Miller Rabin test as GMP uses internally: + // + mt19937 gen2; + + // + // Begin by testing the primes in our table as all these should return true: + // + for (unsigned i = 1; i < boost::math::max_prime; ++i) + { + BOOST_TEST(miller_rabin_test(test_type(boost::math::prime(i)), 25, gen)); + BOOST_TEST(mpz_probab_prime_p(mpz_int(boost::math::prime(i)).backend().data(), 25)); + } + // + // Now test some random values and compare GMP's native routine with ours. + // + for (unsigned i = 0; i < 10000; ++i) + { + test_type n = gen(); + bool is_prime_boost = miller_rabin_test(n, 25, gen2); + bool is_gmp_prime = mpz_probab_prime_p(mpz_int(n).backend().data(), 25) ? true : false; + if (is_prime_boost && is_gmp_prime) + { + std::cout << "We have a prime: " << std::hex << std::showbase << n << std::endl; + } + if (is_prime_boost != is_gmp_prime) + std::cout << std::hex << std::showbase << "n = " << n << std::endl; + BOOST_CHECK_EQUAL(is_prime_boost, is_gmp_prime); + } +} + +int main() +{ + using namespace boost::multiprecision; + + test(); + test >(); + test(); + test(); + + test(); + test, et_off> >(); + test(); + test(); + + return boost::report_errors(); +} diff --git a/pool/shard001/C++/0024204_system_storage_apitest.cc b/pool/shard001/C++/0024204_system_storage_apitest.cc new file mode 100644 index 0000000000000000000000000000000000000000..1a98c1ceef4ab30679a65bb25ee475e41e828c63 --- /dev/null +++ b/pool/shard001/C++/0024204_system_storage_apitest.cc @@ -0,0 +1,149 @@ +// 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 + +#include "base/message_loop/message_loop.h" +#include "base/strings/utf_string_conversions.h" +#include "chrome/browser/extensions/api/system_storage/storage_api_test_util.h" +#include "chrome/browser/extensions/extension_apitest.h" +#include "components/storage_monitor/storage_monitor.h" +#include "components/storage_monitor/test_storage_monitor.h" +#include "extensions/browser/api/system_storage/storage_info_provider.h" +#include "extensions/test/extension_test_message_listener.h" +#include "extensions/test/result_catcher.h" + +namespace { + +using extensions::StorageUnitInfoList; +using extensions::test::TestStorageUnitInfo; +using extensions::test::kRemovableStorageData; +using storage_monitor::StorageMonitor; +using storage_monitor::TestStorageMonitor; + +const struct TestStorageUnitInfo kTestingData[] = { + {"dcim:device:001", "0xbeaf", 4098, 1}, + {"path:device:002", "/home", 4098, 2}, + {"path:device:003", "/data", 10000, 3} +}; + +} // namespace + +class TestStorageInfoProvider : public extensions::StorageInfoProvider { + public: + TestStorageInfoProvider(const struct TestStorageUnitInfo* testing_data, + size_t n); + + private: + virtual ~TestStorageInfoProvider(); + + // StorageInfoProvider implementations. + virtual double GetStorageFreeSpaceFromTransientIdOnFileThread( + const std::string& transient_id) OVERRIDE; + + std::vector testing_data_; +}; + +TestStorageInfoProvider::TestStorageInfoProvider( + const struct TestStorageUnitInfo* testing_data, size_t n) + : testing_data_(testing_data, testing_data + n) { +} + +TestStorageInfoProvider::~TestStorageInfoProvider() { +} + +double TestStorageInfoProvider::GetStorageFreeSpaceFromTransientIdOnFileThread( + const std::string& transient_id) { + std::string device_id = + StorageMonitor::GetInstance()->GetDeviceIdForTransientId( + transient_id); + for (size_t i = 0; i < testing_data_.size(); ++i) { + if (testing_data_[i].device_id == device_id) { + return static_cast(testing_data_[i].available_capacity); + } + } + return -1; +} + +class SystemStorageApiTest : public ExtensionApiTest { + public: + SystemStorageApiTest() {} + virtual ~SystemStorageApiTest() {} + + virtual void SetUpOnMainThread() OVERRIDE { + TestStorageMonitor::CreateForBrowserTests(); + } + + virtual void SetUpInProcessBrowserTestFixture() OVERRIDE { + ExtensionApiTest::SetUpInProcessBrowserTestFixture(); + message_loop_.reset(new base::MessageLoopForUI); + } + + void SetUpAllMockStorageDevices() { + for (size_t i = 0; i < arraysize(kTestingData); ++i) { + AttachRemovableStorage(kTestingData[i]); + } + } + + void AttachRemovableStorage( + const struct TestStorageUnitInfo& removable_storage_info) { + StorageMonitor::GetInstance()->receiver()->ProcessAttach( + extensions::test::BuildStorageInfoFromTestStorageUnitInfo( + removable_storage_info)); + } + + void DetachRemovableStorage(const std::string& id) { + StorageMonitor::GetInstance()->receiver()->ProcessDetach(id); + } + + private: + scoped_ptr message_loop_; +}; + +IN_PROC_BROWSER_TEST_F(SystemStorageApiTest, Storage) { + SetUpAllMockStorageDevices(); + TestStorageInfoProvider* provider = + new TestStorageInfoProvider(kTestingData, + arraysize(kTestingData)); + extensions::StorageInfoProvider::InitializeForTesting(provider); + std::vector > device_ids_listeners; + for (size_t i = 0; i < arraysize(kTestingData); ++i) { + linked_ptr listener( + new ExtensionTestMessageListener( + StorageMonitor::GetInstance()->GetTransientIdForDeviceId( + kTestingData[i].device_id), + false)); + device_ids_listeners.push_back(listener); + } + ASSERT_TRUE(RunPlatformAppTest("system/storage")) << message_; + for (size_t i = 0; i < device_ids_listeners.size(); ++i) + EXPECT_TRUE(device_ids_listeners[i]->WaitUntilSatisfied()); +} + +IN_PROC_BROWSER_TEST_F(SystemStorageApiTest, StorageAttachment) { + extensions::ResultCatcher catcher; + ExtensionTestMessageListener attach_listener("attach", false); + ExtensionTestMessageListener detach_listener("detach", false); + + EXPECT_TRUE(LoadExtension( + test_data_dir_.AppendASCII("system/storage_attachment"))); + // Simulate triggering onAttached event. + ASSERT_TRUE(attach_listener.WaitUntilSatisfied()); + + AttachRemovableStorage(kRemovableStorageData); + + std::string removable_storage_transient_id = + StorageMonitor::GetInstance()->GetTransientIdForDeviceId( + kRemovableStorageData.device_id); + ExtensionTestMessageListener detach_device_id_listener( + removable_storage_transient_id, false); + + // Simulate triggering onDetached event. + ASSERT_TRUE(detach_listener.WaitUntilSatisfied()); + DetachRemovableStorage(kRemovableStorageData.device_id); + + ASSERT_TRUE(detach_device_id_listener.WaitUntilSatisfied()); + + EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); +} diff --git a/pool/shard001/C++/0024209_overviewpage.cpp b/pool/shard001/C++/0024209_overviewpage.cpp new file mode 100644 index 0000000000000000000000000000000000000000..dbd31c3c19aaa4a7069f9964e686cc2224116451 --- /dev/null +++ b/pool/shard001/C++/0024209_overviewpage.cpp @@ -0,0 +1,200 @@ +#include "overviewpage.h" +#include "ui_overviewpage.h" + +#include "walletmodel.h" +#include "bitcoinunits.h" +#include "optionsmodel.h" +#include "transactiontablemodel.h" +#include "transactionfilterproxy.h" +#include "guiutil.h" +#include "guiconstants.h" + +#include +#include + +#define DECORATION_SIZE 64 +#define NUM_ITEMS 3 + +class TxViewDelegate : public QAbstractItemDelegate +{ + Q_OBJECT +public: + TxViewDelegate(): QAbstractItemDelegate(), unit(BitcoinUnits::BTC) + { + + } + + inline void paint(QPainter *painter, const QStyleOptionViewItem &option, + const QModelIndex &index ) const + { + painter->save(); + + QIcon icon = qvariant_cast(index.data(Qt::DecorationRole)); + QRect mainRect = option.rect; + QRect decorationRect(mainRect.topLeft(), QSize(DECORATION_SIZE, DECORATION_SIZE)); + int xspace = DECORATION_SIZE + 8; + int ypad = 6; + int halfheight = (mainRect.height() - 2*ypad)/2; + QRect amountRect(mainRect.left() + xspace, mainRect.top()+ypad, mainRect.width() - xspace, halfheight); + QRect addressRect(mainRect.left() + xspace, mainRect.top()+ypad+halfheight, mainRect.width() - xspace, halfheight); + icon.paint(painter, decorationRect); + + QDateTime date = index.data(TransactionTableModel::DateRole).toDateTime(); + QString address = index.data(Qt::DisplayRole).toString(); + qint64 amount = index.data(TransactionTableModel::AmountRole).toLongLong(); + bool confirmed = index.data(TransactionTableModel::ConfirmedRole).toBool(); + QVariant value = index.data(Qt::ForegroundRole); + QColor foreground = option.palette.color(QPalette::Text); + if(qVariantCanConvert(value)) + { + foreground = qvariant_cast(value); + } + + painter->setPen(foreground); + painter->drawText(addressRect, Qt::AlignLeft|Qt::AlignVCenter, address); + + if(amount < 0) + { + foreground = COLOR_NEGATIVE; + } + else if(!confirmed) + { + foreground = COLOR_UNCONFIRMED; + } + else + { + foreground = option.palette.color(QPalette::Text); + } + painter->setPen(foreground); + QString amountText = BitcoinUnits::formatWithUnit(unit, amount, true); + if(!confirmed) + { + amountText = QString("[") + amountText + QString("]"); + } + painter->drawText(amountRect, Qt::AlignRight|Qt::AlignVCenter, amountText); + + painter->setPen(option.palette.color(QPalette::Text)); + painter->drawText(amountRect, Qt::AlignLeft|Qt::AlignVCenter, GUIUtil::dateTimeStr(date)); + + painter->restore(); + } + + inline QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const + { + return QSize(DECORATION_SIZE, DECORATION_SIZE); + } + + int unit; + +}; +#include "overviewpage.moc" + +OverviewPage::OverviewPage(QWidget *parent) : + QWidget(parent), + ui(new Ui::OverviewPage), + currentBalance(-1), + currentUnconfirmedBalance(-1), + currentImmatureBalance(-1), + txdelegate(new TxViewDelegate()), + filter(0) +{ + ui->setupUi(this); + + // Recent transactions + ui->listTransactions->setItemDelegate(txdelegate); + ui->listTransactions->setIconSize(QSize(DECORATION_SIZE, DECORATION_SIZE)); + ui->listTransactions->setMinimumHeight(NUM_ITEMS * (DECORATION_SIZE + 2)); + ui->listTransactions->setAttribute(Qt::WA_MacShowFocusRect, false); + + connect(ui->listTransactions, SIGNAL(clicked(QModelIndex)), this, SLOT(handleTransactionClicked(QModelIndex))); + + // init "out of sync" warning labels + ui->labelWalletStatus->setText("(" + tr("Out of sync") + ")"); + ui->labelTransactionsStatus->setText("(" + tr("Out of sync") + ")"); + + // start with displaying the "out of sync" warnings + showOutOfSyncWarning(true); +} + +void OverviewPage::handleTransactionClicked(const QModelIndex &index) +{ + if(filter) + emit transactionClicked(filter->mapToSource(index)); +} + +OverviewPage::~OverviewPage() +{ + delete ui; +} + +void OverviewPage::setBalance(qint64 balance, qint64 unconfirmedBalance, qint64 immatureBalance) +{ + int unit = model->getOptionsModel()->getDisplayUnit(); + currentBalance = balance; + currentUnconfirmedBalance = unconfirmedBalance; + currentImmatureBalance = immatureBalance; + ui->labelBalance->setText(BitcoinUnits::formatWithUnit(unit, balance)); + ui->labelUnconfirmed->setText(BitcoinUnits::formatWithUnit(unit, unconfirmedBalance)); + ui->labelImmature->setText(BitcoinUnits::formatWithUnit(unit, immatureBalance)); + + // only show immature (newly mined) balance if it's non-zero, so as not to complicate things + // for the non-mining users + bool showImmature = immatureBalance != 0; + ui->labelImmature->setVisible(showImmature); + ui->labelImmatureText->setVisible(showImmature); +} + +void OverviewPage::setNumTransactions(int count) +{ + ui->labelNumTransactions->setText(QLocale::system().toString(count)); +} + +void OverviewPage::setModel(WalletModel *model) +{ + this->model = model; + if(model && model->getOptionsModel()) + { + // Set up transaction list + filter = new TransactionFilterProxy(); + filter->setSourceModel(model->getTransactionTableModel()); + filter->setLimit(NUM_ITEMS); + filter->setDynamicSortFilter(true); + filter->setSortRole(Qt::EditRole); + filter->sort(TransactionTableModel::Status, Qt::DescendingOrder); + + ui->listTransactions->setModel(filter); + ui->listTransactions->setModelColumn(TransactionTableModel::ToAddress); + + // Keep up to date with wallet + setBalance(model->getBalance(), model->getUnconfirmedBalance(), model->getImmatureBalance()); + connect(model, SIGNAL(balanceChanged(qint64, qint64, qint64)), this, SLOT(setBalance(qint64, qint64, qint64))); + + setNumTransactions(model->getNumTransactions()); + connect(model, SIGNAL(numTransactionsChanged(int)), this, SLOT(setNumTransactions(int))); + + connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); + } + + // update the display unit, to not use the default ("EWC") + updateDisplayUnit(); +} + +void OverviewPage::updateDisplayUnit() +{ + if(model && model->getOptionsModel()) + { + if(currentBalance != -1) + setBalance(currentBalance, currentUnconfirmedBalance, currentImmatureBalance); + + // Update txdelegate->unit with the current unit + txdelegate->unit = model->getOptionsModel()->getDisplayUnit(); + + ui->listTransactions->update(); + } +} + +void OverviewPage::showOutOfSyncWarning(bool fShow) +{ + ui->labelWalletStatus->setVisible(fShow); + ui->labelTransactionsStatus->setVisible(fShow); +} diff --git a/pool/shard001/C++/0024213_evena.cc b/pool/shard001/C++/0024213_evena.cc new file mode 100644 index 0000000000000000000000000000000000000000..e9459a8e4094583e7dab19667edb62704c40ec99 --- /dev/null +++ b/pool/shard001/C++/0024213_evena.cc @@ -0,0 +1,49 @@ +// a1.cc: this file is part of the Vaucanson project. +// +// Vaucanson, a generic library for finite state machines. +// +// Copyright (C) 2005, 2006, 2007 The Vaucanson Group. +// +// 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. +// +// The complete GNU General Public Licence Notice can be found as the +// `COPYING' file in the root directory. +// +// The Vaucanson Group consists of people listed in the `AUTHORS' file. +// +#include + +using namespace vcsn; +using namespace vcsn::boolean_automaton; + +#include + + +int +main(int argc, char **argv) +{ + + alphabet_t A; + A.insert('a'); + A.insert('b'); + + automaton_t evena = make_automaton(A); + + hstate_t p = evena.add_state(); + hstate_t q = evena.add_state(); + + evena.add_letter_transition(p, p, 'b'); + evena.add_letter_transition(q, q, 'b'); + + evena.add_letter_transition(p, q, 'a'); + evena.add_letter_transition(q, p, 'a'); + + + evena.set_initial(p); + evena.set_final(p); + + tools::dumper(argc, argv)(std::cout, evena, "evena"); +} diff --git a/pool/shard001/C++/0024223_MicroFlash.cpp b/pool/shard001/C++/0024223_MicroFlash.cpp new file mode 100644 index 0000000000000000000000000000000000000000..887f4c04ee28b1157189698b17391057dcda3393 --- /dev/null +++ b/pool/shard001/C++/0024223_MicroFlash.cpp @@ -0,0 +1,137 @@ +//////////////////////////////////////////////////////////////////////////////// +// Filename: MicroFlash.cpp +// Author: PB2.x +// Date: PB2.x +// +// Description: Implementation of the CMicroFlash class, this has been +// unmodified from PB2.x +// +//////////////////////////////////////////////////////////////////////////////// + +#include "stdafx.h" +#include "MicroFlash.h" + + +///////////////////////////////////////////////////////////////////////////// +// CMicroFlash + +/******************************************************************************/ +BOOL CMicroFlash::OpenPort (void) +{ + DCB ComSet; + + m_hComPort = CreateFile(m_strPort, GENERIC_READ | GENERIC_WRITE, 0, NULL, + OPEN_EXISTING, 0, NULL); + + DWORD err = GetLastError(); + + if(m_hComPort==INVALID_HANDLE_VALUE) return FALSE; + + if (!GetCommState(m_hComPort, &ComSet)) return FALSE; + + ComSet.BaudRate = 9600; + ComSet.fBinary = TRUE; + ComSet.fOutxCtsFlow = FALSE;//TRUE; + ComSet.fOutxDsrFlow = FALSE;//TRUE; + ComSet.fDtrControl = DTR_CONTROL_ENABLE; + ComSet.fTXContinueOnXoff = FALSE; + ComSet.fRtsControl = RTS_CONTROL_ENABLE; + + ComSet.fOutX = TRUE; + ComSet.fInX = TRUE; + ComSet.ByteSize = 8; + ComSet.Parity = NOPARITY; + ComSet.StopBits = ONESTOPBIT; + + if (!SetCommState(m_hComPort, &ComSet)) return FALSE; + + return TRUE; +} + +/******************************************************************************/ +void CMicroFlash::ClosePort (void) +{ + CloseHandle(m_hComPort); + m_hComPort = INVALID_HANDLE_VALUE; + return; +} + +/******************************************************************************/ +STDMETHODIMP CMicroFlash::AddData(BSTR strData) +{ + m_strData.Append (strData); + + return S_OK; +} + +/******************************************************************************/ +STDMETHODIMP CMicroFlash::AddLine(BSTR strLine) +{ + m_strData.Append (strLine); + m_strData.Append (TEXT("\r\n")); + + return S_OK; +} + +/******************************************************************************/ +STDMETHODIMP CMicroFlash::Clear() +{ + m_strData.Empty (); + + return S_OK; +} + +/******************************************************************************/ +STDMETHODIMP CMicroFlash::Print(int iCopies) +{ + HRESULT r; + char endLine [] = "\r\n"; + DWORD dwBytesWritten; + char *pcPrintBuf; + int iLineCount, n; + + // Assume failure + r = S_FALSE; + + pcPrintBuf = NULL; + iLineCount = 0; + + if(!OpenPort()) goto Exit; + + // Add formfeed to data + m_strData.Append (TEXT("\x0C")); + + // Convert to char data + n = m_strData.Length (); + pcPrintBuf = new char [n + 1]; + wcstombs (pcPrintBuf, m_strData, n); + pcPrintBuf [n] = 0; + + // Wakeup the printer + for(iLineCount = 0; iLineCount < 10; iLineCount++) + WriteFile(m_hComPort, endLine, strlen(endLine), &dwBytesWritten, NULL); + + Sleep(500); + + // Print the buffer + for(iLineCount = 0; iLineCount < iCopies; iLineCount++) + if(!WriteFile(m_hComPort, pcPrintBuf, strlen(pcPrintBuf), + &dwBytesWritten, NULL)) goto Exit; + + m_strData.Empty (); + + r = S_OK; + +Exit: + ClosePort (); + delete [] pcPrintBuf; + + return r; +} + +STDMETHODIMP CMicroFlash::SetPort(BSTR strPort) +{ + m_strPort = strPort; + + return S_OK; +} diff --git a/pool/shard001/C++/0024225_MockWorkerTracker.cc b/pool/shard001/C++/0024225_MockWorkerTracker.cc new file mode 100644 index 0000000000000000000000000000000000000000..997b53419a95962461012e9ddea8a9494fdbfadc --- /dev/null +++ b/pool/shard001/C++/0024225_MockWorkerTracker.cc @@ -0,0 +1,91 @@ +#include "MockWorkerTracker.h" +#include "core/Resource.h" +#include "core/TritonSortAssert.h" + +void MockWorkerTracker::spawn() { + // No-op +} + +void MockWorkerTracker::addSource(WorkerTrackerInterface* prevTracker) { + // No-op +} + +bool MockWorkerTracker::hasAlreadySpawned() const { + return true; +} + +void MockWorkerTracker::noMoreWork() { + // No-op +} + +void MockWorkerTracker::notifyWorkerCompleted(uint64_t id) { + // No-op +} + +void MockWorkerTracker::createWorkers() { + // No-op +} + +void MockWorkerTracker::destroyWorkers() { + // No-op +} + +void MockWorkerTracker::waitForWorkersToFinish() { + // No-op +} + +void MockWorkerTracker::addDownstreamTracker( + WorkerTrackerInterface* downstreamTracker) { + downstreamTrackerVector.push_back(downstreamTracker); +} + +void MockWorkerTracker::addDownstreamTracker( + WorkerTrackerInterface* downstreamTracker, + const std::string& trackerDescription) { + + ABORT("Not implemented"); +} + +const WorkerTrackerInterface::WorkerTrackerVector& +MockWorkerTracker::downstreamTrackers() const { + return downstreamTrackerVector; +} + +const std::string& MockWorkerTracker::getStageName() const { + return stageName; +} + +void MockWorkerTracker::getNewWork(uint64_t queueID, WorkQueue& destWorkQueue) { + ABORT("Shouldn't be getting work from a MockWorkerTracker"); +} + +Resource* MockWorkerTracker::getNewWork(uint64_t queueID) { + ABORT("Shouldn't be getting work from a MockWorkerTracker"); + return NULL; +} + +bool MockWorkerTracker::attemptGetNewWork( + uint64_t queueID, Resource*& workUnit) { + ABORT("Shouldn't be getting work from a MockWorkerTracker"); + return false; +} + +MockWorkerTracker::MockWorkerTracker(const std::string& _stageName) + : stageName(_stageName) { +} + +void MockWorkerTracker::addWorkUnit(Resource* workUnit) { + workUnits.push(workUnit); +} + +const std::queue& MockWorkerTracker::getWorkQueue() const { + return workUnits; +} + +void MockWorkerTracker::deleteAllWorkUnits() { + while (!workUnits.empty()) { + Resource* workUnit = workUnits.front(); + delete workUnit; + workUnits.pop(); + } +} diff --git a/pool/shard001/C++/0024227_databreakpointdlg.cpp b/pool/shard001/C++/0024227_databreakpointdlg.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0dec934206c9d3adde3831caf528e1c59ecf97fa --- /dev/null +++ b/pool/shard001/C++/0024227_databreakpointdlg.cpp @@ -0,0 +1,86 @@ +/* + * This file is part of the Code::Blocks IDE and licensed under the GNU General Public License, version 3 + * http://www.gnu.org/licenses/gpl-3.0.html + * + * $Revision: 8446 $ + * $Id: databreakpointdlg.cpp 8446 2012-10-10 23:16:06Z tpetrov $ + * $HeadURL: svn://svn.code.sf.net/p/codeblocks/code/trunk/src/plugins/debuggergdb/databreakpointdlg.cpp $ + */ + +#include "databreakpointdlg.h" +#include "debugger_defs.h" + +//(*InternalHeaders(DataBreakpointDlg) +#include +#include +#include +//*) + +//(*IdInit(DataBreakpointDlg) +const long DataBreakpointDlg::ID_CHK_ENABLED = wxNewId(); +const long DataBreakpointDlg::ID_TXT_DATA_EXPRESION = wxNewId(); +const long DataBreakpointDlg::ID_RDO_CONDITION = wxNewId(); +//*) + +BEGIN_EVENT_TABLE(DataBreakpointDlg,wxScrollingDialog) + //(*EventTable(DataBreakpointDlg) + //*) +END_EVENT_TABLE() + +DataBreakpointDlg::DataBreakpointDlg(wxWindow *parent, const wxString& dataExpression, bool enabled, int selection) +{ + //(*Initialize(DataBreakpointDlg) + wxBoxSizer* bszMain; + + Create(parent, wxID_ANY, _("Data breakpoint"), wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE, _T("wxID_ANY")); + bszMain = new wxBoxSizer(wxVERTICAL); + m_enabled = new wxCheckBox(this, ID_CHK_ENABLED, _("Enabled"), wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_CHK_ENABLED")); + m_enabled->SetValue(false); + bszMain->Add(m_enabled, 0, wxTOP|wxLEFT|wxRIGHT|wxEXPAND|wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL, 8); + m_dataExpression = new wxTextCtrl(this, ID_TXT_DATA_EXPRESION, wxEmptyString, wxDefaultPosition, wxSize(265,23), wxTE_PROCESS_ENTER, wxDefaultValidator, _T("ID_TXT_DATA_EXPRESION")); + m_dataExpression->SetFocus(); + bszMain->Add(m_dataExpression, 1, wxTOP|wxLEFT|wxRIGHT|wxEXPAND|wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL, 8); + wxString __wxRadioBoxChoices_1[3] = + { + _("Break on read"), + _("Break on write"), + _("Break on read or write") + }; + m_condition = new wxRadioBox(this, ID_RDO_CONDITION, _("Condition"), wxDefaultPosition, wxDefaultSize, 3, __wxRadioBoxChoices_1, 1, 0, wxDefaultValidator, _T("ID_RDO_CONDITION")); + bszMain->Add(m_condition, 0, wxTOP|wxLEFT|wxRIGHT|wxEXPAND|wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL, 8); + StdDialogButtonSizer1 = new wxStdDialogButtonSizer(); + StdDialogButtonSizer1->AddButton(new wxButton(this, wxID_OK, wxEmptyString)); + StdDialogButtonSizer1->AddButton(new wxButton(this, wxID_CANCEL, wxEmptyString)); + StdDialogButtonSizer1->Realize(); + bszMain->Add(StdDialogButtonSizer1, 0, wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 8); + SetSizer(bszMain); + bszMain->Fit(this); + bszMain->SetSizeHints(this); + Center(); + //*) + + m_enabled->SetValue(enabled); + m_condition->SetSelection(selection); + m_dataExpression->SetValue(dataExpression); +} + +DataBreakpointDlg::~DataBreakpointDlg() +{ + //(*Destroy(DataBreakpointDlg) + //*) +} + +bool DataBreakpointDlg::IsBreakpointEnabled() +{ + return m_enabled->IsChecked(); +} + +int DataBreakpointDlg::GetSelection() +{ + return m_condition->GetSelection(); +} + +wxString DataBreakpointDlg::GetDataExpression() const +{ + return CleanStringValue(m_dataExpression->GetValue()); +} diff --git a/pool/shard001/C++/0024229_main.cpp b/pool/shard001/C++/0024229_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c73c2985b3c4d60c54b60f65fcb7d85f31be2549 --- /dev/null +++ b/pool/shard001/C++/0024229_main.cpp @@ -0,0 +1,160 @@ +/* Makefile: +bad: + g++ main.cpp /usr/lib/liblapack.a /usr/lib/libblas.a -lgfortran -z muldefs -pthread +good: + g++ -DGOOD main.cpp /usr/lib/liblapack.a /usr/lib/libblas.a -lgfortran -z muldefs -pthread +*/ +/* Output I see: +$ make good +g++ -DGOOD main.cpp /usr/lib/liblapack.a /usr/lib/libblas.a -lgfortran -z muldefs -pthread +$ ./a.out +Info1,2 = 0,0 +-7050.245589,-8479.237956 +-8580.257527,-9209.117716 +-6301.087406,-6399.428666 +$ ./a.out +Info1,2 = 0,0 +-7050.245589,-8479.237956 +-8580.257527,-9209.117716 +-6301.087406,-6399.428666 +$ make bad +g++ main.cpp /usr/lib/liblapack.a /usr/lib/libblas.a -lgfortran -z muldefs -pthread +$ ./a.out +Info1,2 = 0,0 +-7050.355400,-8478.864949 +-8457.115555,-8501.374698 +1703.121368,-3150.274644 +$ ./a.out +Info1,2 = 0,0 +-7106.927073,-8501.507914 +-8580.257527,-9209.117716 +-6299.486160,-6398.683343 +*/ + +#include +#include +#include +#include +#include + +// Global pthreads stuff +pthread_mutex_t g_mutex = PTHREAD_MUTEX_INITIALIZER; +int count = 0; +pthread_cond_t g_cond = PTHREAD_COND_INITIALIZER; + +typedef std::complex complex_t; + +extern "C" float slamch_(const char *); +extern "C" double dlamch_(const char *); +void lapack_init(){ + slamch_("E"); + dlamch_("E"); +} + +struct thread_data{ + complex_t *A; + complex_t *q; + int n, info; +}; +extern "C" void zgeev_( + const char *jobvl, const char *jobvr, + const int &n, complex_t *a, const int &lda, + complex_t *w, + complex_t *vl, const int &ldvl, + complex_t *vr, const int &ldvr, + complex_t *work, const int &lwork, double *rwork, int *info); +void* thread_func(void *data){ + thread_data *T = (thread_data*)data; + const int n = T->n; + int lwork = 2*n; + + // Query workspace + lwork = -1; + zgeev_("N", "N", n, T->A, n, T->q, + NULL, 1, NULL, 1, T->q, lwork, NULL, &T->info); + lwork = (int)T->q[0].real(); + + complex_t *work = (complex_t*)malloc(sizeof(complex_t)*lwork); + double *rwork = (double*)malloc(sizeof(double)*2*n); + + volatile int t; + // Sync threads at this point + pthread_mutex_lock(&g_mutex); + ++count; + pthread_mutex_unlock(&g_mutex); + do{ + pthread_mutex_lock(&g_mutex); + t = count; + pthread_mutex_unlock(&g_mutex); + }while(t < 2); + +#ifdef GOOD + pthread_mutex_lock(&g_mutex); +#endif + zgeev_("N", "N", n, T->A, n, T->q, + NULL, 1, NULL, 1, work, lwork, rwork, &T->info); +#ifdef GOOD + pthread_mutex_unlock(&g_mutex); +#endif + + // Sync threads at this point + pthread_mutex_lock(&g_mutex); + ++count; + pthread_mutex_unlock(&g_mutex); + do{ + pthread_mutex_lock(&g_mutex); + t = count; + pthread_mutex_unlock(&g_mutex); + }while(t < 4); + + free(rwork); + free(work); + return NULL; +} + + +int main(int argc, char *argv[]){ + int n = 2*71; + + lapack_init(); + + pthread_t thread1, thread2; + thread_data data1, data2; + complex_t *A1, *A2, *q1, *q2; + + data1.n = n; + data2.n = n; + data1.A = (complex_t*)malloc(sizeof(complex_t)*n*n); + data2.A = (complex_t*)malloc(sizeof(complex_t)*n*n); + data1.q = (complex_t*)malloc(sizeof(complex_t)*n); + data2.q = (complex_t*)malloc(sizeof(complex_t)*n); + + // Load in data + FILE *fp; + fp = fopen("1.dat", "rb"); + fread(data1.A, n*n*sizeof(complex_t), 1, fp); + fclose(fp); + fp = fopen("1.dat", "rb"); + fread(data2.A, n*n*sizeof(complex_t), 1, fp); + fclose(fp); + + pthread_create(&thread1, NULL, thread_func, &data1); + pthread_create(&thread2, NULL, thread_func, &data2); + pthread_join(thread1, NULL); + pthread_join(thread2, NULL); + + printf("Info1,2 = %d,%d\n", (int)data1.info, (int)data2.info); + for(int i = 0; i < 3; ++i){ + complex_t q = data1.q[i]; + printf("%f,%f\n", q.real(), q.imag()); + } + + free(data1.A); + free(data2.A); + free(data1.q); + free(data2.q); + + return 0; +} + + diff --git a/pool/shard001/C++/0024230_ndn-rtt-mean-deviation.cc b/pool/shard001/C++/0024230_ndn-rtt-mean-deviation.cc new file mode 100644 index 0000000000000000000000000000000000000000..88cebaaef34d5ef90038b4aa0e80a8a21819a69c --- /dev/null +++ b/pool/shard001/C++/0024230_ndn-rtt-mean-deviation.cc @@ -0,0 +1,187 @@ +/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ +// +// Copyright (c) 2006 Georgia Tech Research Corporation +// (c) 2013 University of Arizona +// (c) 2013 University of California, Los Angeles +// +// 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: Rajib Bhattacharjea +// Cheng Yi +// Alexander Afanasyev +// + +// Georgia Tech Network Simulator - Round Trip Time Estimation Class +// George F. Riley. Georgia Tech, Spring 2002 + +#include "ndn-rtt-mean-deviation.h" +#include "ns3/simulator.h" +#include "ns3/double.h" +#include "ns3/integer.h" +#include "ns3/uinteger.h" +#include "ns3/log.h" + +NS_LOG_COMPONENT_DEFINE ("ndn.RttMeanDeviation"); + +namespace ns3 { +namespace ndn { + +//--------------------------------------------------------------------------------- +// A modified version of Mean-Deviation Estimator optimized for NDN packet delivery + +NS_OBJECT_ENSURE_REGISTERED (RttMeanDeviation); + +TypeId +RttMeanDeviation::GetTypeId (void) +{ + static TypeId tid = TypeId ("ns3::ndn::RttMeanDeviation") + .SetParent () + .AddConstructor () + .AddAttribute ("Gain", + "Gain used in estimating the RTT (smoothed RTT), must be 0 < Gain < 1", + DoubleValue (0.125), + MakeDoubleAccessor (&RttMeanDeviation::m_gain), + MakeDoubleChecker ()) + .AddAttribute ("Gain2", + "Gain2 used in estimating the RTT (variance), must be 0 < Gain2 < 1", + DoubleValue (0.25), + MakeDoubleAccessor (&RttMeanDeviation::m_gain2), + MakeDoubleChecker ()) + ; + return tid; +} + +RttMeanDeviation::RttMeanDeviation() : + m_variance (0) +{ + NS_LOG_FUNCTION (this); +} + +RttMeanDeviation::RttMeanDeviation (const RttMeanDeviation& c) + : RttEstimator (c), m_gain (c.m_gain), m_gain2 (c.m_gain2), m_variance (c.m_variance) +{ + NS_LOG_FUNCTION (this); +} + +TypeId +RttMeanDeviation::GetInstanceTypeId (void) const +{ + return GetTypeId (); +} + +void RttMeanDeviation::Measurement (Time m) +{ + NS_LOG_FUNCTION (this << m); + if (m_nSamples) + { // Not first + Time err (m - m_currentEstimatedRtt); + double gErr = err.ToDouble (Time::S) * m_gain; + m_currentEstimatedRtt += Time::FromDouble (gErr, Time::S); + Time difference = Abs (err) - m_variance; + NS_LOG_DEBUG ("m_variance += " << Time::FromDouble (difference.ToDouble (Time::S) * m_gain2, Time::S)); + m_variance += Time::FromDouble (difference.ToDouble (Time::S) * m_gain2, Time::S); + } + else + { // First sample + m_currentEstimatedRtt = m; // Set estimate to current + //variance = sample / 2; // And variance to current / 2 + // m_variance = m; // try this why???? + m_variance = Seconds (m.ToDouble (Time::S) / 2); + NS_LOG_DEBUG ("(first sample) m_variance += " << m); + } + m_nSamples++; +} + +Time RttMeanDeviation::RetransmitTimeout () +{ + NS_LOG_FUNCTION (this); + + double retval = std::min (m_maxRto.ToDouble (Time::S), + std::max (m_multiplier*m_minRto.ToDouble (Time::S), + m_multiplier*(m_currentEstimatedRtt.ToDouble (Time::S) + 4 * m_variance.ToDouble (Time::S)))); + + NS_LOG_DEBUG ("RetransmitTimeout: return " << retval); + + return Seconds (retval); +} + +Ptr RttMeanDeviation::Copy () const +{ + NS_LOG_FUNCTION (this); + return CopyObject (this); +} + +void RttMeanDeviation::Reset () +{ + NS_LOG_FUNCTION (this); + // Reset to initial state + m_variance = Seconds (0); + RttEstimator::Reset (); +} + +void RttMeanDeviation::Gain (double g) +{ + NS_LOG_FUNCTION (this); + NS_ASSERT_MSG( (g > 0) && (g < 1), "RttMeanDeviation: Gain must be less than 1 and greater than 0" ); + m_gain = g; +} + +void RttMeanDeviation::SentSeq (SequenceNumber32 seq, uint32_t size) +{ + NS_LOG_FUNCTION (this << seq << size); + + RttHistory_t::iterator i; + for (i = m_history.begin (); i != m_history.end (); ++i) + { + if (seq == i->seq) + { // Found it + i->retx = true; + break; + } + } + + // Note that a particular sequence has been sent + if (i == m_history.end()) + m_history.push_back (RttHistory (seq, size, Simulator::Now () )); +} + +Time RttMeanDeviation::AckSeq (SequenceNumber32 ackSeq) +{ + NS_LOG_FUNCTION (this << ackSeq); + // An ack has been received, calculate rtt and log this measurement + // Note we use a linear search (O(n)) for this since for the common + // case the ack'ed packet will be at the head of the list + Time m = Seconds (0.0); + if (m_history.size () == 0) return (m); // No pending history, just exit + + for (RttHistory_t::iterator i = m_history.begin (); i != m_history.end (); ++i) + { + if (ackSeq == i->seq) + { // Found it + if (!i->retx) { + m = Simulator::Now () - i->time;// Elapsed time + Measurement (m); // Log the measurement + ResetMultiplier (); // Reset multiplier on valid measurement + } + m_history.erase(i); + break; + } + } + + return m; +} + +} // namespace ndn +} // namespace ns3 + diff --git a/pool/shard001/C++/0024237_WebSoupRequestManager.cpp b/pool/shard001/C++/0024237_WebSoupRequestManager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7406d685e1ac2a57ec02dfd73937550903bed357 --- /dev/null +++ b/pool/shard001/C++/0024237_WebSoupRequestManager.cpp @@ -0,0 +1,188 @@ +/* + * Copyright (C) 2012 Igalia S.L. + * + * 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" +#include "WebSoupRequestManager.h" + +#include "DataReference.h" +#include "MessageID.h" +#include "WebErrors.h" +#include "WebKitSoupRequestGeneric.h" +#include "WebKitSoupRequestInputStream.h" +#include "WebPageProxyMessages.h" +#include "WebProcess.h" +#include "WebSoupRequestManagerProxyMessages.h" +#include +#include +#include +#include +#include + +namespace WebKit { + +static uint64_t generateSoupRequestID() +{ + static uint64_t uniqueSoupRequestID = 1; + return uniqueSoupRequestID++; +} + +struct WebSoupRequestAsyncData { + WebSoupRequestAsyncData(GSimpleAsyncResult* result, WebKitSoupRequestGeneric* requestGeneric, GCancellable* cancellable) + : result(result) + , request(requestGeneric) + , cancellable(cancellable) + { + // If the struct contains a null request, it is because the request failed. + g_object_add_weak_pointer(G_OBJECT(request), reinterpret_cast(&request)); + } + + ~WebSoupRequestAsyncData() + { + if (request) + g_object_remove_weak_pointer(G_OBJECT(request), reinterpret_cast(&request)); + } + + bool requestFailed() + { + return g_cancellable_is_cancelled(cancellable.get()) || !request; + } + + GRefPtr releaseResult() + { + GSimpleAsyncResult* returnValue = result; + result = 0; + return adoptGRef(returnValue); + } + + GSimpleAsyncResult* result; + WebKitSoupRequestGeneric* request; + GRefPtr cancellable; + GRefPtr stream; +}; + +WebSoupRequestManager::WebSoupRequestManager(WebProcess* process) + : m_process(process) + , m_schemes(adoptGRef(g_ptr_array_new_with_free_func(g_free))) +{ +} + +WebSoupRequestManager::~WebSoupRequestManager() +{ +} + +void WebSoupRequestManager::didReceiveMessage(CoreIPC::Connection* connection, CoreIPC::MessageID messageID, CoreIPC::ArgumentDecoder* arguments) +{ + didReceiveWebSoupRequestManagerMessage(connection, messageID, arguments); +} + +void WebSoupRequestManager::registerURIScheme(const String& scheme) +{ + if (m_schemes->len) + g_ptr_array_remove_index_fast(m_schemes.get(), m_schemes->len - 1); + g_ptr_array_add(m_schemes.get(), g_strdup(scheme.utf8().data())); + g_ptr_array_add(m_schemes.get(), 0); + + SoupSession* session = WebCore::ResourceHandle::defaultSession(); + GRefPtr requester = SOUP_REQUESTER(soup_session_get_feature(session, SOUP_TYPE_REQUESTER)); + if (requester) + soup_session_feature_remove_feature(SOUP_SESSION_FEATURE(requester.get()), WEBKIT_TYPE_SOUP_REQUEST_GENERIC); + else { + requester = adoptGRef(soup_requester_new()); + soup_session_add_feature(session, SOUP_SESSION_FEATURE(requester.get())); + } + SoupRequestClass* genericRequestClass = static_cast(g_type_class_ref(WEBKIT_TYPE_SOUP_REQUEST_GENERIC)); + genericRequestClass->schemes = const_cast(reinterpret_cast(m_schemes->pdata)); + soup_session_feature_add_feature(SOUP_SESSION_FEATURE(requester.get()), WEBKIT_TYPE_SOUP_REQUEST_GENERIC); +} + +void WebSoupRequestManager::didHandleURIRequest(const CoreIPC::DataReference& requestData, uint64_t contentLength, const String& mimeType, uint64_t requestID) +{ + WebSoupRequestAsyncData* data = m_requestMap.get(requestID); + ASSERT(data); + GRefPtr result = data->releaseResult(); + ASSERT(result.get()); + + GRefPtr request = adoptGRef(WEBKIT_SOUP_REQUEST_GENERIC(g_async_result_get_source_object(G_ASYNC_RESULT(result.get())))); + webkitSoupRequestGenericSetContentLength(request.get(), contentLength ? contentLength : -1); + webkitSoupRequestGenericSetContentType(request.get(), !mimeType.isEmpty() ? mimeType.utf8().data() : 0); + + GInputStream* dataStream; + if (!requestData.size()) { + // Empty reply, just create and empty GMemoryInputStream. + dataStream = g_memory_input_stream_new(); + m_requestMap.remove(requestID); + } else if (requestData.size() == contentLength) { + // We don't expect more data, so we can just create a GMemoryInputStream with all the data. + dataStream = g_memory_input_stream_new_from_data(g_memdup(requestData.data(), requestData.size()), contentLength, g_free); + m_requestMap.remove(requestID); + } else { + // We expect more data chunks from the UI process. + dataStream = webkitSoupRequestInputStreamNew(contentLength); + data->stream = dataStream; + webkitSoupRequestInputStreamAddData(WEBKIT_SOUP_REQUEST_INPUT_STREAM(dataStream), requestData.data(), requestData.size()); + } + g_simple_async_result_set_op_res_gpointer(result.get(), dataStream, g_object_unref); + g_simple_async_result_complete(result.get()); +} + +void WebSoupRequestManager::didReceiveURIRequestData(const CoreIPC::DataReference& requestData, uint64_t requestID) +{ + WebSoupRequestAsyncData* data = m_requestMap.get(requestID); + // The data might have been removed from the request map if a previous chunk failed + // and a new message was sent by the UI process before being notified about the failure. + if (!data) + return; + ASSERT(data->stream.get()); + + if (data->requestFailed()) { + // ResourceRequest failed or it was cancelled. It doesn't matter here the error or if it was cancelled, + // because that's already handled by the resource handle client, we just want to notify the UI process + // to stop reading data from the user input stream. If UI process already sent all the data we simply + // finish silently. + if (!webkitSoupRequestInputStreamFinished(WEBKIT_SOUP_REQUEST_INPUT_STREAM(data->stream.get()))) + m_process->connection()->send(Messages::WebSoupRequestManagerProxy::DidFailToLoadURIRequest(requestID), 0); + m_requestMap.remove(requestID); + + return; + } + + webkitSoupRequestInputStreamAddData(WEBKIT_SOUP_REQUEST_INPUT_STREAM(data->stream.get()), requestData.data(), requestData.size()); + if (webkitSoupRequestInputStreamFinished(WEBKIT_SOUP_REQUEST_INPUT_STREAM(data->stream.get()))) + m_requestMap.remove(requestID); +} + +void WebSoupRequestManager::send(GSimpleAsyncResult* result, GCancellable* cancellable) +{ + GRefPtr request = adoptGRef(WEBKIT_SOUP_REQUEST_GENERIC(g_async_result_get_source_object(G_ASYNC_RESULT(result)))); + SoupRequest* soupRequest = SOUP_REQUEST(request.get()); + GOwnPtr uriString(soup_uri_to_string(soup_request_get_uri(soupRequest), FALSE)); + + uint64_t requestID = generateSoupRequestID(); + m_requestMap.set(requestID, adoptPtr(new WebSoupRequestAsyncData(result, request.get(), cancellable))); + + uint64_t initiaingPageID = WebCore::ResourceHandle::getSoupRequestInitiaingPageID(soupRequest); + m_process->connection()->send(Messages::WebPageProxy::DidReceiveURIRequest(String::fromUTF8(uriString.get()), requestID), initiaingPageID); +} + +GInputStream* WebSoupRequestManager::finish(GSimpleAsyncResult* result) +{ + return G_INPUT_STREAM(g_object_ref(g_simple_async_result_get_op_res_gpointer(result))); +} + +} // namespace WebKit diff --git a/pool/shard001/C++/0024249_SphereUtils.cpp b/pool/shard001/C++/0024249_SphereUtils.cpp new file mode 100644 index 0000000000000000000000000000000000000000..211bb5e1596ff94d7fe0f8cfb3e51fa9099d6620 --- /dev/null +++ b/pool/shard001/C++/0024249_SphereUtils.cpp @@ -0,0 +1,102 @@ +/** + * + * This file is part of Tulip (www.tulip-software.org) + * + * Authors: David Auber and the Tulip development Team + * from LaBRI, University of Bordeaux + * + * Tulip 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. + * + * Tulip 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 "SphereUtils.h" + +#include +#include +#include + +#include + +using namespace tlp; +using namespace std; + +float centerOnOriginAndScale(Graph* graph, LayoutProperty * layout, float dist) { + graph->getProperty("viewSize")->setAllNodeValue(Size(0,0,0)); + BoundingBox bb = tlp::computeBoundingBox(graph, graph->getProperty("viewLayout"), graph->getProperty("viewSize"), graph->getProperty("viewRotation"), 0); + Coord move_coord = Coord((bb[0] + bb[1])) / (-2.f); + layout->translate(move_coord, graph); + float ray = (move_coord - bb[1]).norm(); + float scaleFactor = dist / ray; + layout->scale(Coord(scaleFactor, scaleFactor, scaleFactor), graph); + graph->getProperty("viewSize")->setAllNodeValue(Size(0.1f, 0.1f, 0.1f)); + return sqrt( ray*ray / 2.); +} + +void moveBendsToSphere(Graph *graph, float ray, LayoutProperty * layout) { + edge e; + forEach(e, graph->getEdges()) { + vector bends; + bends = layout->getEdgeValue(e); + + for(size_t i = 0 ; i < bends.size(); ++i) { + Coord c = bends[i]; + double dist = c.norm(); + c /= dist; + c *= ray; + bends[i] = c; + } + + layout->setEdgeValue(e, bends); + } + + node n; + forEach(n, graph->getNodes()) { + Coord c= layout->getNodeValue(n); + c /= c.norm(); + c *= ray; + layout->setNodeValue(n, c); + } +} + +static Coord getCoordFromPolar(double rayon, double a1, double a2) { + a1 = a1 * M_PI /2. / 90.; + a2 = a2 * M_PI /2. / 90.; + float x, y, z; + x = rayon * cos(a1) * sin(a2); + y = rayon * sin(a1) * sin(a2); + z = rayon * cos(a2); + return Coord(x,y,z); +} + +void addSphereGraph(Graph *graph, double radius) { + LayoutProperty * layout = graph->getProperty("viewLayout"); + double rho = 0; + + while( rho < 360 ) { + double teta = 5; + + while( teta < 180) { + node n = graph->addNode(); + Coord c = getCoordFromPolar(radius, rho, teta); + layout->setNodeValue(n, c); + teta += 5.; + } + + rho += 5.; + } + + node n = graph->addNode(); + Coord c = getCoordFromPolar(radius, 0, 0); + layout->setNodeValue(n, c); + n = graph->addNode(); + c = getCoordFromPolar(radius, 0, 180); + layout->setNodeValue(n, c); +} diff --git a/pool/shard001/C++/0024257_reachable-nodes-in-subdivided-graph.cpp b/pool/shard001/C++/0024257_reachable-nodes-in-subdivided-graph.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f5814888b3be5d0321c3c04419a7132ffdd6175f --- /dev/null +++ b/pool/shard001/C++/0024257_reachable-nodes-in-subdivided-graph.cpp @@ -0,0 +1,46 @@ +// Time: O((|E| + |V|) * log|V|) = O(|E| * log|V|), +// if we can further to use Fibonacci heap, it would be O(|E| + |V| * log|V|) +// Space: O(|E| + |V|) = O(|E|) + +class Solution { +public: + int reachableNodes(vector>& edges, int M, int N) { + using P = pair; + vector> adj(N); + for (const auto& edge: edges) { + int u = edge[0], v = edge[1], w = edge[2]; + adj[u].emplace_back(v, w); + adj[v].emplace_back(u, w); + } + unordered_map best; + best[0] = 0; + unordered_map> count; + int result = 0; + priority_queue, greater

> min_heap; + min_heap.emplace(0, 0); + while (!min_heap.empty()) { + int curr_total, u; + tie(curr_total, u) = min_heap.top(); min_heap.pop(); + if (best.count(u) && best[u] < curr_total) { + continue; + } + ++result; + for (const auto& kvp: adj[u]) { + int v, w; + tie(v, w) = kvp; + count[u][v] = min(w, M - curr_total); + int next_total = curr_total + w + 1; + if (next_total <= M && + (!best.count(v) || next_total < best[v])) { + best[v] = next_total; + min_heap.emplace(next_total, v); + } + } + } + for (const auto& edge: edges) { + int u = edge[0], v = edge[1], w = edge[2]; + result += min(w, count[u][v] + count[v][u]); + } + return result; + } +}; diff --git a/pool/shard001/C++/0024261_IRBuilder.cpp b/pool/shard001/C++/0024261_IRBuilder.cpp new file mode 100644 index 0000000000000000000000000000000000000000..595dea470bc32c949d4b5e60907980c6be779e24 --- /dev/null +++ b/pool/shard001/C++/0024261_IRBuilder.cpp @@ -0,0 +1,119 @@ +//===---- IRBuilder.cpp - Builder for LLVM Instrs -------------------------===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +// +// This file implements the IRBuilder class, which is used as a convenient way +// to create LLVM instructions with a consistent and simplified interface. +// +//===----------------------------------------------------------------------===// + +#include "llvm/Support/IRBuilder.h" +#include "llvm/GlobalVariable.h" +#include "llvm/Function.h" +#include "llvm/Intrinsics.h" +#include "llvm/LLVMContext.h" +using namespace llvm; + +/// CreateGlobalString - Make a new global variable with an initializer that +/// has array of i8 type filled in with the nul terminated string value +/// specified. If Name is specified, it is the name of the global variable +/// created. +Value *IRBuilderBase::CreateGlobalString(const char *Str, const Twine &Name) { + Constant *StrConstant = ConstantArray::get(Context, Str, true); + Module &M = *BB->getParent()->getParent(); + GlobalVariable *GV = new GlobalVariable(M, StrConstant->getType(), + true, GlobalValue::InternalLinkage, + StrConstant, "", 0, false); + GV->setName(Name); + return GV; +} + +const Type *IRBuilderBase::getCurrentFunctionReturnType() const { + assert(BB && BB->getParent() && "No current function!"); + return BB->getParent()->getReturnType(); +} + +Value *IRBuilderBase::getCastedInt8PtrValue(Value *Ptr) { + const PointerType *PT = cast(Ptr->getType()); + if (PT->getElementType()->isIntegerTy(8)) + return Ptr; + + // Otherwise, we need to insert a bitcast. + PT = getInt8PtrTy(PT->getAddressSpace()); + BitCastInst *BCI = new BitCastInst(Ptr, PT, ""); + BB->getInstList().insert(InsertPt, BCI); + SetInstDebugLocation(BCI); + return BCI; +} + +static CallInst *createCallHelper(Value *Callee, Value *const* Ops, + unsigned NumOps, IRBuilderBase *Builder) { + CallInst *CI = CallInst::Create(Callee, Ops, Ops + NumOps, ""); + Builder->GetInsertBlock()->getInstList().insert(Builder->GetInsertPoint(),CI); + Builder->SetInstDebugLocation(CI); + return CI; +} + + +CallInst *IRBuilderBase:: +CreateMemSet(Value *Ptr, Value *Val, Value *Size, unsigned Align, + bool isVolatile, MDNode *TBAATag) { + Ptr = getCastedInt8PtrValue(Ptr); + Value *Ops[] = { Ptr, Val, Size, getInt32(Align), getInt1(isVolatile) }; + const Type *Tys[] = { Ptr->getType(), Size->getType() }; + Module *M = BB->getParent()->getParent(); + Value *TheFn = Intrinsic::getDeclaration(M, Intrinsic::memset, Tys, 2); + + CallInst *CI = createCallHelper(TheFn, Ops, 5, this); + + // Set the TBAA info if present. + if (TBAATag) + CI->setMetadata(LLVMContext::MD_tbaa, TBAATag); + + return CI; +} + +CallInst *IRBuilderBase:: +CreateMemCpy(Value *Dst, Value *Src, Value *Size, unsigned Align, + bool isVolatile, MDNode *TBAATag) { + Dst = getCastedInt8PtrValue(Dst); + Src = getCastedInt8PtrValue(Src); + + Value *Ops[] = { Dst, Src, Size, getInt32(Align), getInt1(isVolatile) }; + const Type *Tys[] = { Dst->getType(), Src->getType(), Size->getType() }; + Module *M = BB->getParent()->getParent(); + Value *TheFn = Intrinsic::getDeclaration(M, Intrinsic::memcpy, Tys, 3); + + CallInst *CI = createCallHelper(TheFn, Ops, 5, this); + + // Set the TBAA info if present. + if (TBAATag) + CI->setMetadata(LLVMContext::MD_tbaa, TBAATag); + + return CI; +} + +CallInst *IRBuilderBase:: +CreateMemMove(Value *Dst, Value *Src, Value *Size, unsigned Align, + bool isVolatile, MDNode *TBAATag) { + Dst = getCastedInt8PtrValue(Dst); + Src = getCastedInt8PtrValue(Src); + + Value *Ops[] = { Dst, Src, Size, getInt32(Align), getInt1(isVolatile) }; + const Type *Tys[] = { Dst->getType(), Src->getType(), Size->getType() }; + Module *M = BB->getParent()->getParent(); + Value *TheFn = Intrinsic::getDeclaration(M, Intrinsic::memmove, Tys, 3); + + CallInst *CI = createCallHelper(TheFn, Ops, 5, this); + + // Set the TBAA info if present. + if (TBAATag) + CI->setMetadata(LLVMContext::MD_tbaa, TBAATag); + + return CI; +} diff --git a/pool/shard001/C++/0024262_binders.cpp b/pool/shard001/C++/0024262_binders.cpp new file mode 100644 index 0000000000000000000000000000000000000000..429efed945b35b4adf618c31e74a3d91ed8bd4e8 --- /dev/null +++ b/pool/shard001/C++/0024262_binders.cpp @@ -0,0 +1,86 @@ +/************************************************************************** + * + * binders.cpp - Example program for binder1st & binder2nd. + * + * $Id$ + * + *************************************************************************** + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + * implied. See the License for the specific language governing + * permissions and limitations under the License. + * + * Copyright 1994-2006 Rogue Wave Software, Inc. + * + **************************************************************************/ + +#include // for find_if +#include // for equal_to, bind1st, bind2nd +#include // for cout +#include // for ostream_iterator +#include // for vector + +#include + + +int main () +{ + typedef std::vector Vector; + typedef std::equal_to EqualTo; + + const Vector::value_type arr [] = { 1, 2, 3, 4, 5 }; + + // Initialize a vector with the array elements. + const Vector v1 (arr, arr + sizeof arr / sizeof *arr); + + // Value to look for. + const Vector::value_type x (3); + + // Create an 'equal to 3' unary predicate by binding the value + // 3 to the EqualTo binary predicate. + const std::binder1st equal_to_3 (std::bind1st (EqualTo (), x)); + + // Now use this new predicate in a call to find_if. + const Vector::const_iterator it1 = + std::find_if (v1.begin (), v1.end (), equal_to_3); + + // Even better, construct the new predicate on the fly. + const Vector::const_iterator it2 = + std::find_if (v1.begin (), v1.end (), std::bind1st (EqualTo (), x)); + + // And now the same thing using bind2nd. + // Same result since EqualTo is commutative. + const Vector::const_iterator it3 = + std::find_if (v1.begin (), v1.end (), std::bind2nd (EqualTo (), x)); + + // Use the same predicate to count the number of elements + // equal to 3. + const Vector::size_type n = + std::count_if (v1.begin (), v1.end (), std::bind2nd (EqualTo (), x)); + + // Output results. + std::ostream_iterator out (std::cout, " "); + + std::cout << "The vector { "; + std::copy (v1.begin (), v1.end (), out); + + std::cout << "} contains " << n << " element equal to " << x + << " at offset " << it1 - v1.begin () << ".\n"; + + // Exit with status of 0 on success, 1 on failure. + const bool success = 1 == n && it1 == it2 && it1 == it2 && *it1 == x; + + return success ? 0 : 1; +} diff --git a/pool/shard001/C++/0024265_notification_node.cpp b/pool/shard001/C++/0024265_notification_node.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3bf55c3989c0ba4bf0b4b695ac60afbf6516d3ef --- /dev/null +++ b/pool/shard001/C++/0024265_notification_node.cpp @@ -0,0 +1,68 @@ +#include "notification_node.h" +#include +#include + +#include "../db/notification.h" +#include "../util/log.h" + +using std::string; + +using rocksdb::Status; + +NotificationNode::NotificationNode() : WAMethodAuthNode("notification") { +} + +void NotificationNode::executeGet(MgConnection& conn, const char*){ + string loggedUser = conn.getParameter("logged_user"); + + auto it = Notification::NewIterator(); + + if(conn.getHeader("Accept") != NULL && strcmp("text/event-stream", conn.getHeader("Accept")) == 0){ + conn.setParameter("sse", "yes"); + if(conn.getHeader("Last-Event-ID") != NULL){ + string lastId = conn.getHeader("Last-Event-ID"); + Notification::DeleteUpTo(loggedUser, lastId); + } + + conn.sendStatus(MgConnection::STATUS_CODE_OK); + conn.sendContentType(MgConnection::CONTENT_TYPE_EVENT_STREAM); + for(it.seek(loggedUser); it.valid(); it.next()) + conn.printfData("id: %s\ndata: %s\n\n", it.value().getId().c_str(), it.value().toJson().c_str()); + + conn.setResponse(MG_MORE); + return; + } + + conn.sendStatus(MgConnection::STATUS_CODE_OK); + conn.sendContentType(MgConnection::CONTENT_TYPE_JSON); + conn.printfData("{\"notifications\":["); + + it.seek(loggedUser); + for(int counter = 0; it.valid(); it.next(), counter++) + conn.printfData("%s%s", counter == 0 ? "" : ",", it.value().toJson().c_str()); + + conn.printfData("]}"); +} + +void NotificationNode::executeDelete(MgConnection& conn, const char*){ + string loggedUser = conn.getParameter("logged_user"); + string lastId = conn.getVarStr("id"); + if(lastId.size() < sizeof(uint64_t) * 2){ // TODO: este control lo deberia hacer messages! + conn.sendStatus(MgConnection::STATUS_CODE_BAD_REQUEST); + conn.sendContentType(MgConnection::CONTENT_TYPE_JSON); + conn.printfData("{ \"message\": \"Id invalida\", \"code\":%d, \"error_user_msg\":\"Id invalida\"}", MgConnection::STATUS_CODE_BAD_REQUEST); + return; + } + + Status s = Notification::DeleteUpTo(loggedUser, lastId); + if(!s.ok()){ + conn.sendStatus(MgConnection::STATUS_CODE_INTERNAL_ERROR); + conn.sendContentType(MgConnection::CONTENT_TYPE_JSON); + conn.printfData("{ \"message\": \"Error de db %s\", \"code\":%d, \"error_user_msg\":\"Ups.. No se pudo completar, por favor intenta mas tarde\"}", MgConnection::STATUS_CODE_INTERNAL_ERROR); + return; + } + + conn.sendStatus(MgConnection::STATUS_CODE_OK); + conn.sendContentType(MgConnection::CONTENT_TYPE_JSON); + conn.printfData("{ \"success\": \"true\"}"); +} diff --git a/pool/shard001/C++/0024270_CMesh.cpp b/pool/shard001/C++/0024270_CMesh.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d9901b4a2a4c2f6a4279fadf7a0c3194359e37e7 --- /dev/null +++ b/pool/shard001/C++/0024270_CMesh.cpp @@ -0,0 +1,57 @@ +/* + Copyright 2012 Thomas Le Guerroué-Drévillon + This file is part of lemonGL. + + lemonGL 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. + + lemonGL 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 lemonGL. If not, see . +*/ + +#include "CMesh.h" + +CMesh::CMesh() +{ + +} + +CMesh::CMesh(const QString& p_group): +m_group(p_group) +{ + +} + +CMesh::CMesh(const CMesh& p_mesh): +CObject(p_mesh), +m_group(p_mesh.m_group), +m_faces(p_mesh.m_faces) +{ + +} + +void CMesh::addFace(CFace* p_face){ + m_faces.push_back(p_face); + m_order.push_back(m_order.size()); +} + +void CMesh::free(){ + for(int a = 0; a < m_faces.size(); a++) + delete m_faces[a]; +} + +bool CMesh::operator==(const QString& p_group){ + return (m_group == p_group); +} + +void CMesh::drawSub(){ + for(int a = 0; a < m_faces.size(); a++) + m_faces[a]->draw(); +} diff --git a/pool/shard001/C++/0024283_MiniModeWnd.cpp b/pool/shard001/C++/0024283_MiniModeWnd.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6a403e89c2a37c7f57641aefea25cd66b2674fb7 --- /dev/null +++ b/pool/shard001/C++/0024283_MiniModeWnd.cpp @@ -0,0 +1,125 @@ +#include"StdAfx.h" +#include "MiniModeWnd.h" + + +CMiniModeWnd::CMiniModeWnd() +: m_strTransSelect(_T("")) +{ +} + +CMiniModeWnd::~CMiniModeWnd() +{ +} + +UILIB_RESOURCETYPE CMiniModeWnd::GetResourceType() const +{ + return UILIB_FILE; +} + +LPCTSTR CMiniModeWnd::GetWindowClassName() const +{ + return _T("YDMiniModeWnd"); +} + +void CMiniModeWnd::OnFinalMessage(HWND hWnd) +{ + WindowImplBase::OnFinalMessage(hWnd); + delete this; +} + +void CMiniModeWnd::InitWindow() +{ + +} + +CDuiString CMiniModeWnd::GetSkinFile() +{ + TCHAR szBuf[MAX_PATH] = _T("YDMiniModeWnd.xml"); + return szBuf; +} + +CDuiString CMiniModeWnd::GetSkinFolder() +{ + return _T(""); +} + + +CControlUI* CMiniModeWnd::CreateControl(LPCTSTR pstrClass) +{ + return NULL; +} + +LRESULT CMiniModeWnd::HandleMessage(UINT uMsg, WPARAM wParam, LPARAM lParam) +{ + switch (uMsg) + { + default: + break; + } + return __super::HandleMessage(uMsg, wParam, lParam); +} + +LRESULT CMiniModeWnd::HandleCustomMessage(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled) +{ + return 0; +} + + +void CMiniModeWnd::Notify(TNotifyUI& msg) +{ + if (_tcsicmp(msg.sType, _T("click")) == 0) + { + OnClick(msg.pSender); + } +} + +void CMiniModeWnd::OnClick(CControlUI* pSender) +{ + if (_tcsicmp(pSender->GetName(), _T("TransSelectButton1")) == 0) + { + ::SendMessage(m_hMianWnd, WM_USER_TRANS_STRING_CHANGED, 1, 0); + } + else if (_tcsicmp(pSender->GetName(), _T("BtnMiniClose")) == 0) + { + //Ö»Òþ²Ø²»Close + ::ShowWindow(this->m_hWnd,SW_HIDE); + //Close(); + } + else if (_tcsicmp(pSender->GetName(), _T("BtnMiniQcsprig")) == 0) + { + CButtonUI *pBtnMiniQcsprig = static_cast(m_PaintManager.FindControl(_T("BtnMiniQcsprig"))); + CButtonUI *pBtnMiniQcfix = static_cast(m_PaintManager.FindControl(_T("BtnMiniQcfix"))); + pBtnMiniQcsprig->SetVisible(FALSE); + pBtnMiniQcfix->SetVisible(TRUE); + } + else if (_tcsicmp(pSender->GetName(), _T("BtnMiniQcfix")) == 0) + { + CButtonUI *pBtnMiniQcsprig = static_cast(m_PaintManager.FindControl(_T("BtnMiniQcsprig"))); + CButtonUI *pBtnMiniQcfix = static_cast(m_PaintManager.FindControl(_T("BtnMiniQcfix"))); + pBtnMiniQcsprig->SetVisible(TRUE); + pBtnMiniQcfix->SetVisible(FALSE); + } +} +void CMiniModeWnd::OnPrepare(TNotifyUI& msg) +{ + +} +void CMiniModeWnd::OnExit(TNotifyUI& msg) +{ + Close(); +} + +void CMiniModeWnd::OnTimer(TNotifyUI& msg) +{ + +} + +void CMiniModeWnd::SetMainWnd(HWND hWnd) +{ + m_hMianWnd = hWnd; +} + +void CMiniModeWnd::HideWindow() +{ + ::ShowWindow(this->m_hWnd,SW_HIDE); +} \ No newline at end of file diff --git a/pool/shard001/C++/0024291_OgitorsScriptInterpreter.cpp b/pool/shard001/C++/0024291_OgitorsScriptInterpreter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d207a34f5aae756349df3fffba94b5dfa006e5ad --- /dev/null +++ b/pool/shard001/C++/0024291_OgitorsScriptInterpreter.cpp @@ -0,0 +1,70 @@ +/*///////////////////////////////////////////////////////////////////////////////// +/// An +/// ___ ____ ___ _____ ___ ____ +/// / _ \ / ___|_ _|_ _/ _ \| _ \ +/// | | | | | _ | | | || | | | |_) | +/// | |_| | |_| || | | || |_| | _ < +/// \___/ \____|___| |_| \___/|_| \_\ +/// File +/// +/// Copyright (c) 2008-2011 Ismail TARIM and the Ogitor Team +// +/// The MIT License +/// +/// 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 "OgitorsPrerequisites.h" +#include "OgitorsRoot.h" +#include "OgitorsSystem.h" +#include "OgitorsScriptInterpreter.h" + +namespace Ogitors +{ + float OgitorsScriptInterpreter::mTimeSinceLastFrame = 0.0f; + + OgitorsScriptInterpreter::OgitorsScriptInterpreter() + { + mOgitorsRoot = OgitorsRoot::getSingletonPtr(); + mSystem = OgitorsSystem::getSingletonPtr(); + mInitialized = false; + } + + OgitorsScriptInterpreter::~OgitorsScriptInterpreter() + { + mInitialized = false; + mOgitorsRoot = 0; + mSystem = 0; + } + + unsigned int OgitorsScriptInterpreter::getOutput(unsigned int start, OutputDataVector& list) + { + list.clear(); + + OGRE_LOCK_AUTO_MUTEX + + for(unsigned int i = start;i < mBuffer.size();i++) + { + list.push_back(mBuffer[i]); + } + + return mBuffer.size(); + } + +} diff --git a/pool/shard001/C++/0024292_interproc4.cpp b/pool/shard001/C++/0024292_interproc4.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f1e08d3b684c3ecdae5d7f4d52c1e7e25f9b29b5 --- /dev/null +++ b/pool/shard001/C++/0024292_interproc4.cpp @@ -0,0 +1,36 @@ +#include "record.h" +#include +using namespace std; +using namespace record; + +int loopFunction(int _reserved_input_[]) { + int i = _reserved_input_[0]; + int j = _reserved_input_[1]; + + if (i < 0) i = -i; if (j < 0) j = -j; if (i == 0) i = 1; if (j == 0) j = 1; + precondition( i * i < j * j); + + while( i < j) { + record_variable_int(i, j); + + if (j-i +#include +#include + +extern "C" int LLVMFuzzerTestOneInput(uint8_t *buf, size_t len) { + CBS cbs; + CBS_init(&cbs, buf, len); + EVP_PKEY *pkey = EVP_parse_public_key(&cbs); + if (pkey == NULL) { + return 0; + } + + uint8_t *der; + size_t der_len; + CBB cbb; + if (CBB_init(&cbb, 0) && + EVP_marshal_public_key(&cbb, pkey) && + CBB_finish(&cbb, &der, &der_len)) { + OPENSSL_free(der); + } + CBB_cleanup(&cbb); + EVP_PKEY_free(pkey); + return 0; +} diff --git a/pool/shard001/C++/0024310_error_estimator_02.cc b/pool/shard001/C++/0024310_error_estimator_02.cc new file mode 100644 index 0000000000000000000000000000000000000000..91953225f72cce387b4ee238de3648e499b62963 --- /dev/null +++ b/pool/shard001/C++/0024310_error_estimator_02.cc @@ -0,0 +1,198 @@ +// --------------------------------------------------------------------- +// +// Copyright (C) 2004 - 2016 by the deal.II authors +// +// This file is part of the deal.II library. +// +// The deal.II library is free software; you can use it, redistribute +// it, and/or modify it under the terms of the GNU Lesser General +// Public License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// The full text of the license can be found in the file LICENSE at +// the top level of the deal.II distribution. +// +// --------------------------------------------------------------------- + + +// check that the kelly error estimator uses correct normals on surfaces +// with kinks by interpolating a function that is inside the FE space +// and should produce zero errors. + + + +#include "../tests.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +// function is x^2+2xy +template +class MyFunction : public Function +{ +public: + MyFunction () : Function(1) {} + + virtual double value (const Point &p, + const unsigned int component) const + { + return p(0)*p(0)+2.0*p(0)*p(1); + } + + virtual void vector_value (const Point &p, + Vector &values) const + { + values(0) = value(p,0); + } +}; + + +// normal derivative of function above is 0 except for x=1, y=1 with n=(0,1,0) +template +class MyNormalDerivative : public Function +{ +public: + MyNormalDerivative () : Function(1) {} + + virtual double value (const Point &p, + const unsigned int component) const + { + double val = 0.0; + if (std::abs(p(1)-1.0)<1e-5) + val = 2.0; + + deallog << "evaluate normal derivative at " << p << " with value " << val << std::endl; + return val; + } + + virtual void vector_value (const Point &p, + Vector &values) const + { + values(0) = value(p,0); + } +}; + + + +template +Quadrature & +get_q_face () +{ + static QGauss q(4); + return q; +} + +template <> +Quadrature<0> & +get_q_face <1>() +{ + Quadrature<0> *q = nullptr; + return *q; +} + +template +void make_mesh (Triangulation &tria) +{ + // two faces of a hyper_cube + Triangulation volume_mesh; + GridGenerator::hyper_cube(volume_mesh, 0, 1, true); + std::set boundary_ids; + boundary_ids.insert (1); + boundary_ids.insert (2); + GridGenerator::extract_boundary_mesh (volume_mesh, tria, + boundary_ids); + tria.refine_global (2); + typename Triangulation::active_cell_iterator + cell = tria.begin_active(); + for (; cell != tria.end(); ++cell) + if (cell->center()[1]<1e-10 && + (spacedim!=3 || cell->center()[2]<0.5)) + cell->set_refine_flag(); + tria.execute_coarsening_and_refinement (); +} + + + + +template +void +check () +{ + MyFunction function; + + Triangulation tria; + make_mesh (tria); + + FE_Q element(2); + DoFHandler dof(tria); + dof.distribute_dofs(element); + + MappingQ mapping(3); + Quadrature &q_face = get_q_face(); + + Vector v (dof.n_dofs()); + VectorTools::interpolate (mapping, dof, function, v); + + Vector error (tria.n_active_cells()); + + std::map*> neumann_bc; + MyNormalDerivative function_normal; + neumann_bc[0] = &function_normal; + neumann_bc[1] = &function_normal; + + deallog << "estimating..." << std::endl; + KellyErrorEstimator::estimate (mapping, dof, q_face, + neumann_bc, + v, error); + deallog << "Estimated error indicators:" << std::endl; + for (unsigned int i=0; i > data_out; + data_out.attach_dof_handler (dof); + data_out.add_data_vector (v, + "solution", + DataOut >::type_dof_data); + data_out.add_data_vector (error, + "error"); + data_out.build_patches (); + std::string filename = spacedim == 2 ? + "solution-2d-" : + "solution-3d-"; + filename += Utilities::int_to_string(0,2) + ".vtk"; + std::ofstream output (filename.c_str()); + data_out.write_vtk (output); + + } + + deallog << "OK" << std::endl; +} + + +int main () +{ + // do not run multithreaded estimate() because that would break the order of the + // function evaluations that we log above + MultithreadInfo::set_thread_limit(1); + + initlog(true); + + deallog.push ("<1,2>"); + check<1,2> (); + deallog.pop(); + deallog.push ("<2,3>"); + check<2,3> (); + deallog.pop(); +} diff --git a/pool/shard001/C++/0024311_static_bin.cc b/pool/shard001/C++/0024311_static_bin.cc new file mode 100644 index 0000000000000000000000000000000000000000..99a4b7349587e841ec8e09d3de2624e0de8d8461 --- /dev/null +++ b/pool/shard001/C++/0024311_static_bin.cc @@ -0,0 +1,57 @@ +// Copyright 2019 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// This file is an example of a binary which is intended to be sandboxed by the +// sandbox2. It's not google3-based, and compiled statically (see BUILD). +// +// It inverts all bytes coming from stdin and writes them to the stdout. + +#include +#include + +#include +#include +#include + +int main(int argc, char** argv) { + char buf[1024]; + size_t total_bytes = 0U; + + fprintf(stderr, "=============================\n"); + fprintf(stderr, "Starting file capitalization\n"); + fprintf(stderr, "=============================\n"); + fflush(nullptr); + + for (;;) { + ssize_t sz = read(STDIN_FILENO, buf, sizeof(buf)); + if (sz < 0) { + perror("read"); + break; + } + if (sz == 0) { + break; + } + for (int i = 0; i < sz; i++) { + buf[i] = toupper(buf[i]); + } + write(STDOUT_FILENO, buf, sz); + total_bytes += sz; + } + + fprintf(stderr, "=============================\n"); + fprintf(stderr, "Converted: %zu bytes\n", total_bytes); + fprintf(stderr, "=============================\n"); + fflush(nullptr); + return 0; +} diff --git a/pool/shard001/C++/0024315_Tile.cpp b/pool/shard001/C++/0024315_Tile.cpp new file mode 100644 index 0000000000000000000000000000000000000000..116a907c2717992d6b28330708908e853ba8b485 --- /dev/null +++ b/pool/shard001/C++/0024315_Tile.cpp @@ -0,0 +1,102 @@ +/* + * This file is part of Goat Attack. + * + * Goat Attack 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. + * + * Goat Attack 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 Goat Attack. If not, see . + */ + +#include "Tile.hpp" + +const I18NText Tile::TypeDescription[] = { + I18N_TILETYPE01, // "non blocking" + I18N_TILETYPE02, // "blocking" + I18N_TILETYPE03, // "falling only blocking" + I18N_TILETYPE04, // "red base" + I18N_TILETYPE05, // "blue base" + I18N_TILETYPE06, // "killing" + I18N_TILETYPE07, // "jump, no descend" + I18N_TILETYPE08, // "speed race finish" + I18N_TILETYPE09, // "hill zone" + I18N_TILETYPE10, // "falling only blocking (single)" +}; + +Tile::Tile(TileGraphic *tilegraphic, bool background, TileType tile_type, + int animation_speed, bool one_shot, double friction) + : background(background), tile_type(tile_type), + animation_speed(animation_speed), + tilegraphic(tilegraphic), one_shot(one_shot), friction(friction), + animation_counter(0.0f), light_blocking(false) { } + +Tile::~Tile() { + delete tilegraphic; +} + +TileGraphic *Tile::get_tilegraphic() { + return tilegraphic; +} + +bool Tile::is_background() { + return background; +} + +Tile::TileType Tile::get_tile_type() { + return tile_type; +} + +int Tile::get_animation_speed() { + return animation_speed; +} + +bool Tile::is_one_shot() { + return one_shot; +} + +double Tile::get_friction() { + return friction; +} + +void Tile::update_tile_index(double diff) { + int& current_index = tilegraphic->get_current_index(); + animation_counter += diff; + if (animation_counter > static_cast(animation_speed)) { + animation_counter = 0.0f; + current_index++; + if (current_index >= static_cast(tilegraphic->get_tile_count())) { + current_index = 0; + } + } +} + +void Tile::set_is_background(bool state) { + background = state; +} + +void Tile::set_animation_speed(int speed) { + animation_speed = speed; +} + +void Tile::set_friction(double friction) { + this->friction = friction; +} + +void Tile::set_type(TileType type) { + tile_type = type; +} + +bool Tile::is_light_blocking() const { + return light_blocking; +} + +void Tile::set_light_blocking(bool state) { + light_blocking = state; +} diff --git a/pool/shard001/C++/0024321_WP42Parser.cpp b/pool/shard001/C++/0024321_WP42Parser.cpp new file mode 100644 index 0000000000000000000000000000000000000000..15d65f352f3139809f0d8087782b222873240495 --- /dev/null +++ b/pool/shard001/C++/0024321_WP42Parser.cpp @@ -0,0 +1,254 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */ +/* libwpd + * Version: MPL 2.0 / LGPLv2.1+ + * + * 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/. + * + * Major Contributor(s): + * Copyright (C) 2003 William Lachance (wrlach@gmail.com) + * Copyright (C) 2003 Marc Maurer (uwog@uwog.net) + * Copyright (C) 2006 Fridrich Strba (fridrich.strba@bluewin.ch) + * + * For minor contributions see the git repository. + * + * Alternatively, the contents of this file may be used under the terms + * of the GNU Lesser General Public License Version 2.1 or later + * (LGPLv2.1+), in which case the provisions of the LGPLv2.1+ are + * applicable instead of those above. + * + * For further information visit http://libwpd.sourceforge.net + */ + +/* "This product is not manufactured, approved, or supported by + * Corel Corporation or Corel Corporation Limited." + */ + +#include "WP42Parser.h" +#include "WP42Part.h" +#include "WPXHeader.h" +#include "libwpd_internal.h" +#include "WPXTable.h" +#include "WP42FileStructure.h" +#include "WP42StylesListener.h" +#include "WP42ContentListener.h" + +WP42Parser::WP42Parser(WPXInputStream *input, WPXEncryption *encryption) : + WPXParser(input, 0, encryption) +{ +} + +WP42Parser::~WP42Parser() +{ +} + +void WP42Parser::parse(WPXInputStream *input, WPXEncryption *encryption, WP42Listener *listener) +{ + listener->startDocument(); + + input->seek(0, WPX_SEEK_SET); + + WPD_DEBUG_MSG(("WordPerfect: Starting document body parse (position = %ld)\n",(long)input->tell())); + + parseDocument(input, encryption, listener); + + listener->endDocument(); +} + +// parseDocument: parses a document body (may call itself recursively, on other streams, or itself) +void WP42Parser::parseDocument(WPXInputStream *input, WPXEncryption *encryption, WP42Listener *listener) +{ + while (!input->atEOS()) + { + uint8_t readVal; + readVal = readU8(input, encryption); + + if (readVal < (uint8_t)0x20) + { + WPD_DEBUG_MSG(("Offset: %i, Handling Control Character 0x%2x\n", (unsigned int)input->tell(), readVal)); + + switch (readVal) + { + case 0x09: // tab + listener->insertTab(0, 0.0); + break; + case 0x0A: // hard new line + listener->insertEOL(); + break; + case 0x0B: // soft new page + listener->insertBreak(WPX_SOFT_PAGE_BREAK); + break; + case 0x0C: // hard new page + listener->insertBreak(WPX_PAGE_BREAK); + break; + case 0x0D: // soft new line + listener->insertCharacter(' '); + break; + default: + // unsupported or undocumented token, ignore + break; + } + } + else if (readVal >= (uint8_t)0x20 && readVal <= (uint8_t)0x7F) + { + WPD_DEBUG_MSG(("Offset: %i, Handling Ascii Character 0x%2x\n", (unsigned int)input->tell(), readVal)); + + // normal ASCII characters + listener->insertCharacter( readVal ); + } + else if (readVal >= (uint8_t)0x80 && readVal <= (uint8_t)0xBF) + { + WPD_DEBUG_MSG(("Offset: %i, Handling Single Character Function 0x%2x\n", (unsigned int)input->tell(), readVal)); + + // single character function codes + switch (readVal) + { + case 0x92: + listener->attributeChange(true, WP42_ATTRIBUTE_STRIKE_OUT); + break; + case 0x93: + listener->attributeChange(false, WP42_ATTRIBUTE_STRIKE_OUT); + break; + case 0x94: + listener->attributeChange(true, WP42_ATTRIBUTE_UNDERLINE); + break; + case 0x95: + listener->attributeChange(false, WP42_ATTRIBUTE_UNDERLINE); + break; + + case 0x90: + listener->attributeChange(true, WP42_ATTRIBUTE_REDLINE); + break; + case 0x91: + listener->attributeChange(false, WP42_ATTRIBUTE_REDLINE); + break; + + case 0x9C: + listener->attributeChange(false, WP42_ATTRIBUTE_BOLD); + break; + case 0x9D: + listener->attributeChange(true, WP42_ATTRIBUTE_BOLD); + break; + + case 0xB2: + listener->attributeChange(true, WP42_ATTRIBUTE_ITALICS); + break; + case 0xB3: + listener->attributeChange(false, WP42_ATTRIBUTE_ITALICS); + break; + case 0xB4: + listener->attributeChange(true, WP42_ATTRIBUTE_SHADOW); + break; + case 0xB5: + listener->attributeChange(false, WP42_ATTRIBUTE_SHADOW); + break; + + default: + // unsupported or undocumented token, ignore + break; + } + } + else if (readVal >= (uint8_t)0xC0 && readVal <= (uint8_t)0xFE) + { + WP42Part *part = WP42Part::constructPart(input, encryption, readVal); + if (part) + { + part->parse(listener); + DELETEP(part); + } + } + // ignore the rest since they are not documented and at least 0xFF is a special character that + // marks end of variable length part in variable length multi-byte functions + } +} + +void WP42Parser::parse(WPXDocumentInterface *documentInterface) +{ + WPXInputStream *input = getInput(); + WPXEncryption *encryption = getEncryption(); + std::list pageList; + std::vector subDocuments; + + try + { + // do a "first-pass" parse of the document + // gather table border information, page properties (per-page) + WP42StylesListener stylesListener(pageList, subDocuments); + parse(input, encryption, &stylesListener); + + // postprocess the pageList == remove duplicate page spans due to the page breaks + std::list::iterator previousPage = pageList.begin(); + for (std::list::iterator Iter=pageList.begin(); Iter != pageList.end();) + { + if ((Iter != previousPage) && ((*previousPage)==(*Iter))) + { + (*previousPage).setPageSpan((*previousPage).getPageSpan() + (*Iter).getPageSpan()); + Iter = pageList.erase(Iter); + } + else + { + previousPage = Iter; + ++Iter; + } + } + + // second pass: here is where we actually send the messages to the target app + // that are necessary to emit the body of the target document + WP42ContentListener listener(pageList, subDocuments, documentInterface); + parse(input, encryption, &listener); + + // cleanup section: free the used resources + for (std::vector::iterator iterSubDoc = subDocuments.begin(); iterSubDoc != subDocuments.end(); ++iterSubDoc) + { + if (*iterSubDoc) + delete (*iterSubDoc); + } + } + catch(FileException) + { + WPD_DEBUG_MSG(("WordPerfect: File Exception. Parse terminated prematurely.")); + + for (std::vector::iterator iterSubDoc = subDocuments.begin(); iterSubDoc != subDocuments.end(); ++iterSubDoc) + { + if (*iterSubDoc) + delete (*iterSubDoc); + } + + throw FileException(); + } + +} + +void WP42Parser::parseSubDocument(WPXDocumentInterface *documentInterface) +{ + std::list pageList; + std::vector subDocuments; + + WPXInputStream *input = getInput(); + + try + { + WP42StylesListener stylesListener(pageList, subDocuments); + stylesListener.startSubDocument(); + parseDocument(input, 0, &stylesListener); + stylesListener.endSubDocument(); + + WP42ContentListener listener(pageList, subDocuments, documentInterface); + listener.startSubDocument(); + parseDocument(input, 0, &listener); + listener.endSubDocument(); + for (std::vector::iterator iterSubDoc = subDocuments.begin(); iterSubDoc != subDocuments.end(); ++iterSubDoc) + if (*iterSubDoc) + delete (*iterSubDoc); + } + catch(FileException) + { + WPD_DEBUG_MSG(("WordPerfect: File Exception. Parse terminated prematurely.")); + for (std::vector::iterator iterSubDoc = subDocuments.begin(); iterSubDoc != subDocuments.end(); ++iterSubDoc) + if (*iterSubDoc) + delete (*iterSubDoc); + throw FileException(); + } +} +/* vim:set shiftwidth=4 softtabstop=4 noexpandtab: */ diff --git a/pool/shard001/C++/0024322_main.cpp b/pool/shard001/C++/0024322_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..55a8eca9db6f20da2874e35a2a7265e03836faaa --- /dev/null +++ b/pool/shard001/C++/0024322_main.cpp @@ -0,0 +1,102 @@ +/**************************************************************************** +** +** Copyright (C) 2016 The Qt Company Ltd. +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the documentation of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** 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. +** +** BSD License Usage +** Alternatively, you may use this file under the terms of the BSD license +** as follows: +** +** "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 Qt Company Ltd 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include + +QString tr(const char *text) +{ + return QApplication::translate(text, text); +} + +int main(int argc, char *argv[]) +{ + QApplication app(argc, argv); + QTextEdit *editor = new QTextEdit(); + + QTextCursor cursor(editor->textCursor()); + cursor.movePosition(QTextCursor::Start); + + QTextCharFormat plainFormat(cursor.charFormat()); + + QTextCharFormat headingFormat = plainFormat; + headingFormat.setFontWeight(QFont::Bold); + headingFormat.setFontPointSize(16); + + QTextCharFormat emphasisFormat = plainFormat; + emphasisFormat.setFontItalic(true); + + QTextCharFormat qtFormat = plainFormat; + qtFormat.setForeground(QColor("#990000")); + + QTextCharFormat underlineFormat = plainFormat; + underlineFormat.setFontUnderline(true); + +//! [0] + cursor.insertText(tr("Character formats"), + headingFormat); + + cursor.insertBlock(); + + cursor.insertText(tr("Text can be displayed in a variety of " + "different character formats. "), plainFormat); + cursor.insertText(tr("We can emphasize text by ")); + cursor.insertText(tr("making it italic"), emphasisFormat); +//! [0] + cursor.insertText(tr(", give it a "), plainFormat); + cursor.insertText(tr("different color "), qtFormat); + cursor.insertText(tr("to the default text color, "), plainFormat); + cursor.insertText(tr("underline it"), underlineFormat); + cursor.insertText(tr(", and use many other effects."), plainFormat); + + editor->setWindowTitle(tr("Text Document Character Formats")); + editor->resize(320, 480); + editor->show(); + return app.exec(); +} diff --git a/pool/shard001/C++/0024327_compute_rhs.cc b/pool/shard001/C++/0024327_compute_rhs.cc new file mode 100644 index 0000000000000000000000000000000000000000..8522c725d33cce89eaad7cd1c434575295af18c7 --- /dev/null +++ b/pool/shard001/C++/0024327_compute_rhs.cc @@ -0,0 +1,153 @@ +/* Tarang-4.0 + * + * Copyright (C) 2008, 2009 Mahendra K. Verma + * + * Mahendra K. Verma + * Indian Institute of Technology, Kanpur-208016 + * UP, India + * + * mkv@iitk.ac.in + * + * This file is part of Tarang-4.0 . + * + * Tarang-4.0 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. + * Tarang-4.0 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 Tarang-4.0; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, U + */ + + +/*! \file compute_rhs.cc + * + * @brief Compute rhs. + * @sa void IncFluid::Compute_rhs() + * + * @author M. K. Verma + * @version 4.0 MPI + * @date Feb 2009 + * + * @bug No known bugs + */ + +#include "IncFluid.h" + +//********************************************************************************************* + +/** @brief Compute rhs for fluid simulation + * + * @note Status before entering the fn + * nlin[i] contains Dj T[Vr[j]*Vr[i]] - f[i]; + * F.p contains pressure; + * + * @return (rhs) = nlin[i] = -Dj T[Vr[j]*Vr[i]] + f[i] - Di [p(k)] (-grad(pressure)) + */ +void IncFluid::Compute_rhs() +{ + + Add_pressure_gradient(); // nlin = nlin + grad(p) + + *nlin1 = -*nlin1; + *nlin2 = -*nlin2; + *nlin3 = -*nlin3; +} + + + +//********************************************************************************************* + +/** @brief Compute rhs for fluid simulation with scalar + * + * @note Status before entering the fn + * nlin[i] contains Dj T[Vr[j]*Vr[i]] - f[i]; + * F.p contains pressure; + * T.nlin = T[U.grad T] + * + * @return (rhs) = nlin[i] = -Dj T[Vr[j]*Vr[i]] + f[i] - Di [p(k)] (-grad(pressure)) + * (T.nlin) = T.nlin = -T.nlin + */ + +void IncFluid::Compute_rhs(IncSF& T) +{ + if ((globalvar_prog_kind == "INC_SCALAR") || (globalvar_prog_kind == "INC_SCALAR_DIAG")) + Compute_rhs_scalar(T); + + else if ((globalvar_prog_kind == "RB_SLIP") || (globalvar_prog_kind == "RB_SLIP_DIAG") + || (globalvar_prog_kind == "NonBoussinesq")) + Compute_rhs_RB(T); + +} + + +void IncFluid::Compute_rhs_scalar(IncSF& T) +{ + + Compute_rhs(); // Fluid: U.nlin[i] = -U.nlin[i] -FT[grad(p)] + + *T.nlin = -*T.nlin; // For scalar: rhs = -T.nlin +} + + +void IncFluid::Compute_rhs_RB(IncSF& T) +{ + + Compute_rhs(); + + if (globalvar_Pr_switch != "PRZERO") + *T.nlin = -*T.nlin; +} + +//********************************************************************************************* + +/** @brief Compute rhs for fluid simulation with a vector + * + * @note Status before entering the fn + * nlin[i] contains Dj T[Vr[j]*Vr[i]] - f[i]; + * F.p contains pressure; + * W.nlin = T[U.grad B - B.grad U] + * + * @return (rhs) = nlin[i] = -Dj T[Vr[j]*Vr[i]] + f[i] - Di [p(k)] (-grad(pressure)) + * (W.nlin) = W.nlin[i] = -W.nlin[i] + */ +void IncFluid::Compute_rhs(IncVF& W) +{ + + Compute_rhs(); // Fluid: U.nlin[i] = -U.nlin[i] -FT[grad(p)] + + *W.nlin1 = -*W.nlin1; // VF-W rhs[i] = -nlin[i] + *W.nlin2 = -*W.nlin2; + *W.nlin3 = -*W.nlin3; +} + + +//********************************************************************************************* + +/** @brief Compute rhs for fluid simulation with a vector and a scalar + * + * @note Status before entering the fn + * nlin[i] contains Dj T[Vr[j]*Vr[i]] - f[i]; + * F.p contains pressure; + * W.nlin = T[U.grad B - B.grad U] + * T.nlin = T[U.grad T] + * + * @return (rhs) = nlin[i] = -Dj T[Vr[j]*Vr[i]] + f[i] - Di [p(k)] (-grad(pressure)) + * (W.nlin) = W.nlin[i] = -W.nlin[i] + * (T.nlin) = T.nlin = -T.nlin + */ +void IncFluid::Compute_rhs(IncVF& W, IncSF& T) +{ + Compute_rhs(W); + + *T.nlin = -*T.nlin; // For scalar: rhs = -T.nlin +} + + +//********************************** End of compute_rhs.cc ********************************* + diff --git a/pool/shard001/C++/0024331_LeastSquares.cpp b/pool/shard001/C++/0024331_LeastSquares.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2dae8e488a4a279b622f0f7dd187899c635482d3 --- /dev/null +++ b/pool/shard001/C++/0024331_LeastSquares.cpp @@ -0,0 +1,174 @@ +/* +Copyright_License { + + XCSoar Glide Computer - http://www.xcsoar.org/ + Copyright (C) 2000-2015 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. +} +*/ + +// leastsqs.c -- Implements a simple linear least squares best fit routine +// +// Written by Curtis Olson, started September 1997. +// +// Copyright (C) 1997 Curtis L. Olson - http://www.flightgear.org/~curt +// +// 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; if not, write to the +// Free Software Foundation, Inc., 59 Temple Place - Suite 330, +// Boston, MA 02111-1307, USA. + + +#include "Math/LeastSquares.hpp" + +#include + +/* +Least squares fit: + + y = b0 + b1x + + n * sum(xi * yi) - (sum(xi) * sum(yi)) + b1 = ---------------------------------------- + n * sum(xi^2) - sum(xi)^2 + + + b0 = sum(yi) / n - b1 * (sum(xi) / n) + +*/ + +/* +return the least squares error: + + (y[i] - y_hat[i])^2 + --------------------- + n +*/ + +/* +return the maximum least squares error: + + (y[i] - y_hat[i])^2 + +*/ + +void +LeastSquares::Reset() +{ + sum_n = 0; + sum_xi = fixed(0); + sum_yi = fixed(0); + sum_xi_2 = fixed(0); + sum_xi_yi = fixed(0); + max_error = fixed(0); + sum_error = fixed(0); + rms_error = fixed(0); + sum_weights = fixed(0); + y_max = fixed(0); + y_min = fixed(0); + x_min = fixed(0); + x_max = fixed(0); + y_ave = fixed(0); + slots.clear(); +} + +void +LeastSquares::Compute() +{ + fixed denom = (sum_weights * sum_xi_2 - sum_xi * sum_xi); + + if (positive(fabs(denom))) { + m = (sum_weights * sum_xi_yi - sum_xi * sum_yi) / denom; + } else { + m = fixed(0); + } + b = (sum_yi - m * sum_xi) / sum_weights; + + y_ave = GetYAt(GetMiddleX()); +} + +void +LeastSquares::Update(fixed y) +{ + Update(fixed(sum_n + 1), y); +} + +void +LeastSquares::Update(fixed x, fixed y, fixed weight) +{ + // Add new point + Add(x, y, weight); + // Update calculation + Compute(); + + // Calculate error + fixed error = fabs(y - GetYAt(x)); + sum_error += sqr(error) * weight; + if (error > max_error) + max_error = error; +} + +void +LeastSquares::UpdateError() +{ + rms_error = sqrt(sum_error / sum_weights); +} + +void +LeastSquares::Add(fixed x, fixed y, fixed weight) +{ + // Update maximum/minimum values + if (IsEmpty() || y > y_max) + y_max = y; + + if (IsEmpty() || y < y_min) + y_min = y; + + if (IsEmpty() || x > x_max) + x_max = x; + + if (IsEmpty() || x < x_min) + x_min = x; + + // Add point + // TODO code: really should have a circular buffer here + if (!slots.full()) + slots.append() = Slot(x, y, weight); + + ++sum_n; + + // Add weighted point + sum_weights += weight; + + fixed xw = x * weight; + fixed yw = y * weight; + + sum_xi += xw; + sum_yi += yw; + sum_xi_2 += sqr(xw); + sum_xi_yi += xw * yw; +} diff --git a/pool/shard001/C++/0024332_DebugExpressionFactory.cpp b/pool/shard001/C++/0024332_DebugExpressionFactory.cpp new file mode 100644 index 0000000000000000000000000000000000000000..616a9c0e95e73c5630219f1a26ac635464868e61 --- /dev/null +++ b/pool/shard001/C++/0024332_DebugExpressionFactory.cpp @@ -0,0 +1,264 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the test suite 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 +#include +#include +#include + +#include "qfunctionfactorycollection_p.h" + +#include "ASTItem.h" +#include "ExpressionInfo.h" +#include "ExpressionNamer.h" +#include "Global.h" + +#include "DebugExpressionFactory.h" + +using namespace QPatternistSDK; +using namespace QPatternist; + +static const QPatternist::ExpressionVisitor::Ptr namer(new ExpressionNamer()); + +QStringList DebugExpressionFactory::availableFunctionSignatures() +{ + const QPatternist::FunctionFactory::Ptr factory(QPatternist::FunctionFactoryCollection::xpath20Factory(Global::namePool())); + const QPatternist::FunctionSignature::Hash signs(factory->functionSignatures()); + const QPatternist::FunctionSignature::Hash::const_iterator end(signs.constEnd()); + QPatternist::FunctionSignature::Hash::const_iterator it(signs.constBegin()); + QStringList retval; + + while(it != end) + { + retval << it.value()->displayName(Global::namePool()); + ++it; + } + + return retval; +} + +ASTItem *DebugExpressionFactory::buildASTTree(const QPatternist::Expression::Ptr &expr, + ASTItem *parent, + const QPatternist::SequenceType::Ptr &reqType) +{ + Q_ASSERT(expr); + const QPatternist::ExpressionVisitorResult::Ptr exprInfo(expr->accept(namer)); + Q_ASSERT(exprInfo); + const ExpressionInfo *const constExprInfo = static_cast(exprInfo.data()); + const QString name(constExprInfo->first); + const QString details(constExprInfo->second); + const QString rType(reqType ? reqType->displayName(Global::namePool()) : QLatin1String("Not specified")); + + /* ---------- Handle its staticType() -------- */ + const QPatternist::SequenceType::Ptr type(expr->staticType()); + QString seqType; + + if(type) + seqType = type->displayName(Global::namePool()); + else + seqType = QLatin1String("no type, null pointer returned"); + /* ------------------------------------------- */ + + ASTItem *const node = new ASTItem(parent, name, details, seqType, rType); + + /* ------------ Handle child nodes ----------- */ + const QPatternist::Expression::List children(expr->operands()); + QPatternist::Expression::List::const_iterator it(children.constBegin()); + const QPatternist::Expression::List::const_iterator end(children.constEnd()); + + const QPatternist::SequenceType::List reqTypes(expr->expectedOperandTypes()); + const QPatternist::SequenceType::List::const_iterator typeEnd(reqTypes.constEnd()); + QPatternist::SequenceType::List::const_iterator typeIt(reqTypes.constBegin()); + QPatternist::SequenceType::Ptr t; + + for(; it != end; ++it) + { + if(typeIt != typeEnd) + { + t = *typeIt; + ++typeIt; + } + + node->appendChild(buildASTTree(*it, node, t)); + } + /* ------------------------------------------- */ + + return node; +} + +QPatternist::Expression::Ptr +DebugExpressionFactory::createExpression(QIODevice *const expr, + const QPatternist::StaticContext::Ptr &context, + const QXmlQuery::QueryLanguage lang, + const QPatternist::SequenceType::Ptr &requiredType, + const QUrl &baseURI, + const QXmlName &initialTemplateName) +{ + /* Create the root node. */ + m_ast = new ASTItem(0, QString()); + + return ExpressionFactory::createExpression(expr, context, lang, requiredType, baseURI, initialTemplateName); +} + +void DebugExpressionFactory::processTreePass(const QPatternist::Expression::Ptr &expr, + const CompilationStage stage) +{ + ASTItem *newChild = 0; + + switch(stage) + { + case QueryBodyInitial: + { + newChild = new ASTItem(m_ast, QLatin1String("Initial Build")); + break; + } + case QueryBodyTypeCheck: + { + newChild = new ASTItem(m_ast, QLatin1String("Type Check")); + break; + } + case QueryBodyCompression: + { + newChild = new ASTItem(m_ast, QLatin1String("Compression")); + break; + } + case UserFunctionTypeCheck: + { + newChild = new ASTItem(m_ast, QLatin1String("User Function Type Check")); + break; + } + case UserFunctionCompression: + { + newChild = new ASTItem(m_ast, QLatin1String("User Function Compression")); + break; + } + case GlobalVariableTypeCheck: + { + newChild = new ASTItem(m_ast, QLatin1String("Global Variable Type Check")); + break; + } + } + + Q_ASSERT(newChild); + m_ast->appendChild(newChild); + newChild->appendChild(buildASTTree(expr, newChild, QPatternist::SequenceType::Ptr())); +} + +void DebugExpressionFactory::processTemplateRule(const Expression::Ptr &body, + const TemplatePattern::Ptr &pattern, + const QXmlName &mode, + const TemplateCompilationStage stage) +{ + const char * title; + + switch(stage) + { + case TemplateInitial: + { + title = "Initial Build"; + break; + } + case TemplateTypeCheck: + { + title = "Type Check"; + break; + } + case TemplateCompress: + { + title = "Compression"; + break; + } + } + + const QString modeName(Global::namePool()->displayName(mode)); + Q_ASSERT(title); + ASTItem *const newChild = new ASTItem(m_ast, QLatin1String("T-Rule ") + + QLatin1String(title) + + QLatin1String(" mode: ") + + modeName + + QLatin1String(" priority: ") + + QString::number(pattern->priority())); + m_ast->appendChild(newChild); + + newChild->appendChild(buildASTTree(pattern->matchPattern(), newChild, QPatternist::SequenceType::Ptr())); + newChild->appendChild(buildASTTree(body, newChild, QPatternist::SequenceType::Ptr())); +} + +void DebugExpressionFactory::processNamedTemplate(const QXmlName &name, + const Expression::Ptr &body, + const TemplateCompilationStage stage) +{ + const char * title; + + switch(stage) + { + case TemplateInitial: + { + title = "Named Template Initial Build"; + break; + } + case TemplateTypeCheck: + { + title = "Named Template Type Check"; + break; + } + case TemplateCompress: + { + title = "Named Template Compression"; + break; + } + } + + Q_ASSERT(title); + ASTItem *const newChild = new ASTItem(m_ast, QLatin1String(title) + + QLatin1String(": ") + + Global::namePool()->displayName(name)); + + m_ast->appendChild(newChild); + newChild->appendChild(buildASTTree(body, newChild, QPatternist::SequenceType::Ptr())); +} + +ASTItem *DebugExpressionFactory::astTree() const +{ + return m_ast; +} + +// vim: et:ts=4:sw=4:sts=4 diff --git a/pool/shard001/C++/0024337_command.cpp b/pool/shard001/C++/0024337_command.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cc1a61b85bab5f650278ebb4625a3d86d075812f --- /dev/null +++ b/pool/shard001/C++/0024337_command.cpp @@ -0,0 +1,218 @@ +#include "command.h" + +// int Command::execute(Reader& reader, Writer& writer) = 0; + +jsmntok_t* JSONCommand::json_tokenise(char *s_json) { + jsmn_parser parser; + parser.size = sizeof(parser); + jsmn_init(&parser, NULL); + + unsigned int n = 64; + jsmntok_t* a_tokens = (jsmntok_t*)malloc(sizeof(jsmntok_t) * n); + if (!a_tokens) return nullptr; + int ret = jsmn_parse(&parser, s_json, strlen(s_json), a_tokens, n, NULL); + while (ret == JSMN_ERROR_NOMEM) { + n = n * 2 + 1; + jsmntok_t* prev = a_tokens; + a_tokens = (jsmntok_t*)realloc(a_tokens, sizeof(jsmntok_t) * n); + if (!a_tokens) { + free(prev); + return nullptr; + } + ret = jsmn_parse(&parser, s_json, strlen(s_json), a_tokens, n, NULL); + } + return a_tokens; +} + +bool JSONCommand::json_token_streq(const char *s_json, jsmntok_t *a_token, const char *s_string) { + return (strncmp(s_json + a_token->start, s_string, a_token->end - a_token->start) == 0 + && strlen(s_string) == (size_t) (a_token->end - a_token->start)); +} + +char* JSONCommand::json_token_tostr(char *s_json, jsmntok_t *a_token) { + s_json[a_token->end] = '\0'; + return s_json + a_token->start; +} + +void JSONCommand::write_result_code(Writer& writer, int n_result) { + write_char(writer, '{'); + write_json_int(writer, "r", n_result); + write_char(writer, '}'); +} + +int JSONCommand::parse_request(Reader& reader) { + return 0; +} + +void JSONCommand::produce_response(Writer& writer, int n_result) { + write_result_code(writer, n_result); +} + +int JSONCommand::process() { + return 0; +} + +void JSONCommand::write_char(Writer& w, char c) { + w.write((uint8_t*) & c, 1); +} + +void JSONCommand::write_quoted_string(Writer& out, const char* s_string) { + write_char(out, '"'); + out.write(s_string); + write_char(out, '"'); +} + +void JSONCommand::write_json_string(Writer& out, const char* s_name, const char* s_value) { + write_quoted_string(out, s_name); + write_char(out, ':'); + write_quoted_string(out, s_value); +} + +char* JSONCommand::int_to_ascii(int val, char* buf, int i) { + buf[--i] = 0; + bool negative = val < 0; + if (negative) { + val = -val; + } + buf[--i] = (val % 10) + '0'; + val /= 10; + for(; val && i ; val /= 10) { + buf[--i] = (val % 10) + '0'; + } + if (negative) + buf[--i] = '-'; + return &buf[i]; +} + +void JSONCommand::write_json_int(Writer& out, const char* s_name, int n_value) { + char buf[20]; + write_quoted_string(out, s_name); + write_char(out, ':'); + out.write(int_to_ascii(n_value, buf, 20)); +} + +int JSONCommand::execute(Reader& reader, Writer& writer) { + int result = parse_request(reader); + if (!result) { + result = process(); + produce_response(writer, result); + } + return result; +} + +/** + * A command that parses a JSON request. + */ +int JSONRequestCommand::parse_json_string(char* s_json, const char* const a_keys[], const jsmntype_t a_types[], unsigned n_types) { + if (!s_json) + return -1; + + int n_result = -1; + jsmntok_t *a_tokens = json_tokenise(s_json); + + if (a_tokens) { + enum c_parseState { START, KEY, VALUE, SKIP, STOP }; + + c_parseState n_state = START; + jsmntype_t expected_type = JSMN_OBJECT; + + n_result = 0; + int n_key = -1; + + for (size_t n_token = 0, j = 1; j > 0; n_token++, j--) { + jsmntok_t *a_token = &a_tokens[n_token]; + + if (a_token->type == JSMN_ARRAY || a_token->type == JSMN_OBJECT) + j += a_token->size * 2; + + switch (n_state) { + case START: + n_state = KEY; + break; + + case KEY: + n_state = VALUE; + n_key = -1; + for (size_t n_type = 0; n_type < n_types; n_type++) { + if (json_token_streq(s_json, a_token, a_keys[n_type])) { + expected_type = a_types[n_type]; + n_key = n_type; +// Log.info("key: %s %d %d", a_keys[n_type], n_type, (int)expected_type); + } + } + if (n_key == -1) { + Log.warn("JSON Unknown Key: %s", json_token_tostr(s_json, a_token)); + n_result = -1; + } + break; + + case VALUE: + if (n_key != -1) { + if (a_token->type != expected_type) { + n_result = -1; + Log.error("JSON Type Mismatch"); + } + else { + char *s_string = json_token_tostr(s_json, a_token); + if (!parsed_value(n_key, a_token, s_string)) + n_result = -1; + } + } + n_state = KEY; + break; + + case STOP: // Just consume the tokens + break; + + default: + n_result = -1; + } + } + free(a_tokens); + } + return n_result; +} + +int JSONRequestCommand::parse_json_request(Reader& reader, const char* const a_keys[], const jsmntype_t a_types[], unsigned n_types) { + char* s_json = reader.fetch_as_string(); + int n_result = parse_json_string(s_json, a_keys, a_types, n_types); + free(s_json); + return n_result; +} + +int SetConfigCommand::execute(Reader& o_reader, Writer& o_writer) { + int n_result = parse_json_request(o_reader, KEY, TYPE, arraySize(KEY)); + o_config.f_save(); + produce_response(o_writer, n_result); + return n_result; +} + +int SetConfigCommand::execute(char* s_config) { + int n_result = parse_json_string(s_config, KEY, TYPE, arraySize(KEY)); + o_config.f_save(); + return n_result; +} + +bool SetConfigCommand::parsed_value(unsigned n_key, jsmntok_t* a_type, char* s_value) { + Log.info("JSON Key: %s, Value: %s", KEY[n_key], (char*)s_value); + int8_t n_result = o_config.f_setValue(String(KEY[n_key]), String(s_value)); + return (n_result != -1); +} + +c_config& SetConfigCommand::o_config = c_config::f_getInstance(); +const char* SetConfigCommand::KEY[13] = {"nme","rdt","mtt","rlt","rlp","srr","srt","mqtt","mqip","mqpt","mqus","mqpw","mqto"}; +const jsmntype_t SetConfigCommand::TYPE[] = { + JSMN_STRING, + JSMN_PRIMITIVE, + JSMN_PRIMITIVE, + JSMN_PRIMITIVE, + JSMN_PRIMITIVE, + JSMN_PRIMITIVE, + JSMN_PRIMITIVE, + JSMN_PRIMITIVE, + JSMN_STRING, + JSMN_PRIMITIVE, + JSMN_STRING, + JSMN_STRING, + JSMN_PRIMITIVE +}; diff --git a/pool/shard001/JavaScript/0005989_document-detail.js b/pool/shard001/JavaScript/0005989_document-detail.js new file mode 100644 index 0000000000000000000000000000000000000000..f93480a8c247df4c3b4b1f2ba39f51f7a1b370be --- /dev/null +++ b/pool/shard001/JavaScript/0005989_document-detail.js @@ -0,0 +1,52 @@ +/** @jsx React.DOM */ + +var React = require('react'); +var moment = require('moment'); +var jq = require("jquery"); + +var DocumentDetail = React.createClass({ + getInitialState: function() { + return { + selectedDocument: null + }; + }, + + normalizedDocument: function(doc) { + return doc; + }, + + componentDidMount: function() { + window.addEventListener("scroll", function(evt) { + if (jq('body').scrollTop() > 434 || jq('html').scrollTop() > 434) { + if (jq(window).height() > 20) { + jq('.document-detail').addClass('document-detail-fixed'); + } + } + else { + jq('.document-detail').removeClass('document-detail-fixed'); + } + }.bind(this)); + }, + + render: function() { + var r = this.normalizedDocument(this.props.valueLink.value); + console.debug("selected doc:", r); + + return ( +

+

+
+

{r.guid}

+

{moment(r.datePublished).format('L')}

+

{r.type}

+
+

{r.inventors_short}

+

+

+

+

+ ); + } +}); + +module.exports = DocumentDetail; diff --git a/pool/shard001/JavaScript/0005991_dollar.js b/pool/shard001/JavaScript/0005991_dollar.js new file mode 100644 index 0000000000000000000000000000000000000000..e70e62a53169d08b77097936952f0ea31c239f94 --- /dev/null +++ b/pool/shard001/JavaScript/0005991_dollar.js @@ -0,0 +1,47 @@ +var Dollar = (function() { + var lower_bound = "a".charCodeAt(0); + var upper_bound = "Z".charCodeAt(0); + + var is_valid = function(s) { + var i = s.charCodeAt(0); + if ((i >= lower_bound) && (i <= upper_bound)) { + return true; + } else { + return false; + } + }; + + var extract = function(s, starts, modifiers) { + var start_chars = starts || ["$"]; + var mod_chars = modifiers || ["|"]; + + var accum = []; + var index = 0; + var in_var = false; + var buffer = []; + + for(var i=0; i < s.length; i++) { + var char = s[i]; + if (in_var) { + if (is_valid(char)) { + buffer.push(char); + } else { + in_var = false; + accum.push(buffer.join('')); + buffer = []; + } + } else { + if (start_chars.indexOf(char) != -1) { + in_var = true; + } + } + } + + if (buffer.length) { + accum.push(buffer); + } + + return accum; + }; + var render = function() {}; +})(); diff --git a/pool/shard001/JavaScript/0005992_project_issues.js b/pool/shard001/JavaScript/0005992_project_issues.js new file mode 100644 index 0000000000000000000000000000000000000000..be7d2b5654ea33b931b72790c91273a3b08de48c --- /dev/null +++ b/pool/shard001/JavaScript/0005992_project_issues.js @@ -0,0 +1,133 @@ +window.ProjectIssuesView = BaseView.extend({ + + template: _.template($('#project_issues_underscore').html()), + + events: { + "click .close-backlog": "closeBacklog", + "click .open-backlog": "openBacklog", + }, + + initialize: function() { + _.bindAll(this, 'doRender'); + this.listenTo(this.model, 'change', this.doRender); + this.ignores = 0; + }, + + closeBacklog: function(ev) { + var that = this; + ev.preventDefault(); + that.$('.state-col').each(function(ind, e) { + var el = $(e); + el.removeClass('col-md-3').addClass('col-md-4'); + }); + that.$('.backlog-col').addClass('hidden'); + that.$('.glyphicon-folder-close').removeClass('hidden'); + }, + + openBacklog: function(ev) { + var that = this; + ev.preventDefault(); + that.$('.state-col').each(function(ind, e) { + var el = $(e); + el.removeClass('col-md-4').addClass('col-md-3'); + }); + that.$('.backlog-col').removeClass('hidden'); + that.$('.glyphicon-folder-close').addClass('hidden'); + }, + + render: function() { + var that = this; + window.session.nav.setPath([ + { + label: that.model.get('Name'), + path: '/projects/' + that.model.get('Id'), + }, + { + label: 'Issues', + path: '/projects/' + that.model.get('Id') + '/issues', + }, + ]); + window.session.nav.setCollaborators(that.model.collaborators.models); + that.$el.html(that.template({ + model: that.model, + })); + that.$('.issue-list').css('height', '' + ($(window).height() - 150) + 'px'); + that.model.issues.each(function(issue) { + var state = issue.getState(); + if (state == 'Ready') { + that.$('.ready-issues').append(new IssueView({ + project: that.model, + parent: that, + model: issue, + }).doRender().el); + } else if (state == 'Doing') { + that.$('.doing-issues').append(new IssueView({ + project: that.model, + parent: that, + model: issue, + }).doRender().el); + } else if (state == 'Done') { + that.$('.done-issues').append(new IssueView({ + project: that.model, + parent: that, + model: issue, + }).doRender().el); + } else if (state == 'Backlog') { + that.$('.backlog-issues').append(new IssueView({ + project: that.model, + parent: that, + model: issue, + }).doRender().el); + } + }); + var updateFunc = function(ev, ui) { + if (that.ignores > 0) { + that.ignores--; + $(ev.target).sortable('cancel'); + return + } + var issueElement = $(ev.toElement).closest('.issue'); + if (issueElement.length == 1) { + var issue = $(ev.toElement).closest('.issue')[0].issue; + var before = issueElement.prev('.issue'); + var after = issueElement.next('.issue'); + var changedPrio = false; + var newPrio = issue.getPrio(); + if (before.length == 0 && after.length == 1) { + newPrio = after[0].issue.getPrio() - 1; + } else if (before.length == 1 && after.length == 0) { + newPrio = before[0].issue.getPrio() + 1; + } else if (before.length == 1 && after.length == 1) { + newPrio = (before[0].issue.getPrio() + after[0].issue.getPrio()) / 2.0; + } + changedPrio = issue.setPrio(newPrio); + var el = $(ev.target); + var changedState = false; + if (el.hasClass('ready-issues')) { + changedState = issue.setState('Ready'); + } else if (el.hasClass('doing-issues')) { + changedState = issue.setState('Doing'); + } else if (el.hasClass('done-issues')) { + changedState = issue.setState('Done'); + } else if (el.hasClass('backlog-issues')) { + changedState = issue.setState('Backlog'); + } + if (changedState || changedPrio) { + issue.updateBody(); + } + if (changedState) { + that.model.updateStates(); + } + } + }; + that.$('.issue-list').sortable({ + connectWith: '.issue-list', + stop: updateFunc, + receive: updateFunc, + }); + return that; + }, + +}); + + diff --git a/pool/shard001/JavaScript/0005996_MasteriesEndpoint.js b/pool/shard001/JavaScript/0005996_MasteriesEndpoint.js new file mode 100644 index 0000000000000000000000000000000000000000..fdf892b649d143da6862831790a3c1e233a5fae0 --- /dev/null +++ b/pool/shard001/JavaScript/0005996_MasteriesEndpoint.js @@ -0,0 +1,65 @@ +'use strict' +var Endpoint = require('./Endpoint'), + cheerio = require('cheerio'), + Error = require('../Responses/Error'), + responseCodes = require('../Responses/response_codes.json'), + errorMessages = require('../Responses/error_messages.json') + +module.exports = class MasteriesEndpoint extends Endpoint { + Path() { + return '/summoner/mastery/' + } + + ErrorCheck($) { + if (!$) return false + if ($('.ErrorMessage').length) { + return new Error(errorMessages.NO_RESULTS, responseCodes.NO_RESULTS) + } + return false + } + + Parse($) { + var data = [], + regex = undefined + + $('.MasteryPageWrap').each((i, element) => { + var $ = cheerio.load(element), + masteryContainer = {}, + mastery = {} + + masteryContainer.title = this.Strip($('.MasteryPageName').text()) + masteryContainer.masteries = {} + mastery.ranks = [] + $('.MasteryPageArea').each((i, item) => { + var $ = cheerio.load(item) + + $('.Mastery').each((j, item1) => { + var $ = cheerio.load(item1), + rank1 = $('.Rank'), + rank2 = item1.attribs.class.indexOf('Rank-full') > -1, + obj = {} + + obj.rank = rank1.length ? parseInt(rank1.text()) : rank2 ? 1 : 0 + obj.name = item1.attribs.title + obj.name = new RegExp(/>([a-zA-Z \']*) 0) { + data.push(masteryContainer) + } + }) + return data.length ? data : new Error(errorMessages.NO_RESULTS, responseCodes.NO_RESULTS) + } +} \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006001_stacktrace_decorator.js b/pool/shard001/JavaScript/0006001_stacktrace_decorator.js new file mode 100644 index 0000000000000000000000000000000000000000..dd6b0ce458fa1631bba4cf3500285aa76855a357 --- /dev/null +++ b/pool/shard001/JavaScript/0006001_stacktrace_decorator.js @@ -0,0 +1,62 @@ +/* + * Copyright (c) André Bargull + * Alle Rechte vorbehalten / All Rights Reserved. Use is subject to license terms. + * + * + */ +function assertEq(actual, expected) { + if (actual !== expected) { + throw new Error(`Expected '${expected}', but got '${actual}'`); + } +} + +function stackTrace() { + var st = new Error().stackTrace; + return {value: () => st}; +} + +var o = { + @stackTrace + m1() {}, + + @stackTrace + m2() {}, +}; + +var st1 = o.m1(); +var st2 = o.m2(); + +assertEq(st1.length, 2); +assertEq(st1[0].methodName, "stackTrace"); +assertEq(st1[0].lineNumber, 14); +assertEq(st1[1].methodName, ""); +assertEq(st1[1].lineNumber, 19); + +assertEq(st2.length, 2); +assertEq(st2[0].methodName, "stackTrace"); +assertEq(st2[0].lineNumber, 14); +assertEq(st2[1].methodName, ""); +assertEq(st2[1].lineNumber, 22); + +var o = new class { + @stackTrace + m1() {} + + @stackTrace + m2() {} +}; + +var st1 = o.m1(); +var st2 = o.m2(); + +assertEq(st1.length, 2); +assertEq(st1[0].methodName, "stackTrace"); +assertEq(st1[0].lineNumber, 14); +assertEq(st1[1].methodName, ""); +assertEq(st1[1].lineNumber, 42); + +assertEq(st2.length, 2); +assertEq(st2[0].methodName, "stackTrace"); +assertEq(st2[0].lineNumber, 14); +assertEq(st2[1].methodName, ""); +assertEq(st2[1].lineNumber, 45); diff --git a/pool/shard001/JavaScript/0006002_update.test.js b/pool/shard001/JavaScript/0006002_update.test.js new file mode 100644 index 0000000000000000000000000000000000000000..2da88134af7088e832886dfa1a153f254ba45ce9 --- /dev/null +++ b/pool/shard001/JavaScript/0006002_update.test.js @@ -0,0 +1,122 @@ +describe('update', function () { + it('should update', function () { + var Test = this + + setTimeout(function () { + Test.requests[0].respond(200, { 'Content-Type': 'application/json' }, JSON.stringify(Test.p1)) + }, 30) + + return Test.adapter.update(Test.Post, 1, { author: 'John', age: 30 }) + .then(function (data) { + Test.assert.equal(1, Test.requests.length) + Test.assert.equal(Test.requests[0].url, 'api/posts/1') + Test.assert.equal(Test.requests[0].method, 'PUT') + Test.assert.equal(Test.requests[0].requestBody, JSON.stringify({ author: 'John', age: 30 })) + Test.assert.deepEqual(data, Test.p1, 'post 5 should have been updated') + + setTimeout(function () { + Test.requests[1].respond(200, { 'Content-Type': 'application/json' }, JSON.stringify(Test.p1)) + }, 30) + + return Test.adapter.update(Test.Post, 1, { author: 'John', age: 30 }, { basePath: 'api2' }) + }) + .then(function (data) { + Test.assert.equal(2, Test.requests.length) + Test.assert.equal(Test.requests[1].url, 'api2/posts/1') + Test.assert.equal(Test.requests[1].method, 'PUT') + Test.assert.equal(Test.requests[1].requestBody, JSON.stringify({ author: 'John', age: 30 })) + Test.assert.deepEqual(data, Test.p1, 'post 5 should have been updated') + }) + }) + it('should send nested relations', function () { + var Test = this + var JSData = Test.JSData + var store = new JSData.Container() + store.registerAdapter('http', Test.adapter, { default: true }) + store.defineMapper('user', { + relations: { + hasMany: { + post: { + localField: 'posts', + foreignKey: 'userId' + }, + address: { + localField: 'addresses', + foreignKey: 'userId' + } + } + } + }) + store.defineMapper('post', { + relations: { + belongsTo: { + user: { + localField: 'user', + foreignKey: 'userId' + } + } + } + }) + store.defineMapper('address', { + relations: { + belongsTo: { + user: { + localField: 'user', + foreignKey: 'userId' + } + } + } + }) + + setTimeout(function () { + Test.requests[0].respond(200, { 'Content-Type': 'application/json' }, JSON.stringify({ + id: 1, + posts: [ + { + id: 2, + userId: 1 + } + ] + })) + }, 30) + + return store.update('user', 1, { + id: 1, + posts: [ + { + id: 2, + userId: 1 + } + ], + addresses: [ + { + id: 3, + userId: 1 + } + ] + }, { with: ['posts'] }) + .then(function (data) { + Test.assert.equal(1, Test.requests.length) + Test.assert.equal(Test.requests[0].url, 'user/1') + Test.assert.equal(Test.requests[0].method, 'PUT') + Test.assert.equal(Test.requests[0].requestBody, JSON.stringify({ + id: 1, + posts: [ + { + id: 2, + userId: 1 + } + ] + })) + Test.assert.deepEqual(data, { + id: 1, + posts: [ + { + id: 2, + userId: 1 + } + ] + }) + }) + }) +}) diff --git a/pool/shard001/JavaScript/0006004_REPL.js b/pool/shard001/JavaScript/0006004_REPL.js new file mode 100644 index 0000000000000000000000000000000000000000..0afc7b5b645f52b5f5c587767b644089fb114bd3 --- /dev/null +++ b/pool/shard001/JavaScript/0006004_REPL.js @@ -0,0 +1,143 @@ +smalltalk.addPackage('REPL', {}); +smalltalk.addClass('Repl', smalltalk.Object, ['readline', 'interface', 'util'], 'REPL'); +smalltalk.addMethod( +"_close", +smalltalk.method({ +selector: "close", +category: 'actions', +fn: function (){ +var self=this; +smalltalk.send(smalltalk.send(process,"_stdin",[]),"_destroy",[]); +return self}, +args: [], +source: "close\x0a\x09process stdin destroy", +messageSends: ["destroy", "stdin"], +referencedClasses: [] +}), +smalltalk.Repl); + +smalltalk.addMethod( +"_createInterface", +smalltalk.method({ +selector: "createInterface", +category: 'actions', +fn: function (){ +var self=this; +self["@interface"]=smalltalk.send(self["@readline"],"_createInterface_stdout_",[smalltalk.send(process,"_stdin",[]),smalltalk.send(process,"_stdout",[])]); +smalltalk.send(self["@interface"],"_on_do_",["line",(function(buffer){ +return smalltalk.send(self,"_eval_",[buffer]); +})]); +smalltalk.send(self["@interface"],"_on_do_",["close",(function(){ +return smalltalk.send(self,"_close",[]); +})]); +smalltalk.send(self,"_setPrompt",[]); +smalltalk.send(self["@interface"],"_prompt",[]); +return self}, +args: [], +source: "createInterface\x0a\x09\x22No completion for now\x22\x0a\x09interface := readline createInterface: process stdin stdout: process stdout.\x0a\x09interface on: 'line' do: [:buffer | self eval: buffer].\x0a\x09interface on: 'close' do: [self close].\x0a\x09self setPrompt.\x0a\x09interface prompt", +messageSends: ["createInterface:stdout:", "stdin", "stdout", "on:do:", "eval:", "close", "setPrompt", "prompt"], +referencedClasses: [] +}), +smalltalk.Repl); + +smalltalk.addMethod( +"_eval_", +smalltalk.method({ +selector: "eval:", +category: 'actions', +fn: function (buffer){ +var self=this; +var $1,$2; +var result; +$1=smalltalk.send(buffer,"_isEmpty",[]); +if(! smalltalk.assert($1)){ +smalltalk.send(self,"_try_catch_",[(function(){ +result=smalltalk.send(smalltalk.send((smalltalk.Compiler || Compiler),"_new",[]),"_evaluateExpression_",[buffer]); +result; +return smalltalk.send((smalltalk.Transcript || Transcript),"_show_",[result]); +}),(function(e){ +$2=smalltalk.send(e,"_isSmalltalkError",[]); +if(smalltalk.assert($2)){ +return smalltalk.send(smalltalk.send((smalltalk.ErrorHandler || ErrorHandler),"_new",[]),"_handleError_",[e]); +} else { +return smalltalk.send(smalltalk.send(process,"_stdout",[]),"_write_",[smalltalk.send(e,"_jsStack",[])]); +}; +})]); +}; +smalltalk.send(self["@interface"],"_prompt",[]); +return self}, +args: ["buffer"], +source: "eval: buffer\x0a\x09| result |\x0a\x09buffer isEmpty ifFalse: [\x0a\x09\x09self try: [\x0a\x09\x09\x09result := Compiler new evaluateExpression: buffer.\x0a\x09\x09\x09Transcript show: result]\x0a\x09\x09catch: [:e |\x0a\x09\x09\x09e isSmalltalkError\x0a\x09\x09\x09 ifTrue: [ErrorHandler new handleError: e]\x0a\x09\x09\x09 ifFalse: [process stdout write: e jsStack]]].\x0a\x09interface prompt", +messageSends: ["ifFalse:", "try:catch:", "evaluateExpression:", "new", "show:", "ifTrue:ifFalse:", "handleError:", "write:", "jsStack", "stdout", "isSmalltalkError", "isEmpty", "prompt"], +referencedClasses: ["Compiler", "Transcript", "ErrorHandler"] +}), +smalltalk.Repl); + +smalltalk.addMethod( +"_initialize", +smalltalk.method({ +selector: "initialize", +category: 'initialization', +fn: function (){ +var self=this; +smalltalk.send(self,"_initialize",[],smalltalk.Object); +self["@readline"]=smalltalk.send(require,"_value_",["readline"]); +self["@util"]=smalltalk.send(require,"_value_",["util"]); +return self}, +args: [], +source: "initialize\x0a\x09super initialize.\x0a\x09readline := require value: 'readline'.\x0a\x09util := require value: 'util'", +messageSends: ["initialize", "value:"], +referencedClasses: [] +}), +smalltalk.Repl); + +smalltalk.addMethod( +"_prompt", +smalltalk.method({ +selector: "prompt", +category: 'accessing', +fn: function (){ +var self=this; +return "amber >> "; +}, +args: [], +source: "prompt\x0a\x09^'amber >> '", +messageSends: [], +referencedClasses: [] +}), +smalltalk.Repl); + +smalltalk.addMethod( +"_setPrompt", +smalltalk.method({ +selector: "setPrompt", +category: 'actions', +fn: function (){ +var self=this; +smalltalk.send(self["@interface"],"_setPrompt_",[smalltalk.send(self,"_prompt",[])]); +return self}, +args: [], +source: "setPrompt\x0a\x09interface setPrompt: self prompt", +messageSends: ["setPrompt:", "prompt"], +referencedClasses: [] +}), +smalltalk.Repl); + + +smalltalk.addMethod( +"_main", +smalltalk.method({ +selector: "main", +category: 'not yet classified', +fn: function (){ +var self=this; +smalltalk.send(smalltalk.send(self,"_new",[]),"_createInterface",[]); +return self}, +args: [], +source: "main\x0a\x09self new createInterface", +messageSends: ["createInterface", "new"], +referencedClasses: [] +}), +smalltalk.Repl.klass); + + diff --git a/pool/shard001/JavaScript/0006005_list-albums.client.controller.tests.js b/pool/shard001/JavaScript/0006005_list-albums.client.controller.tests.js new file mode 100644 index 0000000000000000000000000000000000000000..e3e9c232b728beeb2defd48ca6eb1acf8c890cfd --- /dev/null +++ b/pool/shard001/JavaScript/0006005_list-albums.client.controller.tests.js @@ -0,0 +1,91 @@ +(function () { + 'use strict'; + + describe('Albums List Controller Tests', function () { + // Initialize global variables + var AlbumsListController, + $scope, + $httpBackend, + $state, + Authentication, + AlbumsService, + mockAlbum; + + // The $resource service augments the response object with methods for updating and deleting the resource. + // If we were to use the standard toEqual matcher, our tests would fail because the test values would not match + // the responses exactly. To solve the problem, we define a new toEqualData Jasmine matcher. + // When the toEqualData matcher compares two objects, it takes only object properties into + // account and ignores methods. + beforeEach(function () { + jasmine.addMatchers({ + toEqualData: function (util, customEqualityTesters) { + return { + compare: function (actual, expected) { + return { + pass: angular.equals(actual, expected) + }; + } + }; + } + }); + }); + + // Then we can start by loading the main application module + beforeEach(module(ApplicationConfiguration.applicationModuleName)); + + // The injector ignores leading and trailing underscores here (i.e. _$httpBackend_). + // This allows us to inject a service but then attach it to a variable + // with the same name as the service. + beforeEach(inject(function ($controller, $rootScope, _$state_, _$httpBackend_, _Authentication_, _AlbumsService_) { + // Set a new global scope + $scope = $rootScope.$new(); + + // Point global variables to injected services + $httpBackend = _$httpBackend_; + $state = _$state_; + Authentication = _Authentication_; + AlbumsService = _AlbumsService_; + + // create mock article + mockAlbum = new AlbumsService({ + _id: '525a8422f6d0f87f0e407a33', + name: 'Album Name' + }); + + // Mock logged in user + Authentication.user = { + roles: ['user'] + }; + + // Initialize the Albums List controller. + AlbumsListController = $controller('AlbumsListController as vm', { + $scope: $scope + }); + + //Spy on state go + spyOn($state, 'go'); + })); + + describe('Instantiate', function () { + var mockAlbumList; + + beforeEach(function () { + mockAlbumList = [mockAlbum, mockAlbum]; + }); + + it('should send a GET request and return all Albums', inject(function (AlbumsService) { + // Set POST response + $httpBackend.expectGET('api/albums').respond(mockAlbumList); + + + $httpBackend.flush(); + + // Test form inputs are reset + expect($scope.vm.albums.length).toEqual(2); + expect($scope.vm.albums[0]).toEqual(mockAlbum); + expect($scope.vm.albums[1]).toEqual(mockAlbum); + + })); + }); + }); +})(); diff --git a/pool/shard001/JavaScript/0006006_interfase.js b/pool/shard001/JavaScript/0006006_interfase.js new file mode 100644 index 0000000000000000000000000000000000000000..77e1dce97e0cf1e3a807053cccd6e472fe4ed31e --- /dev/null +++ b/pool/shard001/JavaScript/0006006_interfase.js @@ -0,0 +1,285 @@ +/** + * @param {object} event The event descriptor + * @param {number} time The simulation time, in minutes + * @return {number} The glucose effect, in mg/dL + */ +function eventEffectAtTime(event, time) { + if(event.etype=="carb") { + return deltaBGC(time - event.time, userdata.sensf, userdata.cratio, event.grams, event.ctype) + } else if(event.etype=="bolus") { + return deltaBGI(time - event.time, event.units, userdata.sensf, userdata.idur) + } else { + return deltatempBGI(time, event.dbdt, userdata.sensf, userdata.idur, event.t1, event.t2); + } +} + +// Function to load the Graph everytime any setting is changed +function reloadGraphData() { + + var simt = userdata.simlength*60; + var dt=simt/n; + + for (i=0;i" + event.grams + " gr of carbs (" + event.ctype + " min absorption time)"; + description_b = "Taken @ min "+ event.time +"" + } else if(event.etype=="bolus") { + description = "" + event.units + " U insulin input"; + description_b = "Taken @ min "+ event.time +"" + } else if (event.etype=="tempbasal") { + description = "" + event.dbdt + " U/min temp basal input"; + description_b = "From min "+ event.t1 +" to min "+ event.t2 +"" + } + + var row = document.createElement("div"); + row.id = "uevent_" + event_id; + row.className = "row"; + row.innerHTML = "
" + description + "
" + description_b + "
"; + document.getElementById("input_history").appendChild(row); + + document.getElementById("input_history_container").classList.remove("hidden"); + +} + +// Document Ready +document.addEventListener('readystatechange', function() { + reloadGraphData(); + + window.addEventListener('resize', function() { + reloadGraphData() + }) +}); diff --git a/pool/shard001/JavaScript/0006007_multipart.test.js b/pool/shard001/JavaScript/0006007_multipart.test.js new file mode 100644 index 0000000000000000000000000000000000000000..a6b40c3bec32c0f87704368acef35ed2b1a340ca --- /dev/null +++ b/pool/shard001/JavaScript/0006007_multipart.test.js @@ -0,0 +1,64 @@ +'use strict'; + +const request = require('supertest'); +const assert = require('assert'); +const formstream = require('formstream'); +const urllib = require('urllib'); +const utils = require('../../utils'); + +describe('test/lib/plugins/multipart.test.js', () => { + let app; + let csrfToken; + let cookies; + let host; + let server; + before(() => { + app = utils.app('apps/multipart'); + return app.ready(); + }); + before(done => { + server = app.listen(); + request(server) + .get('/') + .expect(200, (err, res) => { + csrfToken = res.headers['x-csrf']; + cookies = res.headers['set-cookie'].join(';'); + host = `http://127.0.0.1:${server.address().port}`; + done(err); + }); + }); + + after(() => { + server.close(); + return app.close(); + }); + + it('should upload with csrf', done => { + const form = formstream(); + // form.file('file', filepath, filename); + form.file('file', __filename); + // other form fields + form.field('foo', 'fengmk2').field('love', 'egg'); + // https://snyk.io/vuln/npm:qs:20170213 + form.field('[', 'toString'); + + const headers = form.headers(); + headers.Cookie = cookies; + urllib.request(`${host}/upload?_csrf=${csrfToken}`, { + method: 'POST', + headers, + stream: form, + }, (err, body, res) => { + assert(!err); + assert(res.statusCode === 200); + const data = JSON.parse(body); + assert(data.filename === 'multipart.test.js'); + assert.deepEqual(data.fields, { + foo: 'fengmk2', + love: 'egg', + '[': 'toString', + }); + done(); + }); + }); +}); diff --git a/pool/shard001/JavaScript/0006010_view.js b/pool/shard001/JavaScript/0006010_view.js new file mode 100644 index 0000000000000000000000000000000000000000..7dbb4730f93cd0082bf7f2eb50b7f79b00687141 --- /dev/null +++ b/pool/shard001/JavaScript/0006010_view.js @@ -0,0 +1,170 @@ +/************************************************************************ + * This file is part of EspoCRM. + * + * EspoCRM - Open Source CRM application. + * Copyright (C) 2014-2015 Yuri Kuznetsov, Taras Machyshyn, Oleksiy Avramenko + * Website: http://www.espocrm.com + * + * EspoCRM 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. + * + * EspoCRM 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 EspoCRM. If not, see http://www.gnu.org/licenses/. + ************************************************************************/ +Espo.define('view', [], function () { + + return Bull.View.extend({ + + addActionHandler: function (action, handler) { + this.events = this.events || {}; + + var fullAction = 'click button[data-action=\"'+action+'\"]'; + this.events[fullAction] = handler; + }, + + notify: function (label, type, timeout, scope) { + if (label == false) { + Espo.Ui.notify(false); + return; + } + scope = scope || null; + timeout = timeout || 2000; + if (!type) { + timeout = null; + } + var text = this.getLanguage().translate(label, 'labels', scope); + Espo.Ui.notify(text, type, timeout); + }, + + reRender: function () { + if (this.isRendered()) { + this.render(); + } else if (this.isBeingRendered()) { + this.once('after:render', function () { + this.render(); + }, this); + } + }, + + getHelper: function () { + return this._helper; + }, + + getUser: function () { + if (this._helper) { + return this._helper.user; + } + }, + + getPreferences: function () { + if (this._helper) { + return this._helper.preferences; + } + }, + + getConfig: function () { + if (this._helper) { + return this._helper.settings; + } + }, + + getAcl: function () { + if (this._helper) { + return this._helper.acl; + } + }, + + getModelFactory: function () { + if (this._helper) { + return this._helper.modelFactory; + } + }, + + getCollectionFactory: function () { + if (this._helper) { + return this._helper.collectionFactory; + } + }, + + getRouter: function () { + if (this._helper) { + return this._helper.router; + } + }, + + getStorage: function () { + if (this._helper) { + return this._helper.storage; + } + }, + + getLanguage: function () { + if (this._helper) { + return this._helper.language; + } + }, + + getMetadata: function () { + if (this._helper) { + return this._helper.metadata; + } + }, + + getCache: function () { + if (this._helper) { + return this._helper.cache; + } + }, + + getStorage: function () { + if (this._helper) { + return this._helper.storage; + } + }, + + getDateTime: function () { + if (this._helper) { + return this._helper.dateTime; + } + }, + + getFieldManager: function () { + if (this._helper) { + return this._helper.fieldManager; + } + }, + + getBaseController: function () { + if (this._helper) { + return this._helper.baseController; + } + }, + + getThemeManager: function () { + if (this._helper) { + return this._helper.themeManager; + } + }, + + updatePageTitle: function () { + var title = this.getConfig().get('applicationTitle') || 'EspoCRM'; + this.setPageTitle(title); + }, + + setPageTitle: function (title) { + $('head title').text(title); + }, + + translate: function (label, category, scope) { + return this.getLanguage().translate(label, category, scope); + }, + }); + +}); diff --git a/pool/shard001/JavaScript/0006015_routes.js b/pool/shard001/JavaScript/0006015_routes.js new file mode 100644 index 0000000000000000000000000000000000000000..3b34cddf93ad135f991aa288d0e869d051b51a4a --- /dev/null +++ b/pool/shard001/JavaScript/0006015_routes.js @@ -0,0 +1,14 @@ +module.exports = function (app) { + app.all('/*', function (req, res, next) { + var arbitraryUrls = ['partials', 'api']; + if (arbitraryUrls.indexOf(req.url.split('/')[1]) > -1) { + next(); + } else { + res.render('layout'); + } + }); + + app.get('/partials/*', function (req, res, next) { + res.render('.' + req.path, { title: 'Fakedata.org' }); + }); +}; \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006016_main.js b/pool/shard001/JavaScript/0006016_main.js new file mode 100644 index 0000000000000000000000000000000000000000..130a91d566325896577d191c6fd670b0b315c2e8 --- /dev/null +++ b/pool/shard001/JavaScript/0006016_main.js @@ -0,0 +1,325 @@ +/** + * @file 路由管理 + * @author treelite(c.xinle@gmail.com) + */ + +define(function (require) { + + var extend = require('saber-lang/extend'); + var globalConfig = require('./config'); + var controller = require('./controller'); + + /** + * 路由规则 + * + * @type {Array.} + */ + var rules = []; + + /** + * 判断是否已存在路由处理器 + * + * @inner + * @param {string|RegExp} path 路径 + * @return {number} + */ + function indexOfHandler(path) { + var index = -1; + + path = path.toString(); + rules.some(function (item, i) { + // toString是为了判断正则是否相等 + if (item.raw.toString() === path) { + index = i; + } + return index !== -1; + }); + + return index; + } + + /** + * 从path中获取query + * 针对正则表达式的规则 + * + * @inner + * @param {string} path 路径 + * @param {Object} item 路由信息 + * @return {Object} + */ + function getParamsFromPath(path, item) { + var res = {}; + var names = item.params || []; + var params = path.match(item.path) || []; + + for (var i = 1, name; i < params.length; i++) { + name = names[i - 1] || '$' + i; + res[name] = decodeURIComponent(params[i]); + } + + return res; + } + + /** + * 是否正在等待处理器执行 + * + * @type {boolean} + */ + var pending = false; + + /** + * 等待调用处理器的参数 + * + * @type {!Object} + */ + var waitingRoute; + + /** + * 根据URL调用处理器 + * + * @inner + * @param {URL} url url对象 + * @param {Object=} options 参数 + * @param {string=} options.title 页面标题 + */ + function apply(url, options) { + options = options || {}; + + // 只保存最后一次的待调用信息 + if (pending) { + waitingRoute = { + url: url, + options: options + }; + return; + } + + function finish() { + pending = false; + if (waitingRoute) { + var route = extend({}, waitingRoute); + waitingRoute = null; + apply(route.url, route.options); + } + } + + pending = true; + + var handler; + var defHandler; + var query = extend({}, url.getQuery()); + var params = {}; + var path = url.getPath(); + + rules.some(function (item) { + if (item.path instanceof RegExp) { + if (item.path.test(path)) { + handler = item; + params = getParamsFromPath(path, item); + } + } + else if (url.equalPath(item.path)) { + handler = item; + } + + if (!item.path) { + defHandler = item; + } + + return !!handler; + }); + + handler = handler || defHandler; + + + if (!handler) { + waitingRoute = null; + pending = false; + throw new Error('can not found route for: ' + path); + } + + if (options.title) { + document.title = options.title; + } + + var args = [path, query, params, url.toString(), options]; + if (handler.fn.length > args.length) { + args.push(finish); + handler.fn.apply(handler.thisArg, args); + } + else { + handler.fn.apply(handler.thisArg, args); + finish(); + } + } + + /** + * 处理RESTful风格的路径 + * 使用正则表达式 + * + * @inner + * @param {string} path 路径 + * @return {Object} + */ + function restful(path) { + var res = { + params: [] + }; + + res.path = path.replace(/:([^/]+)/g, function ($0, $1) { + res.params.push($1); + return '([^/]+)'; + }); + + res.path = new RegExp(res.path + '$'); + + return res; + } + + /** + * 添加路由规则 + * + * @inner + * @param {string} path 路径 + * @param {Function} fn 路由处理函数 + * @param {Object} thisArg 路由处理函数的this指针 + */ + function addRule(path, fn, thisArg) { + var rule = { + raw: path, + path: path, + fn: fn, + thisArg: thisArg + }; + + if (!(path instanceof RegExp) + && path.indexOf(':') >= 0 + ) { + rule = extend(rule, restful(path)); + } + + rules.push(rule); + } + + var exports = {}; + + /** + * 重置当前的URL + * + * @public + * @param {string} url 路径 + * @param {Object=} query 查询条件 + * @param {Object=} options 选项 + * @param {boolean=} options.silent 是否静默重置,静默重置只重置URL,不加载action + */ + exports.reset = function (url, query, options) { + controller.reset(url, query, options); + }; + + /** + * 设置配置信息 + * + * @public + * @param {Object} options 配置信息 + * @param {string=} options.path 默认路径 + * @param {string=} options.index index文件名称 + */ + exports.config = function (options) { + options = options || {}; + // 修正root,添加头部的`/`并去掉末尾的'/' + var root = options.root; + if (root && root.charAt(root.length - 1) === '/') { + root = options.root = root.substring(0, root.length - 1); + } + if (root && root.charAt(0) !== '/') { + options.root = '/' + root; + } + extend(globalConfig, options); + }; + + /** + * 添加路由规则 + * + * @public + * @param {string|RegExp=} path 路径 + * @param {function(path, query)} fn 路由处理函数 + * @param {Object=} thisArg 路由处理函数的this指针 + */ + exports.add = function (path, fn, thisArg) { + if (indexOfHandler(path) >= 0) { + throw new Error('path has been existed'); + } + addRule(path, fn, thisArg); + }; + + /** + * 删除路由规则 + * + * @public + * @param {string} path 路径 + */ + exports.remove = function (path) { + var i = indexOfHandler(path); + if (i >= 0) { + rules.splice(i, 1); + } + }; + + /** + * 清除所有路由规则 + * + * @public + */ + exports.clear = function () { + rules = []; + }; + + /** + * URL跳转 + * + * @public + * @param {string} url 路径 + * @param {?Object} query 查询条件 + * @param {Object=} options 跳转参数 + * @param {string=} options.title 跳转后页面的title + * @param {boolean=} options.force 是否强制跳转 + * @param {boolean=} options.silent 是否静默跳转(不改变URL) + */ + exports.redirect = function (url, query, options) { + controller.redirect(url, query, options); + }; + + /** + * 启动路由监控 + * + * @public + * @param {Object} options 配置项 + */ + exports.start = function (options) { + exports.config(options); + controller.init(apply); + }; + + /** + * 停止路由监控 + * + * @public + */ + exports.stop = function () { + controller.dispose(); + exports.clear(); + waitingRoute = null; + }; + + /** + * 更换控制器 + * + * @public + * @param {Object} implement 路由控制器 + */ + exports.controller = function (implement) { + controller.plugin(implement); + }; + + return exports; +}); diff --git a/pool/shard001/JavaScript/0006018_routes.test.js b/pool/shard001/JavaScript/0006018_routes.test.js new file mode 100644 index 0000000000000000000000000000000000000000..c4c8a6d5b0171bf62d95ae9d1c9d65ab21624e7c --- /dev/null +++ b/pool/shard001/JavaScript/0006018_routes.test.js @@ -0,0 +1,100 @@ +import test from 'ava'; +import * as I from 'immutable'; +import * as td from 'testdouble'; +import { ensureLoggedIn, login } from './routes'; +import { push } from 'react-router-redux'; +import * as AuthActionCreators from '../action-creators/auth'; + +test('"ensureLoggedIn" should redirect the user to "/", if the token does not exist', () => { + const session = I.Map({}); + const dispatch = td.function(); + const store = { + getState: () => ({ session }), + dispatch, + }; + ensureLoggedIn(store); + td.verify(dispatch(push('/'))); +}); + +test('"ensureLoggedIn" should do no redirects, if the token exists', (assert) => { + const session = I.Map({ token: '123' }); + const dispatch = td.function(); + const store = { + getState: () => ({ session }), + dispatch, + }; + ensureLoggedIn(store); + assert.throws(() => td.verify(dispatch(td.matchers.anything()))); +}); + +test('"login" should save user token and name, if they exist in the querystring', () => { + const accessToken = '1234'; + const firstName = 'John'; + const lastName = 'Doe'; + const displayName = `${firstName} ${lastName}`; + const state = { + routing: { + locationBeforeTransitions: { + query: { + access_token: accessToken, + display_name: displayName, + }, + }, + }, + }; + + const store = { + getState: () => state, + dispatch: td.function(), + }; + + login(store); + + td.verify(store.dispatch(AuthActionCreators.loginUser({ firstName, lastName }, accessToken))); +}); + +test('"login" should redirect to "/", if token doesn\'t exist in querystring', () => { + const firstName = 'John'; + const lastName = 'Doe'; + const displayName = `${firstName} ${lastName}`; + const state = { + routing: { + locationBeforeTransitions: { + query: { + display_name: displayName, + }, + }, + }, + }; + + const store = { + getState: () => state, + dispatch: td.function(), + }; + + login(store); + + td.verify(store.dispatch(push('/'))); +}); + +test('"login" should redirect to "/", if "displayName" doesn\'t exist in querystring', () => { + const accessToken = '123'; + const state = { + routing: { + locationBeforeTransitions: { + query: { + access_token: accessToken, + }, + }, + }, + }; + + const store = { + getState: () => state, + dispatch: td.function(), + }; + + login(store); + + td.verify(store.dispatch(push('/'))); +}); diff --git a/pool/shard001/JavaScript/0006024_componentAdder.js b/pool/shard001/JavaScript/0006024_componentAdder.js new file mode 100644 index 0000000000000000000000000000000000000000..6a04168f3d569377c40a7ecaaae8a6bd99bd0499 --- /dev/null +++ b/pool/shard001/JavaScript/0006024_componentAdder.js @@ -0,0 +1,102 @@ + +__resources__["/componentAdder.js"] = {meta: {mimetype: "application/javascript"}, data: function(exports, require, module, __filename, __dirname) { + + var MouseButtonEventComponent = require('component').MouseButtonEventComponent; + var HoverEventComponent = require('component').HoverEventComponent; + var clientManager = require('clientManager'); + + /** + * add component to entity, such as mouseButtonEventComponent + */ + var ComponentAdder = function(opts){ + var area = opts.area; + this.addComponent = function(){ + addClickComponent(area); + }; + + this.addComponentTo = function(entity) { + addComponentToEntity(area, entity); + }; + }; + + /** + * add clickComponet to map + */ + var addClickComponent = function(area) { + var clickComponentPlayer = new MouseButtonEventComponent({ + pipe: area.gLevel.sysPipe(), + decider: area.scene.queryDecider('mouseButtonDecider'), + callback: move.bind(null, area) + }); + + area.map.node.addComponent('mouseButtonEventComponent', clickComponentPlayer); + }; + + var move = function(area, event) { + var player = area.getCurPlayer(); + var sprite = player.getSprite(); + if (event.type === 'mousePressed'){ + var endX = event.mouseX - sprite.getMapPosition().x; + var endY = event.mouseY - sprite.getMapPosition().y; + var startX = sprite.getPosition().x; + var startY = sprite.getPosition().y; + var moveMessage = { + startX: startX, + startY: startY, + endX: endX, + endY: endY, + playerId: player.id, + areaId: area.id, + speed: sprite.entity.walkSpeed + }; + clientManager.move(moveMessage); + } + }; + + /** + * add mouseClick component to entity + */ + var addComponentToEntity = function(area, entity) { + //add mouseButtonEvent to entities + var clickComponentEntity = new MouseButtonEventComponent({ + pipe: area.gLevel.sysPipe(), + decider: area.scene.queryDecider('mouseButtonDecider'), + callback: launchAi + }); + var node = entity.getSprite().curNode; + node.addComponent('mouseButtonEventComponent', clickComponentEntity); + //add HoverEventComponent to entities + var hoverEventComponent = new HoverEventComponent({ + pipe: area.gLevel.sysPipe(), + decider: area.scene.queryDecider('hoverDecider'), + callback: hover + }); + node.addComponent('hoverEventComponent', hoverEventComponent); + }; + + /** + * Mouse hover handlerFunction + */ + var hover = function(event) { + var type = event.type; + var c = $('canvas'); + if (type == 'mouseOver') { + c.css('cursor', 'pointer'); + } else { + c.css('cursor', 'default'); + } + }; + + /** + * Mouse click handlerFunction + */ + var launchAi = function (event, node) { + var id = node.id; + if (event.type === 'mouseClicked') { + clientManager.launchAi({id: id}); + } + }; + + module.exports = ComponentAdder; +}}; + diff --git a/pool/shard001/JavaScript/0006025_onlineFeatures.js b/pool/shard001/JavaScript/0006025_onlineFeatures.js new file mode 100644 index 0000000000000000000000000000000000000000..0a91981ec2af98ae5e93fe0e53540accfd3d77f3 --- /dev/null +++ b/pool/shard001/JavaScript/0006025_onlineFeatures.js @@ -0,0 +1,83 @@ +var Clock = require('famous/core/Clock'); + +function OnlineFeatures (storage){ + this.isConnected = false; + this.storage = storage; +} + +OnlineFeatures.prototype.login = function login() { + try { + Cocoon + } catch (e) { + if(!Cocoon) throw new Error("No Cocoon!") + } + if(Cocoon.getPlatform() == 'ios') { + window.social = Cocoon.Social.GameCenter.init(); + window.social = Cocoon.Social.GameCenter.getSocialInterface(); + this.loggedIn = window.social.isLoggedIn(); + if (!window.social.isLoggedIn()) { + window.social.login(); + } + } +} + +OnlineFeatures.prototype.leaderboard = function() { + if (window.social){ + window.social.on("loginStatusChanged", function(loggedIn, error) { + if (this.loggedIn) { + window.social.requestScore(function(score, error) { + if (error) { + console.error("Error getting user score: " + error.message); + }else if (score) { + console.log("score: " + score.score); + window.localUserScore = score.score; + if(game.storage) window.localStorage.high_score = score.score + } + },{ + leaderboardID: "com.karaman.crossfire.highScore" + }); + } + }); + } + this.login(); +} + +OnlineFeatures.prototype.ads = function() { + if (typeof(Cocoon) != 'undefined' && Cocoon.getPlatform() == 'ios'){ + if(Cocoon.Ad.AdMob && game.interstitial){ + game.interstitial.show(); + } + } +} +OnlineFeatures.prototype.submitScore = function() { + if (typeof(Cocoon) != 'undefined' && Cocoon.getPlatform() == 'ios' + && window.social && window.social.isLoggedIn()) { + socialScore = window.localStorage.high_score; + if((window.localUserScore && window.localUserScore < window.localStorage.high_score) + || !window.localUserScore){ + window.social.submitScore(socialScore, function(error){ + if (error) console.error("submitScore error: " + error.message); + },{ + leaderboardID: "com.karaman.crossfire.highScore" + }); + } + } +} + + + + + +if(typeof(Cocoon) != 'undefined' && Cocoon.getPlatform() == 'ios' +&& Cocoon.Ad.AdMob){ + Cocoon.Ad.AdMob.configure({ + ios: { + banner:"ca-app-pub-4693632452063283/2829774253", + interstitial:"ca-app-pub-4693632452063283/4023645854" + } + }); + loadAndShowBannerAd(); + loadInterstitialAd(); +} + +module.exports = OnlineFeatures; diff --git a/pool/shard001/JavaScript/0006028_Tour.js b/pool/shard001/JavaScript/0006028_Tour.js new file mode 100644 index 0000000000000000000000000000000000000000..7d2b69cff7198c59ca40ee6bca0df345dfa74e78 --- /dev/null +++ b/pool/shard001/JavaScript/0006028_Tour.js @@ -0,0 +1,107 @@ +// Import React +import React from 'react'; + +// Import Spectacle Core tags +import { Deck, Heading, ListItem, List, Slide, Text, Appear } from 'spectacle'; + +import CodeSlide from 'spectacle-code-slide'; + +// Import image preloader util +import preloader from 'spectacle/lib/utils/preloader'; + +// Import theme +// import createTheme from "spectacle/lib/themes/default"; +import theme from '../themes/seattlejs/index.js'; + +// Require CSS +require('normalize.css'); +require('spectacle/lib/themes/default/index.css'); +require('../themes/seattlejs/index.css'); +// Best way to include fonts rite +require('../fonts/worksans.css'); +require('../fonts/biorhyme.css'); +require('../fonts/silkscreen.css'); + +// preloader(images); + +const extractRepoInfo = fullName => fullName.split('/'); + +export default class Tour extends React.Component { + render() { + const { loading, tour } = this.props; + + if (loading) { + return
Loading your tour...
; + } + + const { targetRepository, repository, description, steps } = tour; + + const [, targetName] = extractRepoInfo(targetRepository); + const [author] = extractRepoInfo(repository); + + return ( + + {/* welcome slide */} + + + {targetName} + + + {description} + + + {/* steps overview */} + + + Steps + + + {steps.map(({ title }) => + + {title} + + )} + + + {/* for each step, add a code slide with the title & code sections */} + {steps.map(({ title, speakerNotes, filePath, code, sections }) => [ + ({ + loc: [section.lineStart - 1, section.lineEnd], + note: section.slug, + notes: section.speakerNotes, + })), + ]} + notes={speakerNotes && speakerNotes+'?raw=true'} + />, + ])} + {/* conclusion slide */} + + + Recap + + + {steps.map(({ title }) => + + + {title} + + + )} + + + + ); + } +} diff --git a/pool/shard001/JavaScript/0006029_EditAdminForm-test.js b/pool/shard001/JavaScript/0006029_EditAdminForm-test.js new file mode 100644 index 0000000000000000000000000000000000000000..c3a0638f0b64c6b55e1c054d340cd2403a31de1c --- /dev/null +++ b/pool/shard001/JavaScript/0006029_EditAdminForm-test.js @@ -0,0 +1,75 @@ +import React from 'react'; +import { shallow } from 'enzyme'; + +import { EditAdminForm } from '../EditAdminForm'; + +describe('EditAdminForm', () => { + let submitSpy; + let rendered; + + beforeEach(() => { + submitSpy = jasmine.createSpy(); + rendered = shallow(); + }); + + it('calls handle submit when the form is submited', () => { + const form = rendered.find('form'); + form.simulate('submit'); + expect(submitSpy).toHaveBeenCalled(); + }); + + describe('when the admin is being created', () => { + it('renders an email field', () => { + rendered = shallow(); + const fields = rendered.find('Field'); + expect(fields.find({ name: 'email' }).length).toEqual(1); + }); + + it('renders a name field', () => { + rendered = shallow(); + const fields = rendered.find('Field'); + expect(fields.find({ name: 'name' }).length).toEqual(1); + }); + + it('renders a phoneNumber field', () => { + rendered = shallow(); + const fields = rendered.find('Field'); + expect(fields.find({ name: 'phoneNumber' }).length).toEqual(1); + }); + + it('renders a password field', () => { + rendered = shallow(); + const fields = rendered.find('Field'); + expect(fields.find({ name: 'password' }).length).toEqual(1); + }); + }); + + describe('when the admin is being updated', () => { + it('displays the email', () => { + rendered = shallow(); + const fields = rendered.find('Field'); + expect(fields.find({ name: 'email' }).length).toEqual(0); + expect(rendered.text()).toContain('some.email@email.com'); + }); + + it('renders a name field', () => { + rendered = shallow(); + const fields = rendered.find('Field'); + expect(fields.find({ name: 'name' }).length).toEqual(1); + }); + + it('renders a phoneNumber field', () => { + rendered = shallow(); + const fields = rendered.find('Field'); + expect(fields.find({ name: 'phoneNumber' }).length).toEqual(1); + }); + + it('renders a password field', () => { + rendered = shallow(); + const fields = rendered.find('Field'); + expect(fields.find({ name: 'password' }).length).toEqual(1); + }); + }); +}); diff --git a/pool/shard001/JavaScript/0006030_ColorInput.private.uni.driver.js b/pool/shard001/JavaScript/0006030_ColorInput.private.uni.driver.js new file mode 100644 index 0000000000000000000000000000000000000000..e879fedad5ca57846a144f26f013d5b2f6d3a7d7 --- /dev/null +++ b/pool/shard001/JavaScript/0006030_ColorInput.private.uni.driver.js @@ -0,0 +1,53 @@ +import { colorInputDriverFactory as publicDriverFactory } from './ColorInput.uni.driver'; +import { swatchesPrivateDriverFactory } from '../Swatches/test/Swatches.private.uni.driver'; +import DATA_HOOKS from './DataHooks'; +import inputUniDriverFactory from '../Input/Input.uni.driver'; +import { popoverDriverFactory } from '../Popover/Popover.uni.driver'; + +export const colorInputPrivateDriverFactory = (base, body) => { + const swatchesHook = `[data-hook="${DATA_HOOKS.COLOR_PICKER_SWATCHES}"]`; + const swatchesDriver = swatchesPrivateDriverFactory(base.$(swatchesHook)); + const colorViewerPopoverHook = `[data-hook="${DATA_HOOKS.COLOR_INPUT_POPOVER}"]`; + const colorViewerPopoverTestkit = popoverDriverFactory( + base.$(colorViewerPopoverHook), + body, + ); + + const isHashDisabled = async () => + (await base + .$(`[data-hook="${DATA_HOOKS.COLOR_INPUT_HASH}"]`) + .attr('data-disabled')) === 'true'; + + const getViewerSize = () => + base.$(`[data-hook="${DATA_HOOKS.COLOR_INPUT_VIEWER}"]`).attr('data-size'); + + const inputTestkit = inputUniDriverFactory(base); + + return { + ...publicDriverFactory(base, body), + isHashDisabled, + isViewerNull: async () => + await base + .$(`[data-hook="${DATA_HOOKS.COLOR_INPUT_VIEWER_LINE}"]`) + .exists(), + getViewerSize, + getSwatch: async index => swatchesDriver.getSwatch(index), + getSwatchCount: async () => swatchesDriver.getSwatchCount(), + /** Private Swatches driver function to test if swatch is transparent at given index */ + isSwatchTransparentAt: async index => + swatchesDriver.isSwatchTransparentAt(index), + keyDown: async event => { + if (typeof event === 'string') { + await inputTestkit.keyDown({ key: event }); + } else { + await inputTestkit.keyDown(event); + } + }, + blur: inputTestkit.blur, + focus: inputTestkit.focus, + clickOutside: async () => colorViewerPopoverTestkit.clickOutside(), + hasPrefix: inputTestkit.hasPrefix, + }; +}; + +export default colorInputPrivateDriverFactory; diff --git a/pool/shard001/JavaScript/0006031_SingleScrollViewport.js b/pool/shard001/JavaScript/0006031_SingleScrollViewport.js new file mode 100644 index 0000000000000000000000000000000000000000..db36f35022d9ab75a7ffa3b4e9b66a9d113771e6 --- /dev/null +++ b/pool/shard001/JavaScript/0006031_SingleScrollViewport.js @@ -0,0 +1,124 @@ +/** + * Copyright (C) 2010-2014 KO GmbH + * + * @licstart + * This file is part of WebODF. + * + * WebODF is free software: you can redistribute it and/or modify it + * under the terms of the GNU Affero General Public License (GNU AGPL) + * as published by the Free Software Foundation, either version 3 of + * the License, or (at your option) any later version. + * + * WebODF 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 WebODF. If not, see . + * @licend + * + * @source: http://www.webodf.org/ + * @source: https://github.com/kogmbh/WebODF/ + */ + +/*global gui*/ + +/** + * Viewport controller for a single scroll pane capable of scrolling either + * horizontally or vertically. + * + * @constructor + * @implements {gui.Viewport} + * @param {!HTMLElement} scrollPane + */ +gui.SingleScrollViewport = function(scrollPane) { + "use strict"; + var VIEW_PADDING_PX = 5; + + /** + * Pad the client rect with the supplied margin + * @param {!core.SimpleClientRect} clientRect + * @param {!core.SimpleClientRect} margin + * @return {!core.SimpleClientRect} + */ + function shrinkClientRectByMargin(clientRect, margin) { + return { + left: clientRect.left + margin.left, + top: clientRect.top + margin.top, + right: clientRect.right - margin.right, + bottom: clientRect.bottom - margin.bottom + }; + } + + /** + * @param {!core.SimpleClientRect} clientRect + * @return {!number} + */ + function height(clientRect) { + return clientRect.bottom - clientRect.top; + } + + /** + * @param {!core.SimpleClientRect} clientRect + * @return {!number} + */ + function width(clientRect) { + return clientRect.right - clientRect.left; + } + + /** + * @param {?core.SimpleClientRect} clientRect + * @param {!boolean=} alignWithTop + * @return {undefined} + */ + this.scrollIntoView = function(clientRect, alignWithTop) { + var verticalScrollbarHeight = scrollPane.offsetHeight - scrollPane.clientHeight, + horizontalScrollbarWidth = scrollPane.offsetWidth - scrollPane.clientWidth, + nonNullClientRect, + scrollPaneRect = scrollPane.getBoundingClientRect(), + /**@type{!core.SimpleClientRect}*/ + paneRect; + + if (!clientRect || !scrollPaneRect) { + return; + } + + nonNullClientRect = /**@type{!core.SimpleClientRect}*/(clientRect); + + // Visible area is slightly different from the BCR + // See https://developer.mozilla.org/en-US/docs/Web/API/CSS_Object_Model/Determining_the_dimensions_of_elements + paneRect = shrinkClientRectByMargin(/**@type{!core.SimpleClientRect}*/(scrollPaneRect), { + top: VIEW_PADDING_PX, + bottom: verticalScrollbarHeight + VIEW_PADDING_PX, + left: VIEW_PADDING_PX, + right: horizontalScrollbarWidth + VIEW_PADDING_PX + }); + + // Vertical adjustment + if (alignWithTop || nonNullClientRect.top < paneRect.top) { + // Scroll top down into view + scrollPane.scrollTop -= paneRect.top - nonNullClientRect.top; + } else if (nonNullClientRect.top > paneRect.bottom || nonNullClientRect.bottom > paneRect.bottom) { + // Scroll top *up* into view, potentially including bottom if possible + if (height(nonNullClientRect) <= height(paneRect)) { + // Whole region fits vertically on-screen, so scroll bottom into view + scrollPane.scrollTop += nonNullClientRect.bottom - paneRect.bottom; + } else { + // Only one end will fit on screen, so scroll the top as high as possible + scrollPane.scrollTop += nonNullClientRect.top - paneRect.top; + } + } + + // Horizontal adjustment - Logic mirrors vertical adjustment + if (nonNullClientRect.left < paneRect.left) { + scrollPane.scrollLeft -= paneRect.left - nonNullClientRect.left; + } else if (nonNullClientRect.right > paneRect.right) { + if (width(nonNullClientRect) <= width(paneRect)) { + scrollPane.scrollLeft += nonNullClientRect.right - paneRect.right; + } else { + scrollPane.scrollLeft -= paneRect.left - nonNullClientRect.left; + } + } + }; +}; \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006033_rcon.js b/pool/shard001/JavaScript/0006033_rcon.js new file mode 100644 index 0000000000000000000000000000000000000000..081ec80a670e5e5a8401c3006bf0ab721910f0b9 --- /dev/null +++ b/pool/shard001/JavaScript/0006033_rcon.js @@ -0,0 +1,122 @@ + +'use strict'; + +function flush() { + this.commands.forEach(function(command) { + this.client.write(Packet.encode(0x02, Protocol.REQ_ID+1, command)); + }, this); + this.commands = []; +} + +function dequeue(response) { + var callback = this.responseCallbacks.shift(); + if (typeof callback === 'function') { + callback(response); + } +} + +function connect() { + this.client = net.connect({ + host: this.host, + port: this.port + }, function() { + this.emit('connected'); + this.client.write(Packet.encode( + Protocol.SERVERDATA_AUTH, + Protocol.AUTH_ID, + this.password + )); + }.bind(this)); + + this.client.setTimeout(this.timeout); +} + +function listen() { + this.client.on('data', function(data) { + var res = Packet.decode(data); + switch(res.type) { + case Protocol.SERVERDATA_RESPONSE_VALUE: + if (this.authenticated) { + dequeue.call(this, res); + } + break; + case Protocol.SERVERDATA_AUTH_RESPONSE: + if (res.body !== '') { + return this.emit('error', 'Error: Invalid RCON password'); + } + this.authenticated = true; + this.emit('authenticated'); + if (this.execOnAuthenticated) flush.call(this); + break; + default: + this.emit('error', 'Error: Unknown server response'); + break; + } + }.bind(this)); + + this.client.on('timeout', this.client.end.bind(this.client)); + this.client.on('end', this.emit.bind(this, 'disconnected')); + + this.client.on('error', function(e) { + this.emit('error', e); + }.bind(this)); +} + +var net = require('net'), + EventEmitter = require('events').EventEmitter, + inherits = require('util').inherits, + Packet = require('./packet'), + Protocol = require('./protocol'); + +var Rcon = function(options) { + EventEmitter.call(this); + options = options || {}; + this.host = options.host || '127.0.0.1'; + this.port = options.port || '27015'; + this.password = options.password; + this.timeout = options.timeout || 5000; + + + // + // need a more succinct name for this option + this.execOnAuthenticated = options.execOnAuthenticated || true; + + + this.authenticated = false; + this.responseCallbacks = []; + this.commands = []; + + if (options.connect) { + connect.call(this); + listen.call(this); + } +}; + +inherits(Rcon, EventEmitter); + +Rcon.prototype.exec = function(command, callback) { + if (this.authenticated) { + this.client.write(Packet.encode(0x02, Protocol.REQ_ID, command)); + } else { + this.commands.push(command); + } + this.responseCallbacks.push(callback); + return this; +}; + +Rcon.prototype.connect = function() { + this.emit('connecting'); + if (!this.client) { + connect.call(this); + listen.call(this); + } + return this; +}; + +Rcon.prototype.close = function() { + this.emit('disconnecting'); + if (this.client) this.client.end(); + return this; +}; + +module.exports = Rcon; diff --git a/pool/shard001/JavaScript/0006036_mocha_test.js b/pool/shard001/JavaScript/0006036_mocha_test.js new file mode 100644 index 0000000000000000000000000000000000000000..09ab7c488cae51674af1c2b33f5fb7c4fc02568a --- /dev/null +++ b/pool/shard001/JavaScript/0006036_mocha_test.js @@ -0,0 +1,74 @@ +var gui = require('nw.gui'); +var path = require('path'); +var assert = require('assert'); +var fs = require('fs-extra'); +var curDir = fs.realpathSync('.'); + +describe('gui.App', function() { + + + var server, child, result = false; + + before(function(done) { + this.timeout(0); + server = createTCPServer(13013); + child = spawnChildProcess(path.join(curDir, 'internal')); + server.on('connection', function(socket) { + socket.setEncoding('utf8'); + socket.on('data', function(data) { + result = true; + child.kill(); + done(); + }); + }); + + setTimeout(function() { + if (!result) { + child.kill(); + done('timeout'); + } + }, 4500); + + }); + + after(function () { + server.close(); + }); + + + describe('manifest', function() { + it('`gui.App.manifest` should equle to value of package.json', function() { + assert.equal(gui.App.manifest.name, 'nw-gui.App-test.wrapper'); + }); + + it('have main', function() { + assert.equal(typeof gui.App.manifest.main, 'string'); + assert.equal(gui.App.manifest.main, 'index.html'); + }); + + + it('have window', function() { + console.log('====have window:' + typeof gui.App.manifest.window); + assert.equal(typeof gui.App.manifest.window, 'object'); + }); + + it('have dependencies', function() { + assert.equal(typeof gui.App.manifest.dependencies, 'object'); + }); + + }); + + describe('clearCache()', function(done) { + it('should clear the HTTP cache in memory and the one on disk', function() { + var res_save = global.local_server.res_save; + + assert.equal(res_save[1].status, 304); + assert.equal(res_save[1].pathname, 'img.jpg'); + assert.equal(res_save[2].status, 200); + assert.equal(res_save[2].pathname, 'img.jpg'); + }); + }); + +}); + + diff --git a/pool/shard001/JavaScript/0006038_toolbar-spec.js b/pool/shard001/JavaScript/0006038_toolbar-spec.js new file mode 100644 index 0000000000000000000000000000000000000000..a37b4dfaddbddc577a023438a5d5c0c881f22e3d --- /dev/null +++ b/pool/shard001/JavaScript/0006038_toolbar-spec.js @@ -0,0 +1,180 @@ +/* + * Copyright 2015-present Open Networking Laboratory + * + * 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. + */ + +/* + ONOS GUI -- Widget -- Toolbar Service - Unit Tests + */ +describe('factory: fw/widget/toolbar.js', function () { + var $log, fs, tbs, ps, bns, is; + + beforeEach(module('onosWidget', 'onosUtil', 'onosLayer', 'onosSvg')); + + beforeEach(inject(function (_$log_, FnService, ToolbarService, + PanelService, ButtonService, IconService) { + $log = _$log_; + fs = FnService; + tbs = ToolbarService; + ps = PanelService; + bns = ButtonService; + is = IconService; + })); + + beforeEach(function () { + // panel service expects #floatpanels div into which panels are placed + d3.select('body').append('div').attr('id', 'floatpanels'); + tbs.init(); + ps.init(); + }); + + afterEach(function () { + tbs.init(); + ps.init(); + d3.select('#floatpanels').remove(); + }); + + function nullFunc() { } + + it('should define ToolbarService', function () { + expect(tbs).toBeDefined(); + }); + + it('should define api functions', function () { + expect(fs.areFunctions(tbs, [ + 'init', + 'createToolbar', 'destroyToolbar' + ])).toBeTruthy(); + }); + + it('should warn when no id is given', function () { + spyOn($log, 'warn'); + expect(tbs.createToolbar()).toBeNull(); + expect($log.warn).toHaveBeenCalledWith('createToolbar: ' + + 'no ID given: [undefined]'); + }); + + it('should warn when a duplicate id is given', function () { + spyOn($log, 'warn'); + expect(tbs.createToolbar('test')).toBeTruthy(); + expect(tbs.createToolbar('test')).toBeNull(); + expect($log.warn).toHaveBeenCalledWith('createToolbar: ' + + 'duplicate ID given: [test]'); + }); + + it('should verify the toolbar arrow div exists', function () { + tbs.createToolbar('test'); + + // NOTE: toolbar service prefixes id with 'toolbar-' + var tbar = d3.select('#toolbar-test'), + arrow = tbar.select('.tbar-arrow'); + + expect(arrow.size()).toBe(1); + expect(arrow.select('svg').size()).toBe(1); + expect(arrow.select('svg').select('g').select('use') + .attr('xlink:href')).toEqual('#triangleUp'); + }); + + + it('should create a button', function () { + spyOn($log, 'warn'); + var toolbar = tbs.createToolbar('foo'), + btn = toolbar.addButton('btn0', 'gid'); + expect(btn).not.toBeNull(); + expect(btn.id).toBe('toolbar-foo-btn0'); + expect($log.warn).not.toHaveBeenCalled(); + }); + + it('should not create an item with a duplicate id', function () { + spyOn($log, 'warn'); + var toolbar = tbs.createToolbar('foo'), + btn = toolbar.addButton('btn0', 'gid'), + dup; + expect(btn).not.toBeNull(); + expect(btn.id).toBe('toolbar-foo-btn0'); + + dup = toolbar.addButton('btn0', 'gid'); + expect($log.warn).toHaveBeenCalledWith('addButton: duplicate ID:', 'btn0'); + expect(dup).toBeNull(); + + dup = toolbar.addToggle('btn0', 'gid'); + expect($log.warn).toHaveBeenCalledWith('addToggle: duplicate ID:', 'btn0'); + expect(dup).toBeNull(); + + dup = toolbar.addRadioSet('btn0', []); + expect($log.warn).toHaveBeenCalledWith('addRadioSet: duplicate ID:', 'btn0'); + expect(dup).toBeNull(); + }); + + it('should create a toggle', function () { + spyOn($log, 'warn'); + var toolbar = tbs.createToolbar('foo'), + tog = toolbar.addButton('tog0', 'gid'); + expect(tog).not.toBeNull(); + expect(tog.id).toBe('toolbar-foo-tog0'); + expect($log.warn).not.toHaveBeenCalled(); + }); + + it('should create a radio button set', function () { + spyOn($log, 'warn'); + var toolbar = tbs.createToolbar('foo'), + rset = [ + { gid: 'crown', cb: nullFunc, tooltip: 'A Crown' }, + { gid: 'bird', cb: nullFunc, tooltip: 'A Bird' } + ], + rad = toolbar.addRadioSet('rad0', rset); + expect(rad).not.toBeNull(); + expect(rad.selectedIndex()).toBe(0); + expect($log.warn).not.toHaveBeenCalled(); + }); + + it('should create a separator div', function () { + spyOn($log, 'warn'); + var toolbar = tbs.createToolbar('foo'), + tbar = d3.select('#toolbar-foo'); + + toolbar.addSeparator(); + expect($log.warn).not.toHaveBeenCalled(); + + expect(tbar.select('.separator').size()).toBe(1); + }); + + it('should add another row of buttons', function () { + var toolbar = tbs.createToolbar('foo'), + tbar = d3.select('#toolbar-foo'), + rows; + toolbar.addButton('btn0', 'gid'); + toolbar.addRow(); + toolbar.addButton('btn1', 'gid'); + + rows = tbar.selectAll('.tbar-row'); + expect(rows.size()).toBe(2); + rows.each(function (d, i) { + expect(d3.select(this) + .select('div') + .attr('id','toolbar-foo-btn' + i) + .empty()) + .toBe(false); + }); + }); + + it('should not add a row if current row is empty', function () { + var toolbar = tbs.createToolbar('foo'); + expect(toolbar.addRow()).toBeNull(); + toolbar.addButton('btn0', 'gid'); + expect(toolbar.addRow()).not.toBeNull(); + expect(toolbar.addRow()).toBeNull(); + }); + +}); diff --git a/pool/shard001/JavaScript/0006041_lw-metro-ui-pink.js b/pool/shard001/JavaScript/0006041_lw-metro-ui-pink.js new file mode 100644 index 0000000000000000000000000000000000000000..b809f3fdd84b687f839209624d52682f2fd62ce1 --- /dev/null +++ b/pool/shard001/JavaScript/0006041_lw-metro-ui-pink.js @@ -0,0 +1,37 @@ +(function($) { + $(document).ready(function(){ + $("body.home #content div.post, body.search #content div.post, body.archive #content div.post").mouseover(function() { + $(this).stop().animate({ backgroundColor: '#f3bfde', color: '#000000' },'fast'); + }).mouseout(function() { + $(this).stop().animate({ backgroundColor: '#1C1C1C', color: '#999999'},'fast'); + }); + + $("body.home #content div.post, body.search #content div.post, body.archive #content div.post").click(function(){ + window.location=$(this).find("h2 a").attr("href"); + return false; + }); + + $("div.nav-previous, div.nav-next").click(function(){ + window.location=$(this).find("a").attr("href"); + return false; + }); + + $("div.nav-previous, div.nav-next").mouseover(function(){ + $(this).find("a").css({'text-decoration' : 'underline'}); + }).mouseout(function() { + $(this).find("a").css({'text-decoration' : 'none'}); + }); + + $("ul.ctc-tag-cloud li").mouseover(function(){ + $(this).find("a").css({'color' : '#1C1C1C'}); + }).mouseout(function() { + $(this).find("a").css({'color' : '#FFFFFF'}); + }); + + $("ul.ctc-tag-cloud li").click(function(){ + window.location=$(this).find("a").attr("href"); + return false; + }); + + }); +})(jQuery); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006044_v8test.js b/pool/shard001/JavaScript/0006044_v8test.js new file mode 100644 index 0000000000000000000000000000000000000000..5287ab0e9a34ba3b6318cd491de159c47d03e163 --- /dev/null +++ b/pool/shard001/JavaScript/0006044_v8test.js @@ -0,0 +1,33 @@ +'use strict'; + +const Router = require('koa-router'); +const koabody = require('koa-body')(); +const fs = require('fs'); +const profiler = require('v8-profiler'); +profiler.startProfiling('', true); +console.log('start') +setTimeout(() => { + console.log('stop'); + let result = profiler.stopProfiling(''); + fs.writeFileSync('./node.cpu.json', JSON.stringify(result)); + result.delete(); +}, 60 * 1000); +let testTryCatch = (req, res) => { + try { + res.end('tryCatchStatement success!'); + } catch (e) { + res.end('tryCatchStatement ' + e.message); + } +} +let testSleep = (req, res) => { + const now = Date.now(); + while (Date.now() - now < 200) {} + res.end('testSleep success'); +} +let router = new Router(); +router.get('/test', koabody, async (ctx, next) => { + testTryCatch(ctx.req, ctx.res); + testSleep(ctx.req, ctx.res); +}) + +module.exports = router; \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006051_Gruntfile.js b/pool/shard001/JavaScript/0006051_Gruntfile.js new file mode 100644 index 0000000000000000000000000000000000000000..7436766ad82bc96e751dfca24e94589f753c743c --- /dev/null +++ b/pool/shard001/JavaScript/0006051_Gruntfile.js @@ -0,0 +1,31 @@ +require('babel-register'); +process.traceDeprecation = true; + +module.exports = function (grunt) { + // Load per-task config from separate files in folder '/grunt'. + grunt.loadTasks('grunt'); + + // QA + grunt.registerTask('unit', ['mochaTest:build']); + grunt.registerTask('hint', ['eslint']); + grunt.registerTask('test', ['continue:on', 'hint', 'unit', 'continue:off']); + + // Build + grunt.registerTask('git', ['githash', 'json_generator']); + grunt.registerTask('build:dev', ['webpack:dev']); + grunt.registerTask('build:prod', ['webpack:build']); + + // migration + grunt.registerTask('migrate', ['execute:migration']); + + // target for production after deployment + grunt.registerTask('postinstall', ['copy:build', 'build:prod']); + + // dev -> monitor changes and restart + grunt.registerTask('monitor', ['nodemon:build']); + // dev -> build and monitor parallel for local development without a docker container + grunt.registerTask('startDev', ['migrate', 'git', 'concurrent:buildAndRun']); + + // default -> test + grunt.registerTask('default', ['test', 'watch:test']); +}; diff --git a/pool/shard001/JavaScript/0006052_app.js b/pool/shard001/JavaScript/0006052_app.js new file mode 100644 index 0000000000000000000000000000000000000000..3308e19d88816397658afaaca375c6dbbeff6b5a --- /dev/null +++ b/pool/shard001/JavaScript/0006052_app.js @@ -0,0 +1,24 @@ +const express = require('express'); +const bodyParser = require('body-parser'); +const app = express(); +const PORT = '' || 3000; +const router = require('./router/router.js'); +const dirRouter = require('./router/dir-router.js'); + +// 设置静态资源路径 +app.use('/public',express.static('./public')); +// 设置 模板引擎为ejs +app.set('view engine','ejs'); + +app.use('/home',router); +app.use('/dir',dirRouter); + +app.use((err,req,res,next) => { + res.render('404'); + next(); +}); + + +app.listen(PORT,() => { + console.log('listening port : ' + PORT); +}); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006056_MaterialLoader.js b/pool/shard001/JavaScript/0006056_MaterialLoader.js new file mode 100644 index 0000000000000000000000000000000000000000..98192edecd7472b1a2012926df1d32e743a9271f --- /dev/null +++ b/pool/shard001/JavaScript/0006056_MaterialLoader.js @@ -0,0 +1,35 @@ +import React from 'react' + +import { Link } from 'react-router' + +var material = require("./material.json"); +var renderers = {"multiple choice": require("./activities/MultipleChoiceRenderer")}; + +for(var grade in material.grades) { + var gradeData = material.grades[grade].exercises; + for(var i=0; i + {result} + + ) + } +}) + +module.exports = MaterialLoader \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006058_addFolderByCsv.js b/pool/shard001/JavaScript/0006058_addFolderByCsv.js new file mode 100644 index 0000000000000000000000000000000000000000..38748040bdfe3b44459db764f173c485fc6dcdd4 --- /dev/null +++ b/pool/shard001/JavaScript/0006058_addFolderByCsv.js @@ -0,0 +1,174 @@ +import {dialog} from 'electron'; +import {isEmpty, first} from 'lodash'; +import csv from 'fast-csv'; +import fs from 'fs'; +import {basename} from 'path'; +import log from 'karmapa-log'; +import shortid from 'shortid'; + +import csvProcessor, {FIELD_PAGE_NUM} from './../../utils/csvProcessor'; +import pageNumToFloat from './../../utils/pageNumToFloat'; +import FRACTION_LENGTH from './../../constants/fractionLength'; +import now from './../../utils/now'; +import Reporter from './../../utils/Reporter'; + +const reportDuration = 1000; +const reporter = new Reporter(); + +const numberConcurrentWrite = 50000; +const dialogOptions = { + properties: ['openFile'], + filters: [ + {name: 'Csv Files', extensions: ['csv']} + ] +}; + +export default async function addFolderByCsv(event, data) { + + const {models, importEmitter, db} = this.params; + const {Folder} = models; + const {broadcast, resolve, reject} = this; + + dialog.showOpenDialog(dialogOptions, handleDialogOpen); + + function processCsv(csvFilePath) { + + let cancelImporting = false; + importEmitter.removeAllListeners(); + + importEmitter.once('cancel-importing', () => { + cancelImporting = true; + }); + + const filename = basename(csvFilePath).replace('.csv', ''); + const stream = fs.createReadStream(csvFilePath); + + let completedLines = 0; + let hasColumnRow = false; + let folder = null; + let fields = []; + let currentEntryDatum = null; + let entryData = []; + + async function handleData(data) { + + let createdEntryDatum = null; + + if (cancelImporting) { + return Promise.reject('User stopped importing'); + } + + if (isEmpty(folder) && csvProcessor.isColumnRow(data)) { + const columnData = csvProcessor.getColumnData(data); + folder = await Folder.create({ + name: `${filename} - ${shortid.generate()}`, + data: columnData + }); + broadcast('csv-folder-created', {folderId: folder.id}); + fields = csvProcessor.getFields(data); + hasColumnRow = true; + } + else if (folder) { + + const rowData = csvProcessor.getRowDataByFields(data, fields); + const {sourceEntry} = rowData; + const pageNum = pageNumToFloat(rowData[FIELD_PAGE_NUM], FRACTION_LENGTH) || ''; + + if (sourceEntry) { + + delete rowData.sourceEntry; + delete rowData[FIELD_PAGE_NUM]; + + currentEntryDatum = { + folderId: folder.id, + sourceEntry, + pageNum, + data: rowData + }; + createdEntryDatum = currentEntryDatum; + } + else if (currentEntryDatum) { + currentEntryDatum.data = csvProcessor.appendData(data, currentEntryDatum.data, fields); + } + } + ++completedLines; + reporter.report(() => { + broadcast('csv-processing-status', {completedLines}); + }, reportDuration); + + if (createdEntryDatum) { + return createdEntryDatum; + } + } + + async function batchInsertIfNeeded(entryDatum) { + + if (entryDatum) { + entryData.push(entryDatum); + + if (entryData.length > (numberConcurrentWrite + 1)) { + + const insertQuery = getEntryBatchInsertQuery(db, entryData.slice(0, entryData.length - 1)); + + return db.raw(insertQuery) + .then(() => { + // put the last one to new array + entryData = [entryData.pop()]; + }); + } + } + } + + function done() { + broadcast('csv-processing-done', {filename}); + resolve({message: 'done'}); + } + + csv.fromStream(stream) + .validate((data, next) => { + + handleData(data) + .then((entryDatum) => batchInsertIfNeeded(entryDatum)) + .then(() => next(null, true)) + .catch((err) => next(err)); + }) + .on('data', () => {}) + .on('error', (err) => { + log.error(err); + reject({message: `${err}`}); + }) + .on('end', () => { + + if (! hasColumnRow) { + reject({messageId: 'no-column-row-detected', filename}); + return; + } + + // finish the rest + if (entryData.length > 0) { + const insertQuery = getEntryBatchInsertQuery(db, entryData); + db.raw(insertQuery) + .then(done); + } + else { + done(); + } + }); + } + + function handleDialogOpen(paths) { + + if (isEmpty(paths)) { + resolve({message: 'User did not choose csv file'}); + return; + } + broadcast('csv-processing-start'); + const csvFilePath = first(paths); + processCsv(csvFilePath); + } +} + +function getEntryBatchInsertQuery(db, entryData) { + const formattedData = entryData.map((row) => ({...row, data: JSON.stringify(row.data)})); + return db.knex.batchInsert('Entry', formattedData, 200); +} diff --git a/pool/shard001/JavaScript/0006059_no-multiple-toplevel-headings.js b/pool/shard001/JavaScript/0006059_no-multiple-toplevel-headings.js new file mode 100644 index 0000000000000000000000000000000000000000..344027dc0122a9eec0488078923dbe024c520ad8 --- /dev/null +++ b/pool/shard001/JavaScript/0006059_no-multiple-toplevel-headings.js @@ -0,0 +1,61 @@ +/** + * @author Titus Wormer + * @copyright 2015 Titus Wormer + * @license MIT + * @module no-multiple-toplevel-headings + * @fileoverview + * Warn when multiple top-level headings are used. + * @example + * + * # Foo + * + * # Bar + * + * + * # Foo + * + * ## Bar + */ + +'use strict'; + +/* + * Dependencies. + */ + +var visit = require('unist-util-visit'); +var position = require('mdast-util-position'); + +/** + * Warn when multiple top-level headings are used. + * + * @param {Node} ast - Root node. + * @param {File} file - Virtual file. + * @param {*} preferred - Ignored. + * @param {Function} done - Callback. + */ +function noMultipleToplevelHeadings(ast, file, preferred, done) { + var topLevelheading = false; + + visit(ast, 'heading', function (node) { + var pos; + + if (position.generated(node)) { + return; + } + + if (node.depth === 1) { + if (topLevelheading) { + pos = position.start(node); + + file.warn('Don’t use multiple top level headings (' + pos.line + ':' + pos.column + ')', node); + } + + topLevelheading = node; + } + }); + + done(); +} + +module.exports = noMultipleToplevelHeadings; diff --git a/pool/shard001/JavaScript/0006060_test_quotaExceeded_recovery.js b/pool/shard001/JavaScript/0006060_test_quotaExceeded_recovery.js new file mode 100644 index 0000000000000000000000000000000000000000..4ba7c77c4b6b299228f90330abd50c74f8e35469 --- /dev/null +++ b/pool/shard001/JavaScript/0006060_test_quotaExceeded_recovery.js @@ -0,0 +1,141 @@ +/** + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +var disableWorkerTest = "Need a way to set temporary prefs from a worker"; + +var testGenerator = testSteps(); + +function testSteps() +{ + const spec = "http://foo.com"; + const name = + this.window ? window.location.pathname : "test_quotaExceeded_recovery"; + const objectStoreName = "foo"; + + const android = mozinfo.os == "android"; + + // We want 512 KB database on Android and 4 MB database on other platforms. + const groupLimitKB = android ? 512 : 4096; + + // The group limit is calculated as 20% of the global temporary storage limit. + const tempStorageLimitKB = groupLimitKB * 5; + + // We want 64 KB chunks on Android and 512 KB chunks on other platforms. + const dataSizeKB = android ? 64 : 512; + const dataSize = dataSizeKB * 1024; + + const maxIter = 5; + + for (let blobs of [false, true]) { + setTemporaryStorageLimit(tempStorageLimitKB); + + clearAllDatabases(continueToNextStepSync); + yield undefined; + + info("Opening database"); + + let request = indexedDB.openForPrincipal(getPrincipal(spec), name); + request.onerror = errorHandler; + request.onupgradeneeded = grabEventAndContinueHandler;; + request.onsuccess = unexpectedSuccessHandler; + + yield undefined; + + // upgradeneeded + request.onupgradeneeded = unexpectedSuccessHandler; + request.onsuccess = grabEventAndContinueHandler; + + info("Creating objectStore"); + + request.result.createObjectStore(objectStoreName, { autoIncrement: true }); + + yield undefined; + + // success + let db = request.result; + db.onerror = errorHandler; + + ok(true, "Filling database"); + + let obj = { + name: "foo" + } + + if (!blobs) { + obj.data = getRandomView(dataSize); + } + + let iter = 1; + let i = 1; + let j = 1; + while (true) { + if (blobs) { + obj.data = getBlob(getView(dataSize)); + } + + let trans = db.transaction(objectStoreName, "readwrite"); + request = trans.objectStore(objectStoreName).add(obj); + request.onerror = function(event) + { + event.stopPropagation(); + } + + trans.oncomplete = function(event) { + if (iter == 1) { + i++; + } + j++; + testGenerator.next(true); + } + trans.onabort = function(event) { + is(trans.error.name, "QuotaExceededError", "Reached quota limit"); + testGenerator.next(false); + } + + let completeFired = yield undefined; + if (completeFired) { + ok(true, "Got complete event"); + continue; + } + + ok(true, "Got abort event"); + + if (iter++ == maxIter) { + break; + } + + if (iter > 1) { + ok(i == j, "Recycled entire database"); + j = 1; + } + + trans = db.transaction(objectStoreName, "readwrite"); + + // Don't use a cursor for deleting stored blobs (Cursors prolong live + // of stored files since each record must be fetched from the database + // first which creates a memory reference to the stored blob.) + if (blobs) { + request = trans.objectStore(objectStoreName).clear(); + } else { + request = trans.objectStore(objectStoreName).openCursor(); + request.onsuccess = function(event) { + let cursor = event.target.result; + if (cursor) { + cursor.delete(); + cursor.continue(); + } + } + } + + trans.onabort = unexpectedSuccessHandler;; + trans.oncomplete = grabEventAndContinueHandler; + + yield undefined; + } + } + + finishTest(); + yield undefined; +} diff --git a/pool/shard001/JavaScript/0006062_dimension.js b/pool/shard001/JavaScript/0006062_dimension.js new file mode 100644 index 0000000000000000000000000000000000000000..f897f0aa79c2d4f0cca4a500ffb0e31d120f198c --- /dev/null +++ b/pool/shard001/JavaScript/0006062_dimension.js @@ -0,0 +1,47 @@ +(function (tree) { + +// +// A number with a unit +// +tree.Dimension = function (value, unit) { + this.value = parseFloat(value); + this.unit = unit || null; +}; + +tree.Dimension.prototype = { + eval: function () { return this }, + toColor: function () { + return new(tree.Color)([this.value, this.value, this.value]); + }, + toCSS: function () { + var css = this.value + this.unit; + return css; + }, + + // In an operation between two Dimensions, + // we default to the first Dimension's unit, + // so `1px + 2em` will yield `3px`. + // In the future, we could implement some unit + // conversions such that `100cm + 10mm` would yield + // `101cm`. + operate: function (op, other) { + return new(tree.Dimension) + (tree.operate(op, this.value, other.value), + this.unit || other.unit); + }, + + // TODO: Perform unit conversion before comparing + compare: function (other) { + if (other instanceof tree.Dimension) { + if (other.value > this.value) { + return -1; + } else if (other.value < this.value) { + return 1; + } else { + return 0; + } + } + } +}; + +})(require('../tree')); diff --git a/pool/shard001/JavaScript/0006066_ui-theme-service.spec.js b/pool/shard001/JavaScript/0006066_ui-theme-service.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..fdc19b9c8abe69eda07a5112edc4ce21e60f3c9d --- /dev/null +++ b/pool/shard001/JavaScript/0006066_ui-theme-service.spec.js @@ -0,0 +1,44 @@ +import {ThemeBootstrapService} from 'services/theme/ui-theme-service'; +import {ThemeRestClient} from 'services/rest/ui-theme-rest-service'; +import {stub} from 'test/test-utils'; + +describe('ThemeBootstrapService', () => { + let themeRestClient = stub(ThemeRestClient); + let themeBootstrapService; + + beforeEach(() => { + themeBootstrapService = new ThemeBootstrapService(themeRestClient); + }); + + describe('#processStyles', () => { + it('should process all styles that need processing', () => { + let styles = { + brand_primary_color : '#008e8e', + brand_secondary_color:'#003f3f', + button_color:'#8e0071', + button_disabled_color:'#f2ff00', + button_hover_color:'#8e0000', + link_color:'#8e0071', + link_disabled_color:'#f2ff00', + link_hover_color:'#8e0000', + tooltip_color:'#008e8e' + }; + let actualStyles = themeBootstrapService.processStyles(styles); + expect(actualStyles).to.eql({ + brand_primary_color : '#008e8e', + brand_secondary_color:'#003f3f', + button_color:'#8e0071', + button_color_dark: '#75005d', + button_disabled_color:'#f2ff00', + button_disabled_color_dark:'#dae600', + button_hover_color:'#8e0000', + button_hover_color_dark: "#750000", + link_color:'#8e0071', + link_color_darker:'#420034', + link_disabled_color:'#f2ff00', + link_hover_color:'#8e0000', + tooltip_color:'#008e8e' + }); + }); + }); +}); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006068_jquery.infinite-scroll-helper.js b/pool/shard001/JavaScript/0006068_jquery.infinite-scroll-helper.js new file mode 100644 index 0000000000000000000000000000000000000000..f41ad05a7815c4703f2471b6e762a84a5e9f8eb0 --- /dev/null +++ b/pool/shard001/JavaScript/0006068_jquery.infinite-scroll-helper.js @@ -0,0 +1,324 @@ +/** + * @author Ryan Ogden + */ + +;(function($, window) { + + 'use strict'; + + var pluginName = 'infiniteScrollHelper', + namespace = 'plugin_' + pluginName; + + /*-------------------------------------------- */ + /** Plugin Defaults */ + /*-------------------------------------------- */ + + var defaults = { + /** + * The amount of pixels from the bottom of the scrolling element in which the loadMore callback will be invoked + * @type {number} + */ + bottomBuffer: 0, + /** + * The interval, in milliseconds that the scroll event handler will be debounced + * @type {number} + */ + debounceInt: 100, + /** + * A callback that must return `true` or `false`, signaling whether loading has completed. This callback is passed a `pageCount` argument. + * @type {function} + */ + doneLoading: null, + /** + * The interval, in milliseconds, that the doneLoading callback will be called + * @type {number} + */ + interval: 300, + /** + * The class that will be added to the target element once loadMore has been invoked + * @type {string} + */ + loadingClass: 'loading', + /** + * A selector targeting the element that will receive the class specified by the `loadingClass` option + * @type {string} + */ + loadingClassTarget: null, + /** + * The amount of time, in milliseconds, before the loadMore callback is invoked once the bottom of the scroll container has been reached + * @type {number} + */ + loadMoreDelay: 0, + /** + * A callback function that will be invoked when the scrollbar eclipses the bottom threshold of the scrolling element, + * @type {function} + */ + loadMore: $.noop, + /** + * The starting page count that the plugin increment each time loadMore is invoked + * @type {number} + */ + startingPageCount: 1, + /** + * Whether or not the plugin should make an initial call to loadMore. This can be set to true if, for instance, you need to load + * the initial content asynchronously on page load + * @type {boolean} + */ + triggerInitialLoad: false + }; + + /*-------------------------------------------- */ + /** Plugin Constructor */ + /*-------------------------------------------- */ + + /** + * The Plugin constructor + * @constructor + * @param {HTMLElement} element The element that will be monitored + * @param {object} options The plugin options + */ + function Plugin(element, options) { + this.options = $.extend({}, defaults, options); + + this.$element = $(element); + this.$win = $(window); + this.$loadingClassTarget = this._getLoadingClassTarget(); + this.$scrollContainer = this._getScrollContainer(); + + this.loading = false; + this.doneLoadingInt = null; + this.pageCount = this.options.triggerInitialLoad ? this.options.startingPageCount - 1 : this.options.startingPageCount; + this.destroyed = false; + + this._init(); + } + + /*-------------------------------------------- */ + /** Private Methods */ + /*-------------------------------------------- */ + + /** + * Initializes the plugin + * @private + */ + Plugin.prototype._init = function() { + this._addListeners(); + + /* Call initial begin load if option is true. If not, simulate a scroll incase + the scroll element container height is greater than the contents */ + if (this.options.triggerInitialLoad) { + this._beginLoadMore(this.options.loadMoreDelay); + } else { + this._handleScroll(); + } + }; + + /** + * Returns the element that should have the loading class applied to it when + * the plugin is in the loading state + * @return {jQuery} The jQuery wrapped element + * @private + */ + Plugin.prototype._getLoadingClassTarget = function() { + return this.options.loadingClassTarget ? $(this.options.loadingClassTarget) : this.$element; + }; + + /** + * Finds the element that acts as the scroll container for the infinite + * scroll content + * @return {jQuery} The jQuery object that wraps the scroll container + */ + Plugin.prototype._getScrollContainer = function() { + var $scrollContainer = null; + + // see if the target element is overflow-y:scroll. If so, it is the + // scroll container + if (this.$element.css('overflow-y') == 'scroll') { + $scrollContainer = this.$element; + } + + // see if a parent is overflow-y:scroll. If so, it is the scroll container + if (!$scrollContainer) { + $scrollContainer = this.$element.parents().filter(function() { + return $(this).css('overflow-y') == 'scroll'; + }); + } + + // if the target element or any parent aren't overflow-y:scroll, + // assume the window as the scroll container + $scrollContainer = $scrollContainer.length > 0 ? $scrollContainer : this.$win; + + return $scrollContainer; + }; + + /** + * Adds listeners required for plugin to function + * @private + */ + Plugin.prototype._addListeners = function() { + var self = this; + + this.$scrollContainer.on('scroll.' + pluginName, debounce(function() { + self._handleScroll(); + }, this.options.debounceInt)); + }; + + /** + * Removes all listeners required by the plugin + * @private + */ + Plugin.prototype._removeListeners = function() { + this.$scrollContainer.off('scroll.' + pluginName); + }; + + /** + * Handles the scroll logic and determins when to trigger the load more callback + * @private + */ + Plugin.prototype._handleScroll = function(e) { + var self = this; + + if (this._shouldTriggerLoad()) { + this._beginLoadMore(this.options.loadMoreDelay); + + // if a the doneLoading callback was provided, set an interval to check when to call it + if (this.options.doneLoading) { + this.doneLoadingInt = setInterval( + function() { + if (self.options.doneLoading(self.pageCount)) { + self._endLoadMore(); + } + }, + this.options.interval + ); + } + } + }; + + /** + * Determines if the user scrolled far enough to trigger the load more callback + * @return {boolean} true if the load more callback should be triggered, false otherwise + * @private + */ + Plugin.prototype._shouldTriggerLoad = function() { + var elementBottom = this._getElementHeight(), + scrollBottom = this.$scrollContainer.scrollTop() + this.$scrollContainer.height() + this.options.bottomBuffer; + + return (!this.loading && scrollBottom >= elementBottom && this.$element.is(':visible')); + }; + + /** + * Retrieves the height of the element being scrolled. + * @return {number} The height of the element being scrolled + * @private + */ + Plugin.prototype._getElementHeight = function() { + if (this.$element == this.$scrollContainer) { + return this.$element[0].scrollHeight; + } else { + return this.$element.height(); + } + }; + + /** + * Initialize a call to the loadMore callback and set to loading state + * @param {number} delay The amount of time, in milliseconds, to wait before calling the load more callback + * @private + */ + Plugin.prototype._beginLoadMore = function(delay) { + delay = delay || 0; + + setTimeout($.proxy(function() { + this.pageCount++; + this.options.loadMore(this.pageCount, $.proxy(this._endLoadMore, this)); + this.$loadingClassTarget.addClass(this.options.loadingClass); + }, this), delay); + + this.loading = true; + this._removeListeners(); + }; + + /** + * Return the plugin to the not loading state + * @private + */ + Plugin.prototype._endLoadMore = function() { + clearInterval(this.doneLoadingInt); + this.loading = false; + this.$loadingClassTarget.removeClass(this.options.loadingClass); + !this.destroyed && this._addListeners(); + }; + + /*-------------------------------------------- */ + /** Public Methods */ + /*-------------------------------------------- */ + + /** + * Destroys the plugin instance + * @public + */ + Plugin.prototype.destroy = function() { + this._removeListeners(); + this.options.loadMore = null; + this.options.doneLoading = null; + $.data(this.$element[0], namespace, null); + clearInterval(this.doneLoadingInt); + this.destroyed = true; + }; + + /*-------------------------------------------- */ + /** Helpers */ + /*-------------------------------------------- */ + + // A utility method for calling methods on the plugin instance + function callMethod(instance, method, args) { + if ( instance && $.isFunction(instance[method]) ) { + instance[method].apply(instance, args); + } + } + + // Borrowed from Underscore.js (http://underscorejs.org/) + function debounce(func, wait, immediate) { + var timeout; + + return function() { + var context = this, args = arguments; + var later = function() { + timeout = null; + if (!immediate) func.apply(context, args); + }; + var callNow = immediate && !timeout; + clearTimeout(timeout); + timeout = setTimeout(later, wait); + if (callNow) func.apply(context, args); + }; + } + + /*-------------------------------------------- */ + /** Plugin Definition */ + /*-------------------------------------------- */ + + $.fn[pluginName] = function(options) { + var method = false, + methodArgs = arguments; + + if (typeof options == 'string') { + method = options; + } + + return this.each(function() { + + var plugin = $.data(this, namespace); + + if (!plugin && !method) { + $.data(this, namespace, new Plugin(this, options)); + } else if (method) { + callMethod(plugin, method, Array.prototype.slice.call(methodArgs, 1)); + } + }); + }; + + // expose plugin constructor on window + window.InfiniteScrollHelper = window.InfiniteScrollHelper || Plugin; + +})(jQuery, window); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006077_teaser.js b/pool/shard001/JavaScript/0006077_teaser.js new file mode 100644 index 0000000000000000000000000000000000000000..09d4d048aee2f70aa0b59d2518008a366b40d0d0 --- /dev/null +++ b/pool/shard001/JavaScript/0006077_teaser.js @@ -0,0 +1,154 @@ + +'use strict'; + +var async = require('async'); +var _ = require('lodash'); +var S = require('string'); +var winston = require('winston'); + +var meta = require('../meta'); +var user = require('../user'); +var posts = require('../posts'); +var plugins = require('../plugins'); +var utils = require('../utils'); + +module.exports = function (Topics) { + Topics.getTeasers = function (topics, uid, callback) { + if (typeof uid === 'function') { + winston.warn('[Topics.getTeasers] this usage is deprecated please provide uid'); + callback = uid; + uid = 0; + } + if (!Array.isArray(topics) || !topics.length) { + return callback(null, []); + } + + var counts = []; + var teaserPids = []; + var postData; + var tidToPost = {}; + + topics.forEach(function (topic) { + counts.push(topic && (parseInt(topic.postcount, 10) || 0)); + if (topic) { + if (topic.teaserPid === 'null') { + delete topic.teaserPid; + } + + switch (meta.config.teaserPost) { + case 'first': + teaserPids.push(topic.mainPid); + break; + + case 'last-post': + teaserPids.push(topic.teaserPid || topic.mainPid); + break; + + case 'last-reply': // intentional fall-through + default: + teaserPids.push(topic.teaserPid); + break; + } + } + }); + + async.waterfall([ + function (next) { + posts.getPostsFields(teaserPids, ['pid', 'uid', 'timestamp', 'tid', 'content'], next); + }, + function (_postData, next) { + postData = _postData; + var uids = _.uniq(postData.map(function (post) { + return post.uid; + })); + + user.getUsersFields(uids, ['uid', 'username', 'userslug', 'picture'], next); + }, + function (usersData, next) { + var users = {}; + usersData.forEach(function (user) { + users[user.uid] = user; + }); + + + async.each(postData, function (post, next) { + // If the post author isn't represented in the retrieved users' data, then it means they were deleted, assume guest. + if (!users.hasOwnProperty(post.uid)) { + post.uid = 0; + } + + post.user = users[post.uid]; + post.timestampISO = utils.toISOString(post.timestamp); + tidToPost[post.tid] = post; + posts.parsePost(post, next); + }, next); + }, + function (next) { + var teasers = topics.map(function (topic, index) { + if (!topic) { + return null; + } + if (tidToPost[topic.tid]) { + tidToPost[topic.tid].index = meta.config.teaserPost === 'first' ? 1 : counts[index]; + if (tidToPost[topic.tid].content) { + var s = S(tidToPost[topic.tid].content); + tidToPost[topic.tid].content = s.stripTags.apply(s, utils.stripTags).s; + } + } + return tidToPost[topic.tid]; + }); + + plugins.fireHook('filter:teasers.get', { teasers: teasers, uid: uid }, next); + }, + function (data, next) { + next(null, data.teasers); + }, + ], callback); + }; + + Topics.getTeasersByTids = function (tids, uid, callback) { + if (typeof uid === 'function') { + winston.warn('[Topics.getTeasersByTids] this usage is deprecated please provide uid'); + callback = uid; + uid = 0; + } + if (!Array.isArray(tids) || !tids.length) { + return callback(null, []); + } + async.waterfall([ + function (next) { + Topics.getTopicsFields(tids, ['tid', 'postcount', 'teaserPid', 'mainPid'], next); + }, + function (topics, next) { + Topics.getTeasers(topics, uid, next); + }, + ], callback); + }; + + Topics.getTeaser = function (tid, uid, callback) { + if (typeof uid === 'function') { + winston.warn('[Topics.getTeaser] this usage is deprecated please provide uid'); + callback = uid; + uid = 0; + } + Topics.getTeasersByTids([tid], uid, function (err, teasers) { + callback(err, Array.isArray(teasers) && teasers.length ? teasers[0] : null); + }); + }; + + Topics.updateTeaser = function (tid, callback) { + async.waterfall([ + function (next) { + Topics.getLatestUndeletedReply(tid, next); + }, + function (pid, next) { + pid = pid || null; + if (pid) { + Topics.setTopicField(tid, 'teaserPid', pid, next); + } else { + Topics.deleteTopicField(tid, 'teaserPid', next); + } + }, + ], callback); + }; +}; diff --git a/pool/shard001/JavaScript/0006079_app.js b/pool/shard001/JavaScript/0006079_app.js new file mode 100644 index 0000000000000000000000000000000000000000..65df2308b117f443325af054796727f2900d7394 --- /dev/null +++ b/pool/shard001/JavaScript/0006079_app.js @@ -0,0 +1,90 @@ +(function(angular){ + + 'use strict'; + + angular.module('parkLocator', ['appServices', 'appFilters', 'appControllers', 'appDirectives', 'ui.router', 'ngMaterial', 'duScroll', 'dcbImgFallback', 'ngAnimate']) + + .value('duScrollDuration', 600) + .value('duScrollOffset', 0) + .value('duScrollEasing', function (t) { + return t < 0.5 ? 4 * t * t * t : (t - 1) * (2 * t - 2) * (2 * t - 2) + 1; + }) + + .config([ '$httpProvider', function ($httpProvider) { + $httpProvider.interceptors.push('httpInterceptor'); + $httpProvider.defaults.headers.common['Content-Type'] = 'application/json; charset=utf-8'; + $httpProvider.defaults.cache = true; + }]) + + .config([ '$mdThemingProvider', function ($mdThemingProvider) { + $mdThemingProvider.theme('altTheme') + .primaryPalette('purple') + .accentPalette('red') + .warnPalette('yellow'); + }]) + + .config([ '$mdIconProvider', function($mdIconProvider) { + $mdIconProvider.defaultIconSet('img/icons/core.svg', 48); + }]) + + .config(['$stateProvider', '$urlRouterProvider', + function ($stateProvider, $urlRouterProvider) { + + $urlRouterProvider.otherwise('/'); + + $stateProvider + .state('home', { + url: '/', + templateUrl: 'views/main.html', + controller: 'devicesCtrl' + }) + + .state('home.park', { + url: ':name', + views: { + '': { + templateUrl: 'views/partials/park-information.html', + controller: 'parkCtrl' + }, + 'classes-info@home.park': { + templateUrl: 'views/partials/class-section-selection.html', + controller: 'classesCtrl' + } + }, + resolve: { + maps: ['googleMaps', function(googleMaps) { + return googleMaps.isReady(); + }], + currentPark: ['parkService', '$stateParams', '$timeout', '$q', function(parkService, $stateParams, $timeout, $q) { + var deferred = $q.defer(); + $timeout( parkService.resolveCurrentPark, 0, false, deferred, $stateParams.name); + return deferred.promise; + }] + } + }) + + .state('home.park.section', { + url: '/:sectionName', + views: { + 'classes-info@home.park': { + templateUrl: 'views/partials/course-section.html', + controller: 'sectionCtrl' + } + } + }); + + }]) + + .run(['$rootScope', '$state', function($rootScope, $state) { + + $rootScope.$on("$stateChangeError", function(event, toState, toParams, fromState, fromParams, error) { + event.preventDefault(); + if (toState.name === 'home.park') { + $state.go('home'); + } + console.log(event, toState, toParams, fromState, fromParams, error); + }); + + }]); + // End angular.module +})(angular || window.angular); diff --git a/pool/shard001/JavaScript/0006080_detalle.js b/pool/shard001/JavaScript/0006080_detalle.js new file mode 100644 index 0000000000000000000000000000000000000000..b1a315f3f602467ec63bbfe3fad60b8d45481818 --- /dev/null +++ b/pool/shard001/JavaScript/0006080_detalle.js @@ -0,0 +1,29 @@ +var args = arguments[0]; +var ajax = require('ajax'); + +// Extraigo un modelo con .at() de la colección y lo convierto en JSON +var detallesJuego = Alloy.Collections.listaJuegos.at(args).toJSON(); + +// Llamada a la API para los detalles de un juego específico +ajax.obtenerJuego(detallesJuego.name, function(juego) { + Alloy.Globals.loading.hide(); + Alloy.Models.juego.set(juego); + + if (OS_IOS) { + Alloy.Globals.navWin.openWindow($.detalle); + } else { + $.detalle.open(); + } +}); + +Alloy.Globals.loading.show('Cargando...', false); + +function cerrarVentana() { + $.detalle.close(); +} + +// Libero binds y memoria +$.detalle.addEventListener("close", function() { + Alloy.Models.juego.clear(); + $.destroy(); +}); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006081_ui.js b/pool/shard001/JavaScript/0006081_ui.js new file mode 100644 index 0000000000000000000000000000000000000000..efa8c8a3f6579c34e4aa073ce16609570a943602 --- /dev/null +++ b/pool/shard001/JavaScript/0006081_ui.js @@ -0,0 +1,52 @@ +var flight = require('flightjs'); +var template = require('./templates/title.hogan'); + +const TYPING_DELAY = 42; +const BASE_TYPING_DELAY = 50; + +function helloWorldUI() { + + this.attributes({ + + }); + + this.typewriter = function(str) { + var instance = this; + var textEl = document.querySelector('[data-text]'); + var arr = str.split(''); + var i = 0; + textEl.innerHTML = ''; + + setTimeout(function() { + instance.setText(textEl, arr, 0); + }, BASE_TYPING_DELAY); + }; + + this.setText = function(el, arr, i) { + var instance = this; + var delay = (TYPING_DELAY * Math.random()) + BASE_TYPING_DELAY; + if (arr[i]) { + el.innerHTML += arr[i]; + i++; + setTimeout(function() { + instance.setText(el, arr, i); + }, delay); + } + }; + + this.render = function(name) { + var titleEl = document.querySelector('[data-title]'); + + titleEl.innerHTML = template.render({ + name: name + }); + } + + this.after('initialize', function() { + this.render('Hanna'); + this.typewriter.call(this, 'Welcome to the Epsilon Eridani system. What would you like to do next?'); + }); + +} + +module.exports = flight.component(helloWorldUI); diff --git a/pool/shard001/JavaScript/0006083_bench.js b/pool/shard001/JavaScript/0006083_bench.js new file mode 100644 index 0000000000000000000000000000000000000000..e6905f4f20a06bdf64a73ae43bef39416f01e83f --- /dev/null +++ b/pool/shard001/JavaScript/0006083_bench.js @@ -0,0 +1,20 @@ +var midpoint = require('./'); +var Benchmark = require('benchmark'); +var fs = require('fs'); +var point = require('turf-point'); + +var pt1 = point(0,0); +var pt2 = point(10,0); + +var suite = new Benchmark.Suite('turf-midpoint'); +suite + .add('turf-midpoint',function () { + midpoint(pt1, pt2); + }) + .on('cycle', function (event) { + console.log(String(event.target)); + }) + .on('complete', function () { + + }) + .run(); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006084_main.js b/pool/shard001/JavaScript/0006084_main.js new file mode 100644 index 0000000000000000000000000000000000000000..bdb01797c86eac4462117fe733ef76f28c36533d --- /dev/null +++ b/pool/shard001/JavaScript/0006084_main.js @@ -0,0 +1,28 @@ +function walk(node) { + 'use strict'; + var child, next; + switch (node.nodeType){ + case 1: + case 9: + case 11: + child = node.firstChild; + while (child) { + next = child.nextSibling; + walk(child); + child = next; + } + break; + + case 3: + var assmar = node.nodeValue; + + assmar = assmar.replace(/asthma/g, 'ass-mar'); + assmar = assmar.replace(/Asthma/g, 'Ass-mar'); + assmar = assmar.replace(/ASTHMA/g, 'ASS-MAR'); + + node.nodeValue = assmar; + break; + } +} + +walk(document.body); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006085_AWTodoItem.js b/pool/shard001/JavaScript/0006085_AWTodoItem.js new file mode 100644 index 0000000000000000000000000000000000000000..1f4b4f3b568964a600900ef6ae9149227aedf188 --- /dev/null +++ b/pool/shard001/JavaScript/0006085_AWTodoItem.js @@ -0,0 +1,57 @@ +import React from 'react'; +import {List, ListItem} from 'material-ui/List'; +import Avatar from 'material-ui/Avatar'; +import IconButton from 'material-ui/IconButton'; +import MoreVertIcon from 'material-ui/svg-icons/navigation/more-vert'; +import IconMenu from 'material-ui/IconMenu'; +import MenuItem from 'material-ui/MenuItem'; +import {blue400,green400} from 'material-ui/styles/colors'; +import ActionCheckCircle from 'material-ui/svg-icons/action/check-circle'; +import Timelapse from 'material-ui/svg-icons/image/timelapse' +import AWAvatar from './AWAvatar'; + + + +export default class AWTodoItem extends React.Component { + + constructor(props) { + super(props); + this.state = {}; + + console.log(this.props) + } + + + render() { + + + var iconButtonElement = ( + + + { (this.props.status == "fait") ? : } + + + ); + + var rightIconMenu = ( + + } onTouchTap={()=>this.props.changeStatus(this.props.index,"a faire")} >A faire + } onTouchTap={()=>this.props.changeStatus(this.props.index,"fait")} >Fait + + ); + return ( + + } + rightIconButton={rightIconMenu} + primaryText={this.props.text} + + /> + + ); + } +} diff --git a/pool/shard001/JavaScript/0006088_app.js b/pool/shard001/JavaScript/0006088_app.js new file mode 100644 index 0000000000000000000000000000000000000000..7456f362b5d92023e3c82ea58f2e38aa3bba5f8a --- /dev/null +++ b/pool/shard001/JavaScript/0006088_app.js @@ -0,0 +1,31 @@ +'use strict'; + +var app = angular.module('zenApp', ['ui.bootstrap']); + +app.config(function ($provide) { + $provide.decorator('$controller', function ($delegate, tempUserAuthenticationFactory) { + return function (constructor, locals) { + var days_of_week = ["Sun","Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; + var months = ['January', 'February', 'March', 'April','May', 'June', + 'July', 'August', 'September','October', 'November', 'December']; + var number_of_days_in_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; + locals.$scope.days_of_week = days_of_week; + locals.$scope.months = months; + locals.$scope.number_of_days_in_month=number_of_days_in_month; + locals.$scope._UserService = tempUserAuthenticationFactory; + return $delegate(constructor, locals); + }; + }); +}); + +app.run(function ($rootScope){ + $rootScope.formatDate = function(date) { + var date_num = date.getDate() < 10 ? '0'+date.getDate() : date.getDate(); + var day_num = date.getDay(); + var month_num = (date.getMonth()+1) < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1;//date.getMonth(); + var fullYear_num = date.getFullYear(); + //return days_of_week[day_num]+", "+date_num+ " of "+months[month_num]+" "+fullYear_num; + return fullYear_num+"-"+month_num+"-"+date_num; + + } + }); diff --git a/pool/shard001/JavaScript/0006089_comment.js b/pool/shard001/JavaScript/0006089_comment.js new file mode 100644 index 0000000000000000000000000000000000000000..151170bef5ca875f259c0f33524ba9df5675898d --- /dev/null +++ b/pool/shard001/JavaScript/0006089_comment.js @@ -0,0 +1,124 @@ +/** + * @Project NUKEVIET 4.x + * @Author VINADES.,JSC (contact@vinades.vn) + * @Copyright (C) 2014 VINADES.,JSC. All rights reserved + * @License GNU/GPL version 2 or any later version + * @Createdate 1 - 31 - 2010 5 : 12 + */ + +function nv_change_active(cid) { + var new_status = $('#change_active_' + cid).is(':checked') ? 1 : 0; + if (confirm(nv_is_change_act_confirm[0])) { + var nv_timer = nv_settimeout_disable('change_active_' + cid, 3000); + $.post(script_name + '?' + nv_name_variable + '=' + nv_module_name + '&' + nv_fc_variable + '=change_active&nocache=' + new Date().getTime(), 'change_active=1&cid=' + cid + '&new_status=' + new_status, function(res) { + + }); + } else { + $('#change_active_' + cid).prop('checked', new_status ? false : true); + } +} + +$(document).ready(function() { + if ($.fn.datepicker) { + $("#from_date, #to_date").datepicker({ + dateFormat: "dd/mm/yy", + changeMonth: true, + changeYear: true, + showOtherMonths: true, + showOn: 'focus' + }); + } + $('#to-btn').click(function() { + $("#to_date").datepicker('show'); + }); + $('#from-btn').click(function() { + $("#from_date").datepicker('show'); + }); + $("#checkall").click(function() { + $("input[name=commentid]:checkbox").each(function() { + $(this).prop("checked", true); + }); + }); + $("#uncheckall").click(function() { + $("input[name=commentid]:checkbox").each(function() { + $(this).prop("checked", false); + }); + }); + $("a.enable").click(function() { + var list = []; + $("input[name=commentid]:checked").each(function() { + list.push($(this).val()); + }); + if (list.length < 1) { + alert(LANG.nocheck); + return false; + } + $.ajax({ + type: "POST", + url: script_name + "?" + nv_lang_variable + "=" + nv_lang_data + "&" + nv_name_variable + "=" + nv_module_name + "&" + nv_fc_variable + "=active", + data: "list=" + list + "&active=1", + success: function(data) { + alert(data); + window.location = window.location.href; + } + }); + return false; + }); + $("a.disable").click(function() { + var list = []; + $("input[name=commentid]:checked").each(function() { + list.push($(this).val()); + }); + if (list.length < 1) { + alert(LANG.nocheck); + return false; + } + $.ajax({ + type: "POST", + url: script_name + "?" + nv_lang_variable + "=" + nv_lang_data + "&" + nv_name_variable + "=" + nv_module_name + "&" + nv_fc_variable + "=active", + data: "list=" + list + "&active=0", + success: function(data) { + alert(data); + window.location = window.location.href; + } + }); + return false; + }); + $("a.delete").click(function() { + var list = []; + $("input[name=commentid]:checked").each(function() { + list.push($(this).val()); + }); + if (list.length < 1) { + alert(LANG.nocheck); + return false; + } + if (confirm(LANG.delete_confirm)) { + $.ajax({ + type: "POST", + url: script_name + "?" + nv_lang_variable + "=" + nv_lang_data + "&" + nv_name_variable + "=" + nv_module_name + "&" + nv_fc_variable + "=del", + data: "list=" + list, + success: function(data) { + alert(data); + window.location = window.location.href; + } + }); + } + return false; + }); + $("a.deleteone").click(function() { + if (confirm(LANG.delete_confirm)) { + var url = $(this).attr("href"); + $.ajax({ + type: "POST", + url: url, + data: "", + success: function(data) { + alert(data); + window.location = window.location.href; + } + }); + } + return false; + }); +}); diff --git a/pool/shard001/JavaScript/0006091_gallery.js b/pool/shard001/JavaScript/0006091_gallery.js new file mode 100644 index 0000000000000000000000000000000000000000..df7d9a4f8eca060d70ec7b8e13e6534533e0f788 --- /dev/null +++ b/pool/shard001/JavaScript/0006091_gallery.js @@ -0,0 +1,72 @@ +var PictureRoom = PictureRoom || {}; +PictureRoom.IndexPage = function () { + this.init(); +}; +PictureRoom.IndexPage.prototype = { + CLASS: { + dragged: 'pictureDrop__area--isDragged', + disabled: 'isDisabled' + }, + init: function () { + this.setParameter(); + this.bindEvent(); + this.loadThumbnails(); + }, + setParameter: function () { + this.$thumbnailArea = $('.js-thumbnailArea'); + this.$thumbnailTempalte = this.$thumbnailArea.children('li').detach(); + + this.$thumbnailArea.html(''); + this.$loadBtn = $('.js-loadBtn'); + this.loadCount = 16; + this.max = this.loadCount; + this.min = 0; + }, + bindEvent: function () { + this.$loadBtn.on('click', $.proxy(this.loadMore, this)); + }, + loadThumbnails: function() { + var createThumbnail = this.createThumbnail.bind(this); + $.ajax({ + url: 'api/file?min=' + this.min + '&max=' + this.max, + type: 'GET', + cache: false, + processData: false, + contentType: false, + timeout: 10000 + }).done(function(data){ + if (data.result) { + createThumbnail(data.pictures); + } else { + console.log('upload failed...'); + } + }).fail(function(XMLHttpRequest, textStatus, errorThrown){ + console.log(textStatus); + console.log('upload failed...'); + }); + }, + loadMore: function(e) { + if (e) e.preventDefault(); + this.min += this.loadCount; + this.max += this.loadCount; + this.loadThumbnails(); + }, + createThumbnail: function(pictures) { + var fragment = document.createDocumentFragment(); + for(var i in pictures) { + var $template = this.$thumbnailTempalte.clone(); + $template.children('.js-thumbnailImage').attr('src', pictures[i].thumbnailPath); + $template.children('.js-thumbnailTitle').text(pictures[i].name); + $template.get(0).dataset.name = pictures[i].name; + fragment.appendChild($template.get(0)); + } + this.$thumbnailArea.get(0).appendChild(fragment); + } +}; +$(function () { + new PictureRoom.IndexPage(); + new PictureRoom.ImageDisplay({ + selectorDisplayTrigger: '.js-thumbnailArea > li', + selectorImage: 'img' + }); +}); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006093_adhocCommandKO.js b/pool/shard001/JavaScript/0006093_adhocCommandKO.js new file mode 100644 index 0000000000000000000000000000000000000000..88ddc43bc139cb6022ef430ae3176aaf8e812ceb --- /dev/null +++ b/pool/shard001/JavaScript/0006093_adhocCommandKO.js @@ -0,0 +1,117 @@ +/* + * Copyright 2016 SimplifyOps, Inc. (http://simplifyops.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. + */ + +//= require vendor/knockout.min +//= require vendor/knockout-mapping + +function AdhocLink(data,nodefilter) { + var self = this; + self.nodefilter=nodefilter; + self.href=ko.observable(null); + self.title=ko.observable(null); + self.execid=ko.observable(null); + self.filter=ko.observable(null); + + self.status=ko.observable(null); + self.succeeded=ko.observable(null); + + var statusMap={ + 'scheduled':'running', + 'running':'running', + 'succeed':'succeed', + 'succeeded':'succeed', + 'fail':'fail', + 'failed':'fail', + 'cancel':'aborted', + 'aborted':'aborted', + 'retry':'failedretry', + 'timedout':'timedout', + 'timeout':'timedout' + }; + + self.statusClass=ko.pureComputed(function(){ + var css=statusMap[self.status()]; + return css?css:'other'; + }); + + //set the command and filter strings + self.fillCommand=function(){ + jQuery('#runFormExec').val(self.title()); + self.nodefilter.useFilterString(self.filter()); + }; + + ko.mapping.fromJS(data,{},self); +} +function AdhocCommand(data,nodefilter) { + var self = this; + self.nodefilter=nodefilter; + self.loadMax=20; + self.recentCommandsLoaded=ko.observable(false); + self.recentCommands=ko.observableArray([]); + self.commandString=ko.observable(); + self.commandStringDelayed = ko.pureComputed(this.commandString) + .extend({ rateLimit: { method: "notifyWhenChangesStop", timeout: 1000 } }); + self.running=ko.observable(false); + self.canRun=ko.observable(false); + self.error=ko.observable(); + self.allowInput = ko.pureComputed(function(){ + return !self.running() && self.canRun(); + }); + self.followControl=null; + var mapping = { + 'recentCommands': { + create: function (options) { + return new AdhocLink(options.data,self.nodefilter); + } + } + }; + self.recentCommandsNoneFound=ko.pureComputed(function(){ + return self.recentCommands().length<1 && self.recentCommandsLoaded(); + }); + self.loadList=function(params){ + var requrl=_genUrl(appLinks.adhocHistoryAjax,jQuery.extend({max:self.loadMax},params)); + return jQuery.ajax({ + type:'GET', + url:requrl, + + error:function(data,jqxhr,err){ + self.error('Recent commands list: request failed for '+requrl+': '+err+", "+jqxhr); + } + }); + }; + self.loadRecentCommands=function(){ + self.loadList({}).done(function (data,status,xhr) { + self.recentCommandsLoaded(true); + try { + ko.mapping.fromJS({recentCommands:data.executions},mapping,self); + } catch (e) { + console.log('Recent commands list: error receiving data',e); + self.error('Recent commands list: error receiving data: '+e); + runError('Recent commands list: error receiving data: '+e); + } + }); + }; + //self.commandStringDelayed.subscribe(function(newval){ + // if(newval && newval.length>3) { + // self.loadList({query: newval}).done(function (data, status, xhr) { + // console.log('new query: ' + newval, data); + // }); + // } + //}); + if(data){ + ko.mapping.fromJS(data,{},self); + } +} diff --git a/pool/shard001/JavaScript/0006096_app.js b/pool/shard001/JavaScript/0006096_app.js new file mode 100644 index 0000000000000000000000000000000000000000..0655132ec59dfcda1a7f6b8e81a6045de7ffb496 --- /dev/null +++ b/pool/shard001/JavaScript/0006096_app.js @@ -0,0 +1,271 @@ +var express = require('express'); +var path = require('path'); +var favicon = require('static-favicon'); +var logger = require('morgan'); +var cookieParser = require('cookie-parser'); +var bodyParser = require('body-parser'); + +var routes = require('./routes/index'); +var users = require('./routes/users'); +var dataHandler=require('./DataHandler'); +var app = express(); +var fs = require('fs'); + +var JPush = require("jpush-sdk"); + +//var jpushClient = JPush.build({appkey: "f108c40b77940e399d61f7d8", masterSecret: "6dafaafef254d686ac2c6b14"}); +var client = JPush.buildClient('f108c40b77940e399d61f7d8', '6dafaafef254d686ac2c6b14'); + +//Variable +var eventInfo; +var eventName; +var eventDetail; +var accountName="Rocky"; +var accounrClub="建總"; +var accounrPhone="93686526"; +var isJoined=false; + +// view engine setup +app.set('views', path.join(__dirname, 'views')); +app.set('view engine', 'ejs'); + +app.use(favicon()); +app.use(logger('dev')); +app.use(bodyParser.json()); +app.use(bodyParser.urlencoded()); +app.use(cookieParser()); +app.use(express.static(path.join(__dirname, 'public'))); + +app.all('/*', function(req, res, next) { + res.header("Access-Control-Allow-Origin", "*"); + res.header("Access-Control-Allow-Headers", "X-Requested-With"); + next(); +}); +app.use('/', routes); +app.use('/users', users); + +app.get('/push', function (req, res) { + + dataHandler.readImgByFilename('5386a54094363aa414d74ffbbg2.jpg',res,function(image){ + console.log(image); + res.writeHead('200', {'Content-Type': 'image/png'}); + // res.end(image,'binary'); + // res.header({'Content_type': 'image/png'}) + + // res.header({'Content_type': 'image/png'}) + //res.end(image); + }); + console.log("Push"); + +}); + + +app.get('/getImage', function (req, res) { + console.log(req.query.imgName); + dataHandler.readImgByFilename(req.query.imgName,res,function(image){ + console.log(image); + res.writeHead('200', {'Content-Type': 'image/png'}); + + }); + + +}); + +app.get('/findAllOrgs', function (req, res) { + + dataHandler.findAllOrg(res); + + +}); + +app.get('/findOrg', function (req, res) { + console.log(req.query.orgId); + + dataHandler.findOrgById(req.query.orgId,res); + +}); + +app.get('/findOrg/:identifier', function(req, res){ + flow.write(req.params.identifier, res); +}); + + +app.get('/findMsg', function (req, res) { + console.log(req.query.msgid); + + dataHandler.findMsgById(req.query.msgid,res); + +}); + +app.get('/findMsgByCid', function (req, res) { + console.log(req.query.cId); + + dataHandler.findMsgsByCId(res,req.query.cId); + +}); + + + +app.get('/findAllMsgs', function (req, res) { + + dataHandler.findAllMsgs(res); + +}); + + +app.get('/updateOrg', function (req, res) { + + // console.log(req.query); + var orgObj = JSON.parse(req.query.orgData); + console.log(orgObj); + +res.send("OK"); + // dataHandler.findAllMsgs(res); + +}); + + + + +app.get('/eventInfo', function (req, res) { + + // console.log(req.query); + // var orgObj = JSON.parse(req.query.orgData); + //eventInfo="團體活動"; + // eventDetail="團體活動 DEtail"; +// console.log(eventInfo); + + res.send('{"eventName":"'+eventName + '","eventDetail":"'+eventDetail+ '"}'); + // dataHandler.findAllMsgs(res); + +}); + +app.get('/joinEvent', function (req, res) { + + // console.log(req.query); + // var orgObj = JSON.parse(req.query.orgData); + console.log(eventInfo); +isJoined=true; + res.send("OK"); + // dataHandler.findAllMsgs(res); + +}); + +app.get('/isJoined', function (req, res) { + + // console.log(req.query); + // var orgObj = JSON.parse(req.query.orgData); + + res.send(isJoined); + // dataHandler.findAllMsgs(res); + +}); + + +app.get('/addEvent', function (req, res) { + eventInfo="團體活動"; +eventName=req.query.eventName; + eventDetail=req.query.eventDetail; + console.log(req.query.eventDetail); + // var orgObj = JSON.parse(req.query.orgData); + console.log(eventInfo); + client.push().setPlatform(JPush.ALL) + .setAudience(JPush.ALL) + .setNotification("建總 - "+req.query.eventName, JPush.ios('ios alert', 'happy', 5)) + .send(function(err, res) { + if (err) { + console.log(err.message); + } else { + console.log('Sendno: ' + res.sendno); + console.log('Msg_id: ' + res.msg_id); + } + }); + + res.send(eventInfo); + + +}); + + + +app.get('/findAlbumByName/:orgId/:albumName', function (req, res) { + + // __dirname +console.log(req.params.albumName); + // dataHandler.findAlbumDict(res); + var path="F:/album/"+req.params.orgId+"/"+req.params.albumName; + fs.readdir(path,function(err,files){ + if (err) throw err; + var c=0; + console.log("files",files); +res.send(files); + /* + files.forEach(function(file){ + c++; + fs.readFile(dir+file,'utf-8',function(err,html){ + if (err) throw err; + data[file]=html; + if (0===--c) { + console.log(data); //socket.emit('init', {data: data}); + } + }); + + }); + */ + }); +}); + + +app.get('/findAlbum', function (req, res) { + + dataHandler.findAlbumDict(res); + +}); + +app.get('/findAlbum/:orgId', function (req, res) { + + dataHandler.findAlbumDictByOrgId(req.params.orgId,res); + +}); + + + + +/// catch 404 and forward to error handler +app.use(function(req, res, next) { + var err = new Error('Not Found'); + err.status = 404; + next(err); +}); + + + + +/// error handlers + +// development error handler +// will print stacktrace +if (app.get('env') === 'development') { + app.use(function(err, req, res, next) { + res.status(err.status || 500); + res.render('error', { + message: err.message, + error: err + }); + }); +} + +app.use(function(err, req, res, next) { + res.status(err.status || 500); + res.render('error', { + message: err.message, + error: {} + }); +}); + + + + + + +app.listen(3000); diff --git a/pool/shard001/JavaScript/0006100_index_calendar.js b/pool/shard001/JavaScript/0006100_index_calendar.js new file mode 100644 index 0000000000000000000000000000000000000000..1b46ae3d946be17c81804f0b20f835ae8a1ababd --- /dev/null +++ b/pool/shard001/JavaScript/0006100_index_calendar.js @@ -0,0 +1,56 @@ +var date=new Date(); +var datearr=date.toDateString().match(/([\w\d]*)/g); +var current_date={ +day:datearr[0], +month:datearr[2], +date:datearr[4], +year:datearr[6] +}; +document.getElementsByClassName("date")[0].innerHTML=current_date.date; +document.getElementsByClassName("month")[0].innerHTML=current_date.month; +document.getElementsByClassName("year")[0].innerHTML=current_date.year; +var d="",c=""; + +function getday(){ +if(date.getMonth()==2){ +if(current_date.year%4==0){ +if(current_date.year%100==0){ +return 29; +} +if(current_date.year%400!=0){ +return 28; +} +else{ +return 29; +} +}else{ +return 28; +} +} +return 0; +} +var feb=getday(); +var days=["31",feb,"31","30","31","30","31","31","30","31","30","31"]; +var dayname=["Sun","Mon","Tues","Wednes","Thurs","Fri","Satur"] +/* +d+="
  • M<\/li>"; +d+="
  • Tu<\/li>"; +d+="
  • W<\/li>"; +d+="
  • Th<\/li>"; +d+="
  • F<\/li>"; +d+="
  • Sat<\/li>"; +d+="
  • Sun<\/li>"; +*/ + +for(var i=0;i<(days[date.getMonth()]*1);i++){ +if((i+1)!=current_date.date){ +d+="
  • "+(i+1)+"<\/li>"; +if((i+1)%7==0){d+="";} +}else{ +d+="
  • "+(i+1)+"<\/li>"; +if((i+1)%7==0){d+="";} +} +} +c+="
    "+dayname[date.getDay()]+"day
    "; +document.getElementsByClassName("calendar")[0].innerHTML+=c; +document.getElementsByClassName("datelist")[0].innerHTML=d; \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006101_test-devserver-inline-as-valid.js b/pool/shard001/JavaScript/0006101_test-devserver-inline-as-valid.js new file mode 100644 index 0000000000000000000000000000000000000000..a54a08eda7912112d408fce21474bb6c6da093c5 --- /dev/null +++ b/pool/shard001/JavaScript/0006101_test-devserver-inline-as-valid.js @@ -0,0 +1,19 @@ +const test = require('tape'); +const fp = require('../'); + +test('devServer.inline: property is set', function (t) { + t.plan(1); + + const options = { + isDevMode: true, + isHMREnabled: true, + devServerPort: 80, + }; + + const target = true; + + fp(null, options) + .entry('any-entry-file') + .devServer(target) + .run(cfg => t.equals(cfg.devServer.inline, target)); +}); diff --git a/pool/shard001/JavaScript/0006102_ValueComparisonOperation.js b/pool/shard001/JavaScript/0006102_ValueComparisonOperation.js new file mode 100644 index 0000000000000000000000000000000000000000..eb14062e065ef4947cb1fc930a2d7c32bf76a323 --- /dev/null +++ b/pool/shard001/JavaScript/0006102_ValueComparisonOperation.js @@ -0,0 +1,38 @@ +module.exports = function(sequelize, DataTypes) { + var ValueComparisonOperation = sequelize.define("ValueComparisonOperation", + { + id: { + type: DataTypes.INTEGER, + allowNull: false, + primaryKey: true, + autoIncrement: true + }, + frequency: DataTypes.INTEGER, + frequency_unit: DataTypes.STRING, + schedule: DataTypes.TIME, + schedule_retry: DataTypes.INTEGER, + schedule_retry_unit: DataTypes.STRING, + schedule_timeout: DataTypes.INTEGER, + schedule_timeout_unit: DataTypes.STRING + }, + { + underscored: true, + underscoredAll: true, + timestamps: false, + + classMethods: { + associate: function(models) { + ValueComparisonOperation.belongsTo(models.Filter, { + onDelete: "CASCADE", + foreignKey: { + name: 'value_comparison_operation', + allowNull: false + } + }); + } + } + } + ); + + return ValueComparisonOperation; +}; \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006103_captcha.js b/pool/shard001/JavaScript/0006103_captcha.js new file mode 100644 index 0000000000000000000000000000000000000000..525862ec786aad55f98c526971972617af66d5dc --- /dev/null +++ b/pool/shard001/JavaScript/0006103_captcha.js @@ -0,0 +1,87 @@ +/** + * Magento + * + * NOTICE OF LICENSE + * + * This source file is subject to the Academic Free License (AFL 3.0) + * that is bundled with this package in the file LICENSE_AFL.txt. + * It is also available through the world-wide-web at this URL: + * http://opensource.org/licenses/afl-3.0.php + * If you did not receive a copy of the license and are unable to + * obtain it through the world-wide-web, please send an email + * to license@magento.com so we can send you a copy immediately. + * + * DISCLAIMER + * + * Do not edit or add to this file if you wish to upgrade Magento to newer + * versions in the future. If you wish to customize Magento for your + * needs please refer to http://www.magento.com for more information. + * + * @category Mage + * @package js + * @copyright Copyright (c) 2006-2016 X.commerce, Inc. and affiliates (http://www.magento.com) + * @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0) + */ +var Captcha = Class.create(); +Captcha.prototype = { + initialize: function(url, formId){ + this.url = url; + this.formId = formId; + }, + refresh: function(elem) { + formId = this.formId; + if (elem) Element.addClassName(elem, 'refreshing'); + new Ajax.Request(this.url, { + onSuccess: function (response) { + if (response.responseText.isJSON()) { + var json = response.responseText.evalJSON(); + if (!json.error && json.imgSrc) { + $(formId).writeAttribute('src', json.imgSrc); + if (elem) Element.removeClassName(elem, 'refreshing'); + } else { + if (elem) Element.removeClassName(elem, 'refreshing'); + } + } + }, + method: 'post', + parameters: { + 'formId' : this.formId + } + }); + } +}; + +document.observe('billing-request:completed', function(event) { + if (typeof window.checkout != 'undefined') { + if (window.checkout.method == 'guest' && $('guest_checkout')){ + $('guest_checkout').captcha.refresh() + } + if (window.checkout.method == 'register' && $('register_during_checkout')){ + $('register_during_checkout').captcha.refresh() + } + } +}); + + +document.observe('login:setMethod', function(event) { + var switchCaptchaElement = function(shown, hidden) { + var inputPrefix = 'captcha-input-box-', imagePrefix = 'captcha-image-box-'; + if ($(inputPrefix + hidden)) { + $(inputPrefix + hidden).hide(); + $(imagePrefix + hidden).hide(); + } + if ($(inputPrefix + shown)) { + $(inputPrefix + shown).show(); + $(imagePrefix + shown).show(); + } + }; + + switch (event.memo.method) { + case 'guest': + switchCaptchaElement('guest_checkout', 'register_during_checkout'); + break; + case 'register': + switchCaptchaElement('register_during_checkout', 'guest_checkout'); + break; + } +}); diff --git a/pool/shard001/JavaScript/0006105_cursor_effects.js b/pool/shard001/JavaScript/0006105_cursor_effects.js new file mode 100644 index 0000000000000000000000000000000000000000..e1157c977518f75addb18f28a7c0679403f45660 --- /dev/null +++ b/pool/shard001/JavaScript/0006105_cursor_effects.js @@ -0,0 +1,165 @@ +class Circle { + constructor({ origin, speed, color, angle, context }) { + this.origin = origin + this.position = { ...this.origin } + this.color = color + this.speed = speed + this.angle = angle + this.context = context + this.renderCount = 0 + } + + draw() { + this.context.fillStyle = this.color + this.context.beginPath() + this.context.arc(this.position.x, this.position.y, 2, 0, Math.PI * 2) + this.context.fill() + } + + move() { + this.position.x = (Math.sin(this.angle) * this.speed) + this.position.x + this.position.y = (Math.cos(this.angle) * this.speed) + this.position.y + (this.renderCount * 0.3) + this.renderCount++ + } +} + +class Boom { + constructor ({ origin, context, circleCount = 10, area }) { + this.origin = origin + this.context = context + this.circleCount = circleCount + this.area = area + this.stop = false + this.circles = [] + } + + randomArray(range) { + const length = range.length + const randomIndex = Math.floor(length * Math.random()) + return range[randomIndex] + } + + randomColor() { + const range = ['8', '9', 'A', 'B', 'C', 'D', 'E', 'F'] + return '#' + this.randomArray(range) + this.randomArray(range) + this.randomArray(range) + this.randomArray(range) + this.randomArray(range) + this.randomArray(range) + } + + randomRange(start, end) { + return (end - start) * Math.random() + start + } + + init() { + for(let i = 0; i < this.circleCount; i++) { + const circle = new Circle({ + context: this.context, + origin: this.origin, + color: this.randomColor(), + angle: this.randomRange(Math.PI - 1, Math.PI + 1), + speed: this.randomRange(1, 6) + }) + this.circles.push(circle) + } + } + + move() { + this.circles.forEach((circle, index) => { + if (circle.position.x > this.area.width || circle.position.y > this.area.height) { + return this.circles.splice(index, 1) + } + circle.move() + }) + if (this.circles.length == 0) { + this.stop = true + } + } + + draw() { + this.circles.forEach(circle => circle.draw()) + } +} + +class CursorSpecialEffects { + constructor() { + this.computerCanvas = document.createElement('canvas') + this.renderCanvas = document.createElement('canvas') + + this.computerContext = this.computerCanvas.getContext('2d') + this.renderContext = this.renderCanvas.getContext('2d') + + this.globalWidth = window.innerWidth + this.globalHeight = window.innerHeight + + this.booms = [] + this.running = false + } + + handleMouseDown(e) { + const boom = new Boom({ + origin: { x: e.clientX, y: e.clientY }, + context: this.computerContext, + area: { + width: this.globalWidth, + height: this.globalHeight + } + }) + boom.init() + this.booms.push(boom) + this.running || this.run() + } + + handlePageHide() { + this.booms = [] + this.running = false + } + + init() { + const style = this.renderCanvas.style + style.position = 'fixed' + style.top = style.left = 0 + style.zIndex = '999999999999999999999999999999999999999999' + style.pointerEvents = 'none' + + style.width = this.renderCanvas.width = this.computerCanvas.width = this.globalWidth + style.height = this.renderCanvas.height = this.computerCanvas.height = this.globalHeight + + document.body.append(this.renderCanvas) + + window.addEventListener('mousedown', this.handleMouseDown.bind(this)) + window.addEventListener('pagehide', this.handlePageHide.bind(this)) + } + + run() { + this.running = true + if (this.booms.length == 0) { + return this.running = false + } + + requestAnimationFrame(this.run.bind(this)) + + this.computerContext.clearRect(0, 0, this.globalWidth, this.globalHeight) + this.renderContext.clearRect(0, 0, this.globalWidth, this.globalHeight) + + this.booms.forEach((boom, index) => { + if (boom.stop) { + return this.booms.splice(index, 1) + } + boom.move() + boom.draw() + }) + this.renderContext.drawImage(this.computerCanvas, 0, 0, this.globalWidth, this.globalHeight) + } +} + +// 鼠标点击爆炸效果 +const cursorSpecialEffects = new CursorSpecialEffects() +cursorSpecialEffects.init() + +// 览器切换标签离开当前页面时改变title提示 +document.addEventListener('visibilitychange', function() { + if (document.visibilityState == 'hidden') { + normal_title = document.title; + document.title = '客官别走呀!快回来看看~'; + } else { + document.title = normal_title; + } +}); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006106_box_test.js b/pool/shard001/JavaScript/0006106_box_test.js new file mode 100644 index 0000000000000000000000000000000000000000..5c357f26ad52dbd93bade3008f0230c60fa6a7fa --- /dev/null +++ b/pool/shard001/JavaScript/0006106_box_test.js @@ -0,0 +1,86 @@ +var Box = require('@src/traces/box'); + + +describe('Test boxes', function() { + 'use strict'; + + describe('supplyDefaults', function() { + var traceIn, + traceOut; + + var defaultColor = '#444'; + + var supplyDefaults = Box.supplyDefaults; + + beforeEach(function() { + traceOut = {}; + }); + + it('should set visible to false when x and y are empty', function() { + traceIn = {}; + supplyDefaults(traceIn, traceOut, defaultColor); + expect(traceOut.visible).toBe(false); + + traceIn = { + x: [], + y: [] + }; + supplyDefaults(traceIn, traceOut, defaultColor); + expect(traceOut.visible).toBe(false); + }); + + it('should set visible to false when x or y is empty', function() { + traceIn = { + x: [] + }; + supplyDefaults(traceIn, traceOut, defaultColor); + expect(traceOut.visible).toBe(false); + + traceIn = { + x: [], + y: [1, 2, 3] + }; + supplyDefaults(traceIn, traceOut, defaultColor); + expect(traceOut.visible).toBe(false); + + traceIn = { + y: [] + }; + supplyDefaults(traceIn, traceOut, defaultColor); + expect(traceOut.visible).toBe(false); + + traceIn = { + x: [1, 2, 3], + y: [] + }; + supplyDefaults(traceIn, traceOut, defaultColor); + expect(traceOut.visible).toBe(false); + }); + + it('should set orientation to v by default', function() { + traceIn = { + y: [1, 2, 3] + }; + supplyDefaults(traceIn, traceOut, defaultColor); + expect(traceOut.orientation).toBe('v'); + + traceIn = { + x: [1, 1, 1], + y: [1, 2, 3] + }; + supplyDefaults(traceIn, traceOut, defaultColor); + expect(traceOut.orientation).toBe('v'); + }); + + it('should set orientation to h when only x is supplied', function() { + traceIn = { + x: [1, 2, 3] + }; + supplyDefaults(traceIn, traceOut, defaultColor); + expect(traceOut.orientation).toBe('h'); + + }); + + }); + +}); diff --git a/pool/shard001/JavaScript/0006107_autoStrip.spec.js b/pool/shard001/JavaScript/0006107_autoStrip.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..cbd9ae65da2095e48724b699263043e559401051 --- /dev/null +++ b/pool/shard001/JavaScript/0006107_autoStrip.spec.js @@ -0,0 +1,24 @@ +let chai = require('chai') +let should = chai.should() + +let string = require('./index') + +describe('autoStrip', () => { + + it('removes trailing and leading character from prefix and suffix', () => { + ({ prefix, selected, suffix } = string.autoStrip('\t(', '', ')')) + prefix.should.equal('\t') + selected.should.equal('') + suffix.should.equal('') + }) + + describe('test', () => { + it('returns true if prefix and suffix ends with and starts with paired characters', () => { + string.testAutoStrip([['(', ')'], ['[', ']']], '(', '', ')').should.equal(true) + }) + + it('returns false if prefix and suffix do not end and start with paired characters', () => { + string.testAutoStrip([['(', ')'], ['[', ']']], '(', '', ']').should.equal(false) + }) + }) +}) diff --git a/pool/shard001/JavaScript/0006108_SideBarHeader.unit.test.js b/pool/shard001/JavaScript/0006108_SideBarHeader.unit.test.js new file mode 100644 index 0000000000000000000000000000000000000000..31176e2d3ee058154e43c4164710648ea346dcc3 --- /dev/null +++ b/pool/shard001/JavaScript/0006108_SideBarHeader.unit.test.js @@ -0,0 +1,18 @@ +import React from 'react'; +import {shallow} from 'enzyme'; +import {SideBarHeader} from '../SideBarHeader'; + +describe('SideBarHeader', () => { + test('renders without title', () => { + const wrapper = shallow(); + expect(wrapper).toMatchSnapshot(); + }); + test('renders with empty title', () => { + const wrapper = shallow(); + expect(wrapper).toMatchSnapshot(); + }); + test('renders with title', () => { + const wrapper = shallow(); + expect(wrapper).toMatchSnapshot(); + }); +}); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006109_eventStream.js b/pool/shard001/JavaScript/0006109_eventStream.js new file mode 100644 index 0000000000000000000000000000000000000000..0745d674822ca6f8684052af6f3de67d65a22b81 --- /dev/null +++ b/pool/shard001/JavaScript/0006109_eventStream.js @@ -0,0 +1,185 @@ +var CONNECTED = 'CONNECTED'; +var REGION_CHANGE = 'REGION_CHANGE'; +var SHOW_HELP = 'SHOW_HELP'; + +var HabiventsES = null; +var CurrentAvatars = {}; + +function orientationToRotation(orientation) { + switch (orientation) { + case 'North': + return 270; + case 'West': + return 90; + case 'South': + return 180; + case 'East': + return 0; + default: + return 0; + } +} + +const HTMLArrows = ['↑', '←', '↓', '→']; +const orient = ["West", "East", "North", "South"]; + +function processEvent(event) { + switch (event.type) { + case CONNECTED: + return; + case REGION_CHANGE: + $('#regionHeader').text(event.msg.description); + $('#docsFrame').attr('src', event.msg.docsURL); + $('#orientationHeader').text(event.msg.orientation); + $("#compass").rotate({ + animateTo: orientationToRotation(event.msg.orientation), + }) + var arrow = (orient.indexOf(event.msg.orientation) + 3) % 4; + $("#northArrow").html(HTMLArrows[arrow]); + $("#northHeader").text(event.msg.neighbors.North); + arrow = ++arrow % 4; + $("#westArrow").html(HTMLArrows[arrow]); + $("#westHeader").text(event.msg.neighbors.West); + arrow = ++arrow % 4; + $("#southArrow").html(HTMLArrows[arrow]); + $("#southHeader").text(event.msg.neighbors.South); + arrow = ++arrow % 4; + $("#eastArrow").html(HTMLArrows[arrow]); + $("#eastHeader").text(event.msg.neighbors.East); + return; + case SHOW_HELP: + $('#docsFrame').attr('src', event.msg.docsURL); + return; + default: + console.log('Unknown event type: ', event.type) + return; + } +} + +function startEventSource() { + if (HabiventsES == null || HabiventsES.readyState == 2) { + HabiventsES = new EventSource('/events/'+AvatarName+'/eventStream'); + HabiventsES.onerror = function(e) { + if (HabiventsES.readyState == 2) { + console.log('Habivents EventSource disconnected, retrying in 3 secs:', e); + setTimeout(startEventSource, 3000); + } + } + HabiventsES.addEventListener('message', function(e) { + var event = JSON.parse(e.data); + processEvent(event); + }, false); + } +} + +function doAction(type, params) { + var action = { + type: type, + params: {}, + } + if (params !== undefined) { + action.params = params; + } + $.ajax('/api/v1/avatar/'+AvatarName+'/action', { + data: JSON.stringify(action), + contentType: 'application/json', + type: 'POST', + success: function () { + console.log('Successfully sent action:', type, params); + }, + }); +} + +function startEsp(avatarName) { + doAction('START_ESP', {avatar: avatarName}); +} + +function sendTeleportInvite(avatarName) { + doAction('SEND_TELEPORT_INVITE', {avatar: avatarName}); +} + +function sendTeleportRequest(avatarName) { + doAction('SEND_TELEPORT_REQUEST', {avatar: avatarName}); +} + +function appendButton(element, avatarName, btnClass, text, tooltip, onclick) { + var newButton = $('', + $('').addClass('icon-warning-sign'), + 'サーバに接続できませんでした。' + ); +} + +// ユーザ名をランダムに生成 +var userName = 'ゲスト' + Math.floor(Math.random() * 100); +// チャットボックスの前にユーザ名を表示 +$('#user-name').append(userName); + +// WebSocketサーバ接続イベント +ws.onopen = function() { + $('#textbox').focus(); + // 入室情報を文字列に変換して送信 + ws.send(JSON.stringify({ + type: 'login', + user: userName + })); +}; + +// メッセージ受信イベントを処理 +ws.onmessage = function(event) { + // 受信したメッセージを復元 + var data = JSON.parse(event.data); + var item = $('
  • ').append( + $('
    ').append( + $('').addClass('icon-user'), + $('').addClass('meta chat-time').append(data.time)) + ); + + // pushされたメッセージを解釈し、要素を生成する + if (data.type === 'join') { + /* + item.addClass('alert alert-info') + .prepend('') + .children('div').children('i').after(data.user + 'が入室しました'); + */ + var source = $("#user-template").html(); + var template = Handlebars.compile(source); + $("#user_list").prepend(template(data)).fadeIn(300); + + } else if (data.type === 'chat') { + // item.addClass('well well-small') + // .append($('
    ').text(data.text)) + // .children('div').children('i').after(data.user); + + + } else if (data.type === 'defect') { + /* + item.addClass('alert') + .prepend('') + .children('div').children('i').after(data.user + 'が退室しました'); + */ + $("#"+data.user).remove(); + }else if(data.type === 'start'){ // ゲーム開始 + $("#ansTxt").text(data.text); + } else if(data.type === 'ans'){ + console.log(data); + if(data.res) + { + var source = $("#correct-ans-template").html(); + var template = Handlebars.compile(source); + $("#chat-history").prepend(template(data)).fadeIn(300); + console.log("せいかい"); + }else{ + var source = $("#false-ans-template").html(); + var template = Handlebars.compile(source); + $("#chat-history").prepend(template(data)).fadeIn(300); + } + + }else { + item.addClass('alert alert-error') + .children('div').children('i').removeClass('icon-user').addClass('icon-warning-sign') + .after('不正なメッセージを受信しました'); + } + //$('#chat-history').prepend(item).hide().fadeIn(500); +}; + + +// 発言イベント +textbox.onkeyup = function(event) { + // エンターキーを押したとき + ws.send(JSON.stringify({ + type: 'change', + user: userName, + text: textbox.value, + })); +}; + +// ブラウザ終了イベント +window.onbeforeunload = function () { + ws.send(JSON.stringify({ + type: 'defect', + user: userName, + })); +}; + + +function ansCorrect() +{ + +} + +function ansFalse() +{ + +} diff --git a/pool/shard001/JavaScript/0006142_app.js b/pool/shard001/JavaScript/0006142_app.js new file mode 100644 index 0000000000000000000000000000000000000000..76f31e60458763fc6d88b1dba7d675fcbc01226a --- /dev/null +++ b/pool/shard001/JavaScript/0006142_app.js @@ -0,0 +1,47 @@ + +/** + * Module dependencies. + */ + +var express = require('express'); +var http = require('http'); +var path = require('path'); +var handlebars = require('express3-handlebars') + +var index = require('./routes/index'); +var project = require('./routes/project'); + +// Example route +// var user = require('./routes/user'); + +var app = express(); + +// all environments +app.set('port', process.env.PORT || 3000); +app.set('views', path.join(__dirname, 'views')); +app.engine('handlebars', handlebars()); +app.set('view engine', 'handlebars'); +app.use(express.favicon()); +app.use(express.logger('dev')); +app.use(express.json()); +app.use(express.urlencoded()); +app.use(express.methodOverride()); +app.use(express.cookieParser('Intro HCI secret key')); +app.use(express.session()); +app.use(app.router); +app.use(express.static(path.join(__dirname, 'public'))); + +// development only +if ('development' == app.get('env')) { + app.use(express.errorHandler()); +} + +// Add routes here +app.get('/', index.view); +app.get('/project/:name', project.viewProject); +// Example route +// app.get('/users', user.list); + +http.createServer(app).listen(app.get('port'), function(){ + console.log('Express server listening on port ' + app.get('port')); + }); diff --git a/pool/shard001/JavaScript/0006143_init.js b/pool/shard001/JavaScript/0006143_init.js new file mode 100644 index 0000000000000000000000000000000000000000..4782223b752b1658821250f9fcd9fed839fe5956 --- /dev/null +++ b/pool/shard001/JavaScript/0006143_init.js @@ -0,0 +1,37 @@ +'use strict'; + +/** + * Why does this file exist? + * + * Individual tests can load the datasource, and avoid repetition, by adding: + * `require('./init.js');` + * of their source code. + */ + +var chai = require('chai'); +global.expect = chai.expect; +global.assert = chai.assert; +global.should = chai.should(); // Why is the function being executed? Because the "should" interface extends Object.prototype to provide a single getter as the starting point for your language assertions. + +global._ = require('lodash'); /*global _:true*/ + +var settings = require('./datasource-test-v7-plain.json'); +global.getSettings = function() { /*global getSettings*/ + return _.cloneDeep(settings); +}; + +var DataSource = require('loopback-datasource-juggler').DataSource; +global.getDataSource = global.getSchema = global.getConnector = function (customSettings) { + (customSettings) /*eslint no-console: ["error", { allow: ["log"] }] */ + ? console.log('\n\tcustomSettings will override global settings for datasource\n'/*, JSON.stringify(customSettings,null,2)*/) + : console.log('\n\twill use global settings for datasource\n'); + var settings = customSettings || getSettings(); + // settings.log = { + // type: 'file', + // level: 'trace', + // path: 'test/es-v5/elasticsearch-v5-'+Date.now()+'.log' + // }; + //console.log('\n\tsettings:\n', JSON.stringify(settings,null,2)); + settings.connector = require('../../'); + return new DataSource(settings); +}; diff --git a/pool/shard001/JavaScript/0006145_main.js b/pool/shard001/JavaScript/0006145_main.js new file mode 100644 index 0000000000000000000000000000000000000000..42b76a0d595a1ca91bd7d3b703494fe09d234914 --- /dev/null +++ b/pool/shard001/JavaScript/0006145_main.js @@ -0,0 +1,74 @@ +/*jslint node:true, vars:true, bitwise:true, unparam:true */ +/*jshint unused:true */ +/*global */ + +var config = require('./config'); +var nitrogen = require('nitrogen'); +var service = new nitrogen.Service(config); +var seisometer = new nitrogen.Device({ + nickname: 'seisometer', + name: 'SeismicSense' +}); +var lcd = require('jsupm_i2clcd'); +var display = new lcd.Jhd1313m1(0, 0x3E, 0x62); + +var mraa = require('mraa'); //require mraa +console.log('MRAA Version: ' + mraa.getVersion()); //write the mraa version to the console + +var min = 200; +var max = 1023; +var maxDelay = 500; +var analogPin0 = new mraa.Aio(0); //setup access analog input Analog pin #0 (A0) + +service.connect(seisometer, function(err, session, seisometer){ + if (err) { return console.log('failed to connect to service' + err);} + + // this will be our main sensor loop + setInterval(function(){ + display.clear(); + var reading = analogPin0.read(); + reading = constrain(reading, min, max); + reading = map(reading, min, max, 0, 15); + display.setCursor(0,1); + for(var i = 0; i <= reading; i++){ + display.write('#'); + } + if(reading >= 4 && reading < 8){ + //display.write('seismic activity'); + display.setColor(255, 255, 100); // yellow + sendMessage(reading, session); + }else if(reading >= 8){ + display.setCursor(1,1); + display.write('EARTHQUAKE'); + display.setColor(255, 0, 0); // red + sendMessage(reading, session); + }else { + display.setColor(255, 255, 255); // white + } + }, maxDelay); + + function sendMessage(reading, session){ + var message = new nitrogen.Message({ + type: '_seismic', + body: { + reading: reading + } + }); + + session.log.info('sending reading: ' + reading); + + message.send(session); + } +}); + + + +function constrain(value, min, max){ + if(value < min) return min; + else if (value > max) return max; + else return value; +} + +function map(x, in_min, in_max, out_min, out_max){ + return(x-in_min)*(out_max - out_min)/(in_max - in_min)+out_min; +} \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006148_traverson.js b/pool/shard001/JavaScript/0006148_traverson.js new file mode 100644 index 0000000000000000000000000000000000000000..a7e2cbbddba92bfe928daef86586eb6a0aa1dbea --- /dev/null +++ b/pool/shard001/JavaScript/0006148_traverson.js @@ -0,0 +1,77 @@ +'use strict'; + +var minilog = require('minilog') + , errorModule = require('./lib/errors') + , errors = errorModule.errors + , createError = errorModule.createError + , mediaTypes = require('./lib/media_types') + , Builder = require('./lib/builder') + , mediaTypeRegistry = require('./lib/media_type_registry'); + +// activate this line to enable logging +if (process.env.TRAVERSON_LOGGING) { + require('minilog').enable(); +} + +// export builder for traverson-angular +exports._Builder = Builder; + +/** + * Creates a new request builder instance. + */ +exports.newRequest = function newRequest() { + return new Builder(); +}; + +/** + * Creates a new request builder instance with the given root URL. + */ +exports.from = function from(url) { + var builder = new Builder(); + builder.from(url); + return builder; +}; + +// Provided for backward compatibility with pre-1.0.0 versions. +// The preferred way is to use newRequest() or from() to create a request +// builder and either set the media type explicitly by calling json() on the +// request builder instance - or use content negotiation. +exports.json = { + from: function(url) { + var builder = new Builder(); + builder.from(url); + builder.setMediaType(mediaTypes.JSON); + return builder; + } +}, + +// Provided for backward compatibility with pre-1.0.0 versions. +// The preferred way is to use newRequest() or from() to create a request +// builder and then either set the media type explicitly by calling jsonHal() on +// the request builder instance - or use content negotiation. +exports.jsonHal = { + from: function(url) { + if (!mediaTypeRegistry.get(mediaTypes.JSON_HAL)) { + throw createError('JSON HAL adapter is not registered. From version ' + + '1.0.0 on, Traverson has no longer built-in support for ' + + 'application/hal+json. HAL support was moved to a separate, optional ' + + 'plug-in. See https://github.com/traverson/traverson-hal', + errors.UnsupportedMediaType + ); + } + var builder = new Builder(); + builder.from(url); + builder.setMediaType(mediaTypes.JSON_HAL); + return builder; + } +}; + +// expose media type registry so that media type plug-ins can register +// themselves +exports.registerMediaType = mediaTypeRegistry.register; + +// re-export media type constants +exports.mediaTypes = mediaTypes; + +// re-export error names +exports.errors = errors; diff --git a/pool/shard001/JavaScript/0006151_test.events.js b/pool/shard001/JavaScript/0006151_test.events.js new file mode 100644 index 0000000000000000000000000000000000000000..7a1bd8ea7e036e918ce901aa5cbeff8567830722 --- /dev/null +++ b/pool/shard001/JavaScript/0006151_test.events.js @@ -0,0 +1,113 @@ +'use strict'; + +var adapters = ['local', 'http']; + +adapters.forEach(function (adapter) { + describe('test.events.js-' + adapter, function () { + + var dbs = {}; + beforeEach(function (done) { + dbs.name = testUtils.adapterUrl(adapter, 'testdb'); + testUtils.cleanup([dbs.name], done); + }); + + after(function (done) { + testUtils.cleanup([dbs.name], done); + }); + + + it('PouchDB emits creation event', function (done) { + PouchDB.once('created', function (name) { + name.should.equal(dbs.name, 'should be same thing'); + done(); + }); + new PouchDB(dbs.name); + }); + + it('PouchDB emits destruction event', function (done) { + new PouchDB(dbs.name, function (err, db) { + db.destroy(); + }).once('destroyed', function () { + new PouchDB(dbs.name, function () { + done(); + }); + }); + }); + + it('PouchDB emits destruction event on PouchDB object', function (done) { + PouchDB.once('destroyed', function (name) { + name.should.equal(dbs.name, 'should have the same name'); + new PouchDB(dbs.name, function () { + done(); + }); + }); + new PouchDB(dbs.name, function (err, db) { + db.destroy(); + }); + }); + + it('PouchDB emits destroyed when using {name: foo}', function () { + return new PouchDB({name: 'testdb'}).then(function (db) { + return new testUtils.Promise(function (resolve) { + PouchDB.once('destroyed', function (name) { + name.should.equal('testdb'); + resolve(); + }); + db.destroy(); + }); + }); + }); + + it('db emits destroyed on all DBs', function () { + var db1 = new PouchDB('testdb'); + var db2 = new PouchDB('testdb'); + + return new testUtils.Promise(function (resolve) { + var called = 0; + function checkDone() { + if (++called === 2) { + resolve(); + } + } + db1.once('destroyed', checkDone); + db2.once('destroyed', checkDone); + db1.destroy(); + }); + }); + + it('3900 db emits destroyed event', function () { + return new PouchDB('testdb').then(function (db) { + return new testUtils.Promise(function (resolve) { + db.once('destroyed', function () { + resolve(); + }); + db.destroy(); + }); + }); + }); + + it('3900 db emits destroyed event 2', function () { + var db = new PouchDB('testdb'); + return new testUtils.Promise(function (resolve) { + db.once('destroyed', function () { + resolve(); + }); + db.destroy(); + }); + }); + + it('emit creation event', function (done) { + var db = new PouchDB(dbs.name).on('created', function (newDB) { + db.should.equal(newDB, 'should be same thing'); + done(); + }); + }); + + it('#4168 multiple constructor calls don\'t leak listeners', function () { + for (var i = 0; i < 50; i++) { + new PouchDB(dbs.name); + } + }); + + }); +}); diff --git a/pool/shard001/JavaScript/0006154_codeCellOutputWidget.js b/pool/shard001/JavaScript/0006154_codeCellOutputWidget.js new file mode 100644 index 0000000000000000000000000000000000000000..2e16ab22aa852585687e7b966ba58dc622bf346b --- /dev/null +++ b/pool/shard001/JavaScript/0006154_codeCellOutputWidget.js @@ -0,0 +1,164 @@ +/*global define*/ +/*jslint white:true,browser:true*/ + +define([ + 'bluebird', + 'notebook/js/outputarea', + 'kb_common/html', + '../events', + '../utils', + '../methodCellController', + 'bootstrap' +], function (Promise, OutputArea, html, Events, utils, MethodCellController) { + 'use strict'; + + function factory(config) { + var container, + cell, + t = html.tag, + div = t('div'), + span = t('span'), + table = t('table'), tr = t('tr'), td = t('td'), th = t('th'); + + // RENDERING + + function renderLayout() { + var events = Events.make(), + content = div({dataElement: 'output-widget-form', class: 'container-fluid'}, [ + // Insert fields into here. + utils.buildPanel({ + title: 'Run Status', + name: 'run-bar', + hidden: false, + type: 'default', + body: [ + div({style: {lineHeight: '20px'}}, [ + span({ + }, [ + span('Launch:'), + span({ + style: {border: '1px silver solid', padding: '4px', display: 'inline-block', minWidth: '20px', backgroundColor: 'gray', color: '#FFF'}, + dataElement: 'launch-time' + }) + ]), + span({ + }, [ + span('Queue:'), + span({ + style: {border: '1px silver solid', padding: '4px', display: 'inline-block', minWidth: '20px', backgroundColor: 'gray', color: '#FFF'}, + dataElement: 'queue-time' + }) + ]), + span({ + }, [ + span('Running:'), + span({ + style: {border: '1px silver solid', padding: '4px', display: 'inline-block', minWidth: '20px', backgroundColor: 'gray', color: '#FFF'}, + dataElement: 'running-time' + }) + ]), + span({ + }, [ + span('Sucess:'), + span({ + style: {border: '1px silver solid', padding: '4px', display: 'inline-block', minWidth: '20px', backgroundColor: 'gray', color: '#FFF'}, + dataElement: 'success-time' + }) + ]), + span({ + }, [ + span('Error:'), + span({ + style: {border: '1px silver solid', padding: '4px', display: 'inline-block', minWidth: '20px', backgroundColor: 'gray', color: '#FFF'}, + dataElement: 'error-time' + }) + ]) + ]) + ] + }), + utils.buildPanel({ + title: 'Job Details Status', + name: 'job-details', + hidden: false, + type: 'default', + body: [ + table({class: 'table table-striped'}, [ + tr([th('Job Id'), td({dataElement: 'id'})]), + tr([th('Status'), td({dataElement: 'status'})]), + tr([th('Deleted?'), td({dataElement: 'deleted'})]), + tr([th('Submitted'), td({dataElement: 'submitted'})]), + tr([th('Started'), td({dataElement: 'started'})]), + tr([th('Completed'), td({dataElement: 'completed'})]) + ]) + ] + }) + ]); + return { + content: content, + events: events + }; + } + + function renderJobDetails() { + console.log('RENDERING job details') + var details = utils.getMeta(cell, 'jobDetails'); + if (details) { + Object.keys(details).forEach(function (key) { + var value = details[key], + el = utils.getElement(container, ['job-details', key]); + if (el) { + el.innerHTML = value; + } + }); + } + } + + // LIFECYCLE + + function init(config) { + return Promise.try(function () { + cell = MethodCellController.getCell(config.kbaseCellId); + return null; + }); + } + + function attach(node) { + return Promise.try(function () { + container = node; + var layout = renderLayout(); + container.innerHTML = layout.content; + layout.events.attachEvents(); + }); + } + + function start() { + return Promise.try(function () { + // Listen for events + renderJobDetails(); + }); + + } + + function run(params) { + return Promise.try(function () { + return null; + }); + + } + + + + return { + init: init, + attach: attach, + start: start, + run: run + }; + } + + return { + make: function (config) { + return factory(config); + } + }; +}); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006155_sidebar.js b/pool/shard001/JavaScript/0006155_sidebar.js new file mode 100644 index 0000000000000000000000000000000000000000..7d831dede79c92c414f82abb1b02d1cac56ef763 --- /dev/null +++ b/pool/shard001/JavaScript/0006155_sidebar.js @@ -0,0 +1,155 @@ +// Copyright 2015 Endless Mobile, Inc. + +/* exported Sidebar */ + +const Endless = imports.gi.Endless; +const EosKnowledgePrivate = imports.gi.EosKnowledgePrivate; +const Gdk = imports.gi.Gdk; +const GLib = imports.gi.GLib; +const GObject = imports.gi.GObject; +const Gtk = imports.gi.Gtk; + +const Module = imports.framework.interfaces.module; +const Utils = imports.framework.utils; + +/** + * Class: Sidebar + * Template with a sidebar and content area + * + * CSS Styles: + * sidebar-template - on the template + * sidebar - a frame containing the sidebar module + * content - a frame containing the content module + */ +var Sidebar = new Module.Class({ + Name: 'Layout.Sidebar', + Extends: Endless.CustomContainer, + + Properties: { + /** + * Property: sidebar-first + * True if the sidebar should be first in the reading direction. + */ + 'sidebar-first': GObject.ParamSpec.boolean('sidebar-first', 'Sidebar First', 'Sidebar First', + GObject.ParamFlags.READWRITE | GObject.ParamFlags.CONSTRUCT_ONLY, true), + }, + StyleProperties: { + 'sidebar-width-large': GObject.ParamSpec.int('sidebar-width-large', + 'Sidebar Width Large', 'Sidebar Width Large', + GObject.ParamFlags.READABLE, 0, GLib.MAXINT32, 400), + 'sidebar-width-small': GObject.ParamSpec.int('sidebar-width-small', + 'Sidebar Width Small', 'Sidebar Width Small', + GObject.ParamFlags.READABLE, 0, GLib.MAXINT32, 240), + 'threshold-width-large': GObject.ParamSpec.int('threshold-width-large', + 'Threshold Width Large', 'Threshold Width Large', + GObject.ParamFlags.READABLE, 0, GLib.MAXINT32, 800), + }, + + Slots: { + 'sidebar': {}, + 'content': {}, + }, + + _init: function (props={}) { + props.expand = true; + this.parent(props); + + this.content_frame = new Gtk.Frame({ + expand: true, + }); + this.sidebar_frame = new Gtk.Frame({ + expand: false, + }); + + this._sidebar = this.create_submodule('sidebar'); + this._content = this.create_submodule('content'); + + this.content_frame.add(this._content); + this.sidebar_frame.add(this._sidebar); + this.add(this.content_frame); + this.add(this.sidebar_frame); + + this.content_frame.get_style_context().add_class('content'); + this.sidebar_frame.get_style_context().add_class('sidebar'); + + this.connect('style-set', () => this._update_custom_style()); + this.connect('style-updated', () => this._update_custom_style()); + }, + + _update_custom_style: function () { + let threshold_width_large = EosKnowledgePrivate.style_context_get_custom_int(this.get_style_context(), + 'threshold-width-large'); + let sidebar_width_large = EosKnowledgePrivate.style_context_get_custom_int(this.get_style_context(), + 'sidebar-width-large'); + let sidebar_width_small = EosKnowledgePrivate.style_context_get_custom_int(this.get_style_context(), + 'sidebar-width-small'); + if (typeof this._threshold_width_large !== 'undefined' && + typeof this._sidebar_width_large !== 'undefined' && + typeof this._sidebar_width_small !== 'undefined' && + this._threshold_width_large === threshold_width_large && + this._sidebar_width_large === sidebar_width_large && + this._sidebar_width_small === sidebar_width_small) + return; + this._threshold_width_large = threshold_width_large; + this._sidebar_width_large = sidebar_width_large; + this._sidebar_width_small = sidebar_width_small; + this.queue_resize(); + }, + + vfunc_get_request_mode: function () { + return Gtk.SizeRequestMode.HEIGHT_FOR_WIDTH; + }, + + _get_sidebar_width: function (width) { + let [content_min,] = this.content_frame.get_preferred_width(); + let [sidebar_min,] = this.sidebar_frame.get_preferred_width(); + + let sidebar_width = this._sidebar_width_small; + if (width - content_min >= this._sidebar_width_large && + width >= this._threshold_width_large) + sidebar_width = this._sidebar_width_large; + return Math.max(sidebar_width, sidebar_min); + }, + + vfunc_get_preferred_height_for_width: function (width) { + let sidebar_width = this._get_sidebar_width(width); + let content_width = width - sidebar_width; + let [content_min, content_nat] = this.content_frame.get_preferred_height_for_width(content_width); + let [sidebar_min, sidebar_nat] = this.sidebar_frame.get_preferred_height_for_width(sidebar_width); + return [Math.max(content_min, sidebar_min), Math.max(content_nat, sidebar_nat)]; + }, + + vfunc_get_preferred_width: function () { + let [content_min, content_nat] = this.content_frame.get_preferred_width(); + let [sidebar_min, sidebar_nat] = this.sidebar_frame.get_preferred_width(); + let min = Math.max(sidebar_min, this._sidebar_width_small) + content_min; + let nat = Math.max(sidebar_min, this._sidebar_width_large) + content_nat; + return [min, nat]; + }, + + vfunc_size_allocate: function (alloc) { + this.parent(alloc); + + let sidebar_width = this._get_sidebar_width(alloc.width); + let content_width = alloc.width - sidebar_width; + + let sidebar_left = this.sidebar_first; + if (this.get_direction() === Gtk.TextDirection.RTL) + sidebar_left = !sidebar_left; + this.sidebar_frame.size_allocate(new Gdk.Rectangle({ + x: alloc.x + (sidebar_left ? 0 : content_width), + y: alloc.y, + width: sidebar_width, + height: alloc.height, + })); + this.content_frame.size_allocate(new Gdk.Rectangle({ + x: alloc.x + (sidebar_left ? sidebar_width : 0), + y: alloc.y, + width: content_width, + height: alloc.height, + })); + Utils.set_container_clip(this); + }, + + vfunc_draw: Utils.vfunc_draw_background_default, +}); diff --git a/pool/shard001/JavaScript/0006157_tagfilter.js b/pool/shard001/JavaScript/0006157_tagfilter.js new file mode 100644 index 0000000000000000000000000000000000000000..2616ffb8c177758540103f1d7efc90a8c9c513a7 --- /dev/null +++ b/pool/shard001/JavaScript/0006157_tagfilter.js @@ -0,0 +1,20 @@ +'use strict'; + +describe('Filter: tagFilter', function () { + + // load the filter's module + beforeEach(module('openstorefrontApp')); + + // initialize a new instance of the filter before each test + var tagFilter; + beforeEach(inject(function ($filter) { + tagFilter = $filter('tagFilter'); + })); + + it('should return what you feed into it', function () { + //var theArr = [123, 456, 7890, -99, '-a' , 'TheEND!']; + var theObj = [{something: 'blah'}, {something2: 'blah'}]; + expect(tagFilter(theObj)).toBe(theObj); + }); + +}); diff --git a/pool/shard001/JavaScript/0006158_feedback.js b/pool/shard001/JavaScript/0006158_feedback.js new file mode 100644 index 0000000000000000000000000000000000000000..5ffea5b9af008c9434a59939cc5e2a09df0ca52e --- /dev/null +++ b/pool/shard001/JavaScript/0006158_feedback.js @@ -0,0 +1,160 @@ +/** + * @title WET-BOEW Feedback form + * @overview Allows users to submit feedback for a specific Web page or Web site. + * @license wet-boew.github.io/wet-boew/License-en.html / wet-boew.github.io/wet-boew/Licence-fr.html + * @author @pjackson28 + */ +( function( $, window, document, wb ) { +"use strict"; + +/* + * Variable and function definitions. + * These are global to the plugin - meaning that they will be initialized once per page, + * not once per instance of plugin on the page. So, this is a good place to define + * variables that are common to all instances of the plugin on a page. + */ +var componentName = "wb-fdbck", + selector = "." + componentName, + initEvent = "wb-init" + selector, + $document = wb.doc, + fbrsn, fbaxs, fbcntc1, fbcntc2, $fbweb, $fbmob, $fbcomp, $fbinfo, + + /** + * @method init + * @param {jQuery Event} event Event that triggered this handler + */ + init = function( event ) { + + // Start initialization + // returns DOM object = proceed with init + // returns undefined = do not proceed with init (e.g., already initialized) + var elm = wb.init( event, componentName, selector ), + referrerUrl = document.referrer, + $elm, $fbrsn, urlParams; + + if ( elm ) { + $elm = $( elm ); + $fbrsn = $elm.find( "#fbrsn" ); + urlParams = wb.pageUrlParts.params; + + // Cache the form areas + fbrsn = $fbrsn[ 0 ]; + fbaxs = document.getElementById( "fbaxs" ); + fbcntc1 = document.getElementById( "fbcntc1" ); + fbcntc2 = document.getElementById( "fbcntc2" ); + $fbweb = $elm.find( "#fbweb" ); + $fbmob = $fbweb.find( "#fbmob" ); + $fbcomp = $fbweb.find( "#fbcomp" ); + $fbinfo = $elm.find( "#fbinfo" ); + + // Set the initial value for the fbrsn field based on the query string + if ( !urlParams.submit && urlParams.fbrsn ) { + $fbrsn.find( "option[value='" + urlParams.fbrsn + "']" ).attr( "selected", "selected" ); + } + + // Set aria-controls + fbrsn.setAttribute( "aria-controls", "fbweb" ); + fbaxs.setAttribute( "aria-controls", "fbmob fbcomp" ); + + // Set the initial show/hide state of the form + showHide( fbrsn ); + showHide( fbaxs ); + showHide( fbcntc1 ); + showHide( fbcntc2 ); + + // Prepopulates URL form field with referrer + document.getElementById( "fbpg" ).setAttribute( "value", referrerUrl ); + + // Identify that initialization has completed + wb.ready( $elm, componentName ); + } + }, + + /** + * @method showHide + * @param {DOM element} elm The element triggering the show/hide + */ + showHide = function( elm ) { + var $hide, $show, + classHide = "hide", + classShow = "show", + funcToggle = "toggle", + targetId = elm.id; + + switch ( targetId ) { + case "fbrsn": + if ( elm.value === "web" ) { + $show = $fbweb; + } else { + $hide = $fbweb; + } + break; + case "fbaxs": + if ( elm.value === "mobile" ) { + $show = $fbmob; + $hide = $fbcomp; + } else { + $show = $fbcomp; + $hide = $fbmob; + } + break; + case "fbcntc1": + case "fbcntc2": + if ( document.getElementById( "fbcntc1" ).checked || document.getElementById( "fbcntc2" ).checked ) { + $show = $fbinfo; + } else { + $hide = $fbinfo; + } + break; + } + + // Element to show + if ( $show ) { + $show + .attr( "aria-hidden", "false" ) + .wb( funcToggle, classShow, classHide ); + } + + // Element to hide + if ( $hide ) { + $hide + .attr( "aria-hidden", "true" ) + .wb( funcToggle, classHide, classShow ); + } + }; + +// Bind the init event of the plugin +$document.on( "timerpoke.wb " + initEvent, selector, init ); + +// Show/hide form areas when certain form fields are changed +$document.on( "keydown click change", "#fbrsn, #fbaxs, #fbcntc1, #fbcntc2", function( event ) { + var which = event.which; + + // Ignore middle/right mouse buttons + if ( !which || which === 1 ) { + showHide( event.target ); + } +} ); + +// Return to the form defaults when the reset button is activated +$document.on( "click", selector + " input[type=reset]", function( event ) { + var which = event.which; + + // Ignore middle/right mouse buttons + if ( !which || which === 1 ) { + + // Manually reset the form as this event handler can be triggered + // before the browser invokes the native form reset. + event.target.form.reset(); + + showHide( fbrsn ); + showHide( fbaxs ); + showHide( fbcntc1 ); + showHide( fbcntc2 ); + } +} ); + +// Add the timer poke to initialize the plugin +wb.add( selector ); + +} )( jQuery, window, document, wb ); diff --git a/pool/shard001/JavaScript/0006159_personas.js b/pool/shard001/JavaScript/0006159_personas.js new file mode 100644 index 0000000000000000000000000000000000000000..142476eb612f95caac6946f8680d7a9712bfc5c3 --- /dev/null +++ b/pool/shard001/JavaScript/0006159_personas.js @@ -0,0 +1,318 @@ +var express = require('express'); +var router = express.Router(); +//var mongoose = require('mongoose'); +//var ObjectId = mongoose.Types.ObjectId; + +/* +function checkUserAccess(req, req_level) { + var userid = JSON.parse(req.cookies.userid); + if (!(userid in req.product.permLookup) || req.product.permLookup[userid] < req_level) { + var err = new Error("Unauthorized"); + err.status = 401; + return err; + } +} +*/ + +// ***** user personas ***** + +// get user personas +router.get('/', function(req, res, next) { +/* + var err = checkUserAccess(req, 1); + if (err) return next(err); +*/ + return res.json(req.product.personas); +}); + +// add user persona +router.post('/', function(req, res, next) { + +/* + var err = checkUserAccess(req, 2); + if (err) return next(err); +*/ + + var prod = req.product; + var newpersona = req.body.value; + + prod.personas.push({name: newpersona}); + + return prod.save(function(err) { + if (err) { + return next(err); + } else { + return res.json(prod.personas[prod.personas.length-1]); + } + }); +}); + +// persona index +router.param('persona_ix', function(req, res, next) { + // TODO: assert ix is a normal int + var ix = req.params.persona_ix; + var prod = req.product; + if (ix && ix < prod.personas.length) { + req.personaIx = ix; // need to save just the index because we're saving the entire product document to the db + return next(); + } + var err = new Error('No such user type'); + err.status = 404; + return next(err); +}); + +// change user persona +router.put('/:persona_ix', function(req, res, next) { + +/* + var err = checkUserAccess(req, 2); + if (err) return next(err); +*/ + + var prod = req.product; + var ix = req.personaIx; + + prod.personas[ix].name = req.body.value; + + return prod.save(function(err) { + if (err) { // TODO: convert to next(err)? + return res.json({ + success: false, + error: err + }); + } else { + return res.json({ + success: true + }); + } + }); +}); + +// delete user persona +router.delete('/:persona_ix', function(req, res, next) { + +/* + var err = checkUserAccess(req, 2); + if (err) return next(err); +*/ + + var prod = req.product; + //if (req.body.ix) { + var ix = req.personaIx; + //var ix = req.body.ix; + prod.personas.splice(ix, 1); + + return prod.save(function(err) { + if (err || !prod) { + return res.json({ + success: false, + error: err + }); + } else { + return res.json({ + success: true + }); + } + }); + //} + + // TODO: remove this/put in the param thing above + var err = new Error('Invalid request; index not specified'); + err.status = 400; + return next(err); +}); + +// ****** persona evidence ***** + +// get persona evidence +router.get('/:persona_ix/evidence', function(req, res, next) { +/* + var err = checkUserAccess(req, 1); + if (err) return next(err); +*/ + var prod = req.product; + var ix = req.personaIx; + return res.json(prod.personas[ix].evidence); +}); + +// add persona evidence +router.post('/:persona_ix/evidence', function(req, res, next) { + +/* + var err = checkUserAccess(req, 2); + if (err) return next(err); +*/ + + var prod = req.product; + var ix = req.personaIx; + + var ev = { + name: req.body.name, + url: req.body.url, + icon: req.body.icon + }; + + if (!('evidence' in prod.personas[ix])) { + prod.personas[ix].evidence = []; + } + prod.personas[ix].evidence.push(ev); + + return prod.save(function(err) { + if (err) { // TODO: convert to next(err)? + return res.json({ + success: false, + error: err + }); + } else { + return res.json({ + success: true + }); + } + }); +}); + +router.param('ev_ix', function(req, res, next) { + // TODO: assert ev_ix is a normal int + var ix = req.params.ev_ix; + var prod = req.product; + if (ix && ix < prod.personas[req.personaIx].evidence.length) { + req.evIx = ix; + return next(); + } + var err = new Error('No such evidence file'); + err.status = 404; + return next(err); +}); + +// delete persona evidence +router.delete('/:persona_ix/evidence/:ev_ix', function(req, res, next) { + +/* + var err = checkUserAccess(req, 2); + if (err) return next(err); +*/ + + var prod = req.product; + var ix = req.evIx; + prod.personas[req.personaIx].evidence.splice(ix, 1); + + return prod.save(function(err) { + if (err || !prod) { + return res.json({ + success: false, + error: err + }); + } else { + return res.json({ + success: true + }); + } + }); + + var err = new Error('Invalid request; index not specified'); + err.status = 400; + return next(err); +}); + +// ***** persona trends ****** + +// get persona trends +router.get('/:persona_ix/evidence/:ev_ix/trends', function(req, res, next) { +/* + var err = checkUserAccess(req, 1); + if (err) return next(err); +*/ + var prod = req.product; + var personaIx = req.personaIx; + var evIx = req.evIx; + return res.json(prod.personas[personaIx].evidence[evIx].trends); +}); + +// add persona trends +router.post('/:persona_ix/evidence/:ev_ix/trends', function(req, res, next) { + +/* + var err = checkUserAccess(req, 2); + if (err) return next(err); +*/ + + var prod = req.product; + var personaIx = req.personaIx; + var evIx = req.evIx; + + var trend = { + name: req.body.name, + type: req.body.type + }; + + if (!('trends' in prod.personas[personaIx].evidence[evIx])) { + prod.personas[personaIx].evidence[evIx].trends = []; + } + prod.personas[personaIx].evidence[evIx].trends.push(trend); + + return prod.save(function(err) { + if (err) { + next(err); + } else { + return res.json(trend); + } + }); +}); + +// change persona trends +router.put('/:persona_ix/evidence/:ev_ix/trends/:trend_ix', function(req, res, next) { + +/* + var err = checkUserAccess(req, 2); + if (err) return next(err); +*/ + + var prod = req.product; + var personaIx = req.personaIx; + var evIx = req.evIx; + var trendIx = req.params.trend_ix; + var trend = prod.personas[personaIx].evidence[evIx].trends[trendIx]; + + // execute the PUT changes + trend.type = req.body.type; + + return prod.save(function(err) { + if (err) { + return next(err); + } else { + return res.json({ + success: true + }); + } + }); +}); + +// delete persona trend +router.delete('/:persona_ix/evidence/:ev_ix/trends/:trend_ix', function(req, res, next) { + +/* + var err = checkUserAccess(req, 2); + if (err) return next(err); +*/ + + var prod = req.product; + var personaIx = req.personaIx; + var evIx = req.evIx; + var trendIx = req.params.trend_ix; + prod.personas[personaIx].evidence[evIx].trends.splice(trendIx, 1); + + return prod.save(function(err) { + if (err || !prod) { + return res.json({ + success: false, + error: err + }); + } else { + return res.json({ + success: true + }); + } + }); +}); + +module.exports = router; \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006161_response-builder.js b/pool/shard001/JavaScript/0006161_response-builder.js new file mode 100644 index 0000000000000000000000000000000000000000..2717d873ab6c38a8a5f2d0d1343bcb2769071035 --- /dev/null +++ b/pool/shard001/JavaScript/0006161_response-builder.js @@ -0,0 +1,16 @@ +'use strict'; + +const responseStatus = require('./response-status'); + +module.exports = Object.freeze({ + fail: (res, err) => { + // eslint-disable-next-line no-console + console.log(err); + res + .status(responseStatus.INTERNAL_SERVER_ERROR) + .json({ error: err }); + }, + ok: (res, result) => { + res.status(responseStatus.OK).json(result); + } +}); diff --git a/pool/shard001/JavaScript/0006164_app.js b/pool/shard001/JavaScript/0006164_app.js new file mode 100644 index 0000000000000000000000000000000000000000..0ae5034b7131ce3e3b28f440a7728fb392526a85 --- /dev/null +++ b/pool/shard001/JavaScript/0006164_app.js @@ -0,0 +1,122 @@ +var files = ['bag', 'banana', 'bathroom', 'boots', 'breakfast', 'bubblegum', 'chair', 'cthulhu', 'dog-duck', +'dragon', 'pen', 'pet-sweep', 'scissors', 'shark', 'sweep', 'tauntaun', 'unicorn', 'usb', 'water-can', 'wine-glass']; +var totalClicks = 0; +var left = document.getElementById('left'); +var center = document.getElementById('center'); +var right = document.getElementById('right'); +var container = document.getElementById('container'); +var productArray = []; + +var barGraph; +var nameChartData = []; +var clicksChartData = []; +var graphData = { + labels: nameChartData, + datasets: [ + { + data: clicksChartData, + } ] +}; + +function Product(productName) { + this.productName = productName; + this.path = 'img/' + productName + '.jpg'; + this.clicks = 0; + this.displayed = 0; + productArray.push(this); +}; + +function randIndex(min, max) { + return (Math.floor(Math.random() * (max - min)) + min); +} + +function handleProductClick(event) { + if (event.target.id !== 'container') { + totalClicks += 1; + for (var i = 0; i < productArray.length; i++) { + if (event.target.alt === productArray[i].productName) { + productArray[i].clicks += 1; + var lsArray = JSON.stringify(productArray); + localStorage.setItem('productData', lsArray); + } + } + displayProducts(); + } +} + +function handleButtonClick(event) { + document.getElementById('graphBox').hidden = false; + document.getElementById('results').hidden = true; + updateChartData(); + drawGraph(); + alert('Thanks for participating'); +} + +function updateChartData() { + for (var i = 0; i < productArray.length; i++) { + nameChartData[i] = productArray[i].productName; + clicksChartData[i] = productArray[i].clicks; + } +} + +function drawGraph() { + var barCanvas = document.getElementById('graph').getContext('2d'); + barGraph = new Chart(barCanvas, { + type: 'bar', + data: graphData, + options: { + backgroundColor: 'black' + } + }); +} + +function displayProducts() { + if (totalClicks >= 25) { + document.getElementById('results').hidden = false; + // document.getElementById('graphBox').hidden = false; + } else if (totalClicks < 25) { + document.getElementById('results').hidden = true; + document.getElementById('graphBox').hidden = true; + } + var leftIndex = randIndex(0, productArray.length); + productArray[leftIndex].displayed += 1; + left.src = productArray[leftIndex].path; + left.alt = productArray[leftIndex].productName; + + var centerIndex = randIndex(0, productArray.length); + while (centerIndex === leftIndex) { + console.log('Duplicate found between center and left'); + centerIndex = randIndex(0, productArray.length); + } + productArray[centerIndex].displayed += 1; + center.src = productArray[centerIndex].path; + center.alt = productArray[centerIndex].productName; + + var rightIndex = randIndex(0, productArray.length); + while (rightIndex === leftIndex || rightIndex === centerIndex) { + rightIndex = randIndex(0, productArray.length); + } + productArray[rightIndex].displayed += 1; + right.src = productArray[rightIndex].path; + right.alt = productArray[rightIndex].productName; + var lsArray = JSON.stringify(productArray); + localStorage.setItem('productData', lsArray); + +} + +for (var i = 0; i < 20; i++) { + productArray[i] = new Product(files[i]); +} + +if (localStorage.getItem('productData') !== null) { + var storageData = localStorage.getItem('productData'); + storageData = JSON.parse(storageData); + for (var i = 0; i < storageData.length; i++) { + productArray[i].clicks = storageData[i].clicks; + productArray[i].displayed = storageData[i].displayed; + } +} + +container.addEventListener('click', handleProductClick); +document.getElementById('results').addEventListener('click', handleButtonClick); +displayProducts(); diff --git a/pool/shard001/JavaScript/0006165_app.js b/pool/shard001/JavaScript/0006165_app.js new file mode 100644 index 0000000000000000000000000000000000000000..22cdc8bded91e0975e6446ed889726024e0aae38 --- /dev/null +++ b/pool/shard001/JavaScript/0006165_app.js @@ -0,0 +1,50 @@ +'use strict'; + +/* + * Defining the Package + */ +var Module = require('meanio').Module; + +var Dragstar = new Module('dragstar'); + +/* + * All MEAN packages require registration + * Dependency injection is used to define required modules + */ +Dragstar.register(function(app, auth, database) { + + //We enable routing. By default the Package Object is passed to the routes + Dragstar.routes(app, auth, database); + + //We are adding a link to the main menu for all authenticated users + Dragstar.menus.add({ + title: 'dragstar example page', + link: 'dragstar example page', + roles: ['authenticated'], + menu: 'main' + }); + + /** + //Uncomment to use. Requires meanio@0.3.7 or above + // Save settings with callback + // Use this for saving data from administration pages + Dragstar.settings({ + 'someSetting': 'some value' + }, function(err, settings) { + //you now have the settings object + }); + + // Another save settings example this time with no callback + // This writes over the last settings. + Dragstar.settings({ + 'anotherSettings': 'some value' + }); + + // Get settings. Retrieves latest saved settigns + Dragstar.settings(function(err, settings) { + //you now have the settings object + }); + */ + + return Dragstar; +}); diff --git a/pool/shard001/JavaScript/0006166_FctTest.js b/pool/shard001/JavaScript/0006166_FctTest.js new file mode 100644 index 0000000000000000000000000000000000000000..cba67e60fa6c0a31a3cbe11206a80ff7f6e8c683 --- /dev/null +++ b/pool/shard001/JavaScript/0006166_FctTest.js @@ -0,0 +1,246 @@ +// Copyright (c) 2015, Łukasz Walukiewicz . +// Licensed under the MIT License . +// Part of the node-glp2 project . + +'use strict'; + +var util = require('./util'); +var ProgramStep = require('./ProgramStep'); + +module.exports = FctTest; + +var SET_VALUE_BOUNDRIES = { + 0: [0.01, 64, 100], + 1: [1, 15000, 10], + 2: [1, 15000, 10], + 3: [0.01, 1, 100], + 6: [20, 300, 1], + 7: [10, 9999, 1], + 8: [1, 2, 1] +}; + +/** + * @constructor + * @param {object} options + * @param {string} [options.label] + * @param {number} options.step + * @param {number} options.upperToleranceRel + * @param {number} options.startTime + * @param {number} options.duration + * @param {number} options.execution + * @param {number} options.range + * @param {number} options.voltage + * @param {number} options.lowerToleranceAbs + * @param {number} options.upperToleranceAbs + * @param {boolean} options.correction + * @param {boolean} options.leaveOn + * @param {number} options.uTolerance + * @param {number} options.retries + * @param {number} options.lowerToleranceRel + * @param {boolean} options.cancelOnFailure + * @param {number} options.visMode + * @param {number} options.goInput + * @param {number} options.noGoInput + * @param {boolean} options.enabled + * @param {number} options.rsvChannel + * @param {number} options.rsvNumber + * @param {boolean} options.multi + * @param {number} options.trigger + * @throws {Error} + */ +function FctTest(options) +{ + /*jshint -W071*/ + + ProgramStep.call(this, options); + + var setValueBoundries = SET_VALUE_BOUNDRIES[options.mode] || [0, 0, 1]; + + util.validateEnum( + 'mode', + options.mode, + [0, 1, 2, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25] + ); + util.validateNumber('setValue', options.setValue, setValueBoundries[0], setValueBoundries[1]); + util.validateNumber('upperToleranceRel', options.upperToleranceRel, 0, 100); + util.validateNumber('startTime', options.startTime, 0, 86400); + util.validateNumber('duration', options.duration, 0, 86400); + util.validateEnum('execution', options.execution, [0, 1, 2, 4]); + util.validateNumber('range', options.range, 0, 65535); + util.validateNumber('voltage', options.voltage, 0, 400); + util.validateNumber('lowerToleranceAbs', options.lowerToleranceAbs, 0, setValueBoundries[1] * 2); + util.validateNumber('upperToleranceAbs', options.upperToleranceAbs, 0, setValueBoundries[1] * 2); + util.validateBool('correction', options.correction); + util.validateBool('leaveOn', options.leaveOn); + util.validateNumber('uTolerance', options.uTolerance, 0, 100); + util.validateNumber('retries', options.retries, 0, 5); + util.validateNumber('lowerToleranceRel', options.lowerToleranceRel, 0, 100); + util.validateBool('cancelOnFailure', options.cancelOnFailure); + util.validateEnum('visMode', options.visMode, [0, 1]); + util.validateNumber('goInput', options.goInput, 0, 2000); + util.validateNumber('noGoInput', options.noGoInput, 0, 2000); + util.validateBool('enabled', options.enabled); + util.validateEnum('rsvChannel', options.rsvChannel, [0, 1, 2, 3, 4, 5, 6, 7]); + util.validateNumber('rsvNumber', options.rsvNumber, 1, 100); + util.validateBool('multi', options.multi); + util.validateEnum('trigger', options.trigger, [0, 1, 2]); + + this.setValue = Math.round(options.setValue * setValueBoundries[2]) / setValueBoundries[2]; + this.upperToleranceRel = Math.floor(options.upperToleranceRel); + this.startTime = options.startTime; + this.duration = options.duration; + this.execution = options.execution; + this.range = Math.floor(options.range); + this.voltage = Math.floor(options.voltage); + this.lowerToleranceAbs = Math.round(options.lowerToleranceAbs * setValueBoundries[2]) / setValueBoundries[2]; + this.upperToleranceAbs = Math.round(options.upperToleranceAbs * setValueBoundries[2]) / setValueBoundries[2]; + this.correction = util.bool(options.correction); + this.mode = options.mode; + this.leaveOn = util.bool(options.leaveOn); + this.uTolerance = Math.floor(options.uTolerance); + this.rMin = 0; + this.retries = Math.floor(options.retries); + this.lowerToleranceRel = Math.floor(options.lowerToleranceRel); + this.cancelOnFailure = util.bool(options.cancelOnFailure); + this.visMode = options.visMode; + this.goInput = Math.floor(options.goInput); + this.noGoInput = Math.floor(options.noGoInput); + this.enabled = util.bool(options.enabled); + this.rsvChannel = options.rsvChannel; + this.rsvNumber = Math.floor(options.rsvNumber); + this.multi = util.bool(options.multi); + this.trigger = options.trigger; +} + +util.inherits(FctTest, ProgramStep); + +/** + * @enum {number} + */ +FctTest.Mode = { + CURRENT: 0, + APPARENT_POWER: 1, + ACTIVE_POWER: 2, + COS_PHI: 3, + VISUAL_CHECK: 5, + RESIDUAL_VOLTAGE: 6, + RPM: 7, + SENSE_OF_ROTATION: 8, + ANALOG_0: 9, + ANALOG_1: 10, + ANALOG_2: 11, + ANALOG_3: 12, + ANALOG_4: 13, + ANALOG_5: 14, + ANALOG_6: 15, + ANALOG_7: 16, + ANALOG_8: 17, + ANALOG_9: 18, + ANALOG_10: 19, + ANALOG_11: 20, + ANALOG_12: 21, + ANALOG_13: 22, + ANALOG_14: 23, + ANALOG_15: 24, + FI: 25 +}; + +/** + * @enum {number} + */ +FctTest.Execution = { + AUTO: 0, + HOLD_START: 1, + STOP_BEFORE_TEST: 2, + STOP_AFTER_TEST: 4 +}; + +/** + * @enum {number} + */ +FctTest.VisMode = { + NORMAL: 0, + CONDITIONAL: 1 +}; + +/** + * @enum {number} + */ +FctTest.RsvChannel = { + L1_N: 0, + L1_PE: 1, + N_PE: 2, + L2_N: 3, + L1_L2: 4, + L3_N: 5, + L1_L3: 6, + L2_L3: 7 +}; + +/** + * @enum {number} + */ +FctTest.Trigger = { + START_TIME: 0, + STARTING_SIGNAL: 1, + MEASURED_VALUE: 2 +}; + +/** + * @returns {FctTest} + */ +FctTest.fromObject = function(obj) +{ + if (obj instanceof FctTest) + { + return obj; + } + + return new FctTest(obj); +}; + +/** + * @returns {number} + */ +FctTest.prototype.getTotalTime = function() +{ + return (this.startTime + this.duration) * 1000; +}; + +/** + * @param {number} [step] + * @returns {string} + */ +FctTest.prototype.serializeCommand = function(step) +{ + var fractionalDigits = Math.log10((SET_VALUE_BOUNDRIES[this.mode] || [0, 0, 1])[2]); + + return 'F9-' + [ + step || this.step, + this.setValue.toFixed(fractionalDigits), + this.upperToleranceRel, + Math.floor(this.startTime * 1000), + Math.floor(this.duration * 1000), + this.execution, + this.range, + this.voltage, + this.upperToleranceAbs.toFixed(fractionalDigits), + this.lowerToleranceAbs.toFixed(fractionalDigits), + this.correction, + this.mode, + this.leaveOn, + this.uTolerance, + this.rMin, + this.retries, + this.lowerToleranceRel, + this.cancelOnFailure, + this.visMode, + this.goInput, + this.noGoInput, + this.enabled ? 0 : 1, + this.rsvChannel, + this.rsvNumber, + this.multi, + this.trigger + ].join('_'); +}; diff --git a/pool/shard001/JavaScript/0006167_index.js b/pool/shard001/JavaScript/0006167_index.js new file mode 100644 index 0000000000000000000000000000000000000000..bde0efce8a33d98ebba592d09eb6322c83087921 --- /dev/null +++ b/pool/shard001/JavaScript/0006167_index.js @@ -0,0 +1,38 @@ +const WindowsUpdater = require('./lib/WindowsUpdater'), + DarwinUpdater = require('./lib/DarwinUpdater'), + LinuxUpdater = require('./lib/LinuxUpdater'), + LinuxAutoUpdater = require('./lib/autoUpdater/LinuxAutoUpdater'), + + WINDOWS = 'Windows_NT', + DARWIN = 'Darwin', + LINUX = 'Linux', + + + /** + * @method initializeUpdater + * @description Provides the updater class Instance based on the OS. + * It uses Node.os.type() to detect the os. + * https://nodejs.org/dist/latest-v8.x/docs/api/os.html#os_os_type + * + * @returns {?Object} WindowsAutoUpdate || DarwinUpdater || LinuxUpdater || null + */ + init = function init (options = {}) { + const { adapter } = options, + os = require('os').type(), + updaterOptions = { adapter, autoUpdater: adapter.getAutoUpdater() }; + + switch (os) { + case WINDOWS: + return new WindowsUpdater(updaterOptions); + case DARWIN: + return new DarwinUpdater(updaterOptions); + case LINUX: + return new LinuxUpdater(Object.assign(updaterOptions, { + autoUpdater: new LinuxAutoUpdater({ quitApp: adapter.quitApp }) + })); + default: + return null; + } + }; + +module.exports = { init }; diff --git a/pool/shard001/JavaScript/0006169_flood.js b/pool/shard001/JavaScript/0006169_flood.js new file mode 100644 index 0000000000000000000000000000000000000000..c0f96cac67acf5121499e350190b8521134ca3ac --- /dev/null +++ b/pool/shard001/JavaScript/0006169_flood.js @@ -0,0 +1,152 @@ +#!/usr/bin/env node +// Copyright (c) 2012 Ian C. Good +// +// 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. +// + +var cluster = require('cluster'), + crypto = require('crypto'), + assert = require('assert'), + npm = require('npm'), + os = require('os'), + fs = require('fs'), + http = require('http'), + url = require('url'), + path = require('path'), + argv = require('minimist')(process.argv.slice(2)); + +if (argv.help) { + console.log('usage: '+process.argv.slice(0, 2).join(' ')+' [options]'); + console.log(' --help Display this help.'); + console.log(' --port Run on a custom port, default 5143'); + console.log(' --public-key Path to the public key,'); + console.log(' default /etc/flood/public.pem'); + process.exit(0); +} + +var snapshots = require('../lib/snapshots'); + +cluster.setupMaster({ + exec: __dirname+'/../lib/worker.js', +}); + +var pubkeyFile = argv['public-key'] || '/etc/flood/public.pem', + pubkey = fs.readFileSync(pubkeyFile); + + +function killAll(workers) { + var i; + for (i=0; i 0 ? numWorkers : os.cpus().length + numWorkers, + file: fileParts.join(''), + env: JSON.parse(req.headers['x-env'] || null), + }; + + var deps = JSON.parse(req.headers['x-dependencies'] || null); + installDeps(deps, function () { + startTest(options, res); + }); + }); +}); +server.setTimeout(0); + +server.listen(argv.port || 5143); + +// vim:ft=javascript:et:sw=2:ts=2:sts=2: diff --git a/pool/shard001/JavaScript/0006181_index.js b/pool/shard001/JavaScript/0006181_index.js new file mode 100644 index 0000000000000000000000000000000000000000..0ece1e7c391778ea81f83330bf7ef699e9b41078 --- /dev/null +++ b/pool/shard001/JavaScript/0006181_index.js @@ -0,0 +1,13 @@ +import "./index.css"; +import generateText from "./sub"; +import $ from "jquery"; +import moment from "moment"; + +let app = document.createElement('div'); +const myPromise = Promise.resolve(42); +myPromise.then((number) => { + $('body').append('

    promise result is ' + number + ' now is ' + moment().format() + '

    '); +}); +app.innerHTML = '

    Hello World it

    '; +document.body.appendChild(app); +app.appendChild(generateText()); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006186_json.js b/pool/shard001/JavaScript/0006186_json.js new file mode 100644 index 0000000000000000000000000000000000000000..edbba01ffa3fe0bb81a2cec34e4d84647e58af20 --- /dev/null +++ b/pool/shard001/JavaScript/0006186_json.js @@ -0,0 +1,40 @@ +var expect = require('chai').expect; +var sinon = require('sinon'); + +var Checker = require('../../../lib/checker'); +var json = require('../../../lib/reporters/json'); + +describe('reporters/json', function() { + var checker; + + beforeEach(function() { + checker = new Checker(); + checker.registerDefaultRules(); + checker.configure({disallowKeywords: ['with']}); + sinon.stub(console, 'log'); + }); + + afterEach(function() { + console.log.restore(); + }); + + it('should correctly reports no errors', function() { + json([checker.checkString('a++;')]); + expect(console.log).to.have.callCount(0); + }); + + it('should correctly reports 1 error', function() { + json([checker.checkString('with (x) {}')]); + var resultStr = '{"input":[{"line":1,"column":3,"message":"disallowKeywords: Illegal keyword: with"}]}'; + expect(console.log.getCall(0).args[0]).to.equal(resultStr); + expect(console.log).to.have.callCount(1); + }); + + it('should correctly reports 2 errors', function() { + json([checker.checkString('with (x) {} with (x) {}')]); + var resultStr = '{"input":[{"line":1,"column":3,"message":"disallowKeywords: Illegal keyword: with"},' + + '{"line":1,"column":15,"message":"disallowKeywords: Illegal keyword: with"}]}'; + expect(console.log.getCall(0).args[0]).to.equal(resultStr); + expect(console.log).to.have.callCount(1); + }); +}); diff --git a/pool/shard001/JavaScript/0006189_FiltersEditor.js b/pool/shard001/JavaScript/0006189_FiltersEditor.js new file mode 100644 index 0000000000000000000000000000000000000000..e173ec2dfe98334c8dd808764cbd9ef08ede2e33 --- /dev/null +++ b/pool/shard001/JavaScript/0006189_FiltersEditor.js @@ -0,0 +1,216 @@ +/*! + * ${copyright} + */ +sap.ui.define([ + "sap/ui/integration/designtime/baseEditor/propertyEditor/BasePropertyEditor", + "sap/ui/integration/designtime/cardEditor/propertyEditor/complexMapEditor/ComplexMapEditor", + "sap/base/util/restricted/_merge", + "sap/ui/integration/cards/filters/DateRangeFilter" +], function ( + BasePropertyEditor, + ComplexMapEditor, + _merge, + DateRangeFilter +) { + "use strict"; + + /** + * @class + * Constructor for a new FiltersEditor. + * + *

    Configuration

    + * + * Configuration is inherited from {@link sap.ui.integration.designtime.cardEditor.propertyEditor.complexMapEditor.ComplexMapEditor} + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
    OptionTypeDefaultDescription
    allowedTypesstring[][]Allowed filter types
    + * + * @extends sap.ui.integration.designtime.cardEditor.propertyEditor.complexMapEditor.ComplexMapEditor + * @alias sap.ui.integration.designtime.cardEditor.propertyEditor.filtersEditor.FiltersEditor + * @author SAP SE + * @since 1.98 + * @version ${version} + * + * @private + * @experimental 1.97 + * @ui5-restricted + */ + var FiltersEditor = ComplexMapEditor.extend("sap.ui.integration.designtime.cardEditor.propertyEditor.filtersEditor.FiltersEditor", { + metadata: { + library: "sap.ui.integration" + }, + renderer: BasePropertyEditor.getMetadata().getRenderer().render + }); + + FiltersEditor.configMetadata = Object.assign({}, ComplexMapEditor.configMetadata, { + allowedValues: { + defaultValue: [], + mergeStrategy: "intersection" + } + }); + + FiltersEditor.prototype.onBeforeConfigChange = function (oConfig) { + var oCustomConfig = {}; + + if (oConfig["allowKeyChange"]) { + // Filter-specific developer scenario + oCustomConfig = { + template: { + key: { + label: this.getI18nProperty("CARD_EDITOR.FILTER.KEY"), + path: "key", + type: "string", + enabled: oConfig.allowKeyChange, + allowBindings: false, + validators: [ + { + type: "isUniqueKey", + config: { + keys: function () { + return Object.keys(this.getValue()); + }.bind(this), + currentKey: function (oPropertyEditor) { + return oPropertyEditor.getValue(); + } + } + } + ] + }, + type: { + label: this.getI18nProperty("CARD_EDITOR.FILTER.TYPE"), + path: "type", + type: "select", + items: (oConfig["allowedTypes"] || []).map(function(sKey){ return { key: sKey }; }), + allowCustomValues: true, + allowBindings: false + }, + label: { + label: this.getI18nProperty("CARD_EDITOR.FILTER.LABEL"), + path: "label", + type: "string" + }, + description: { + label: this.getI18nProperty("CARD_EDITOR.FILTER.DESCRIPTION"), + type: "string", + path: "description", + allowCustomValues: true, + allowBindings: false + }, + value: { + label: this.getI18nProperty("CARD_EDITOR.FILTER.VALUE"), + path: "sValue", + type: "string", + visible: "{= ${type} === 'Select'}" + }, + itemPath: { + label: this.getI18nProperty("CARD_EDITOR.FILTER.ITEM.PATH"), + path: "item/path", + type: "string", + visible: "{= ${type} === 'Select'}", + enabled: "{= ${items} === undefined || ${items} === null}" + }, + itemTemplateKey: { + label: this.getI18nProperty("CARD_EDITOR.FILTER.ITEM.TEMPLATE.KEY"), + path: "item/template/key", + type: "string", + visible: "{= ${type} === 'Select'}", + enabled: "{= ${items} === undefined || ${items} === null}" + }, + itemTemplateTitle: { + label: this.getI18nProperty("CARD_EDITOR.FILTER.ITEM.TEMPLATE.TITLE"), + path: "item/template/title", + type: "string", + visible: "{= ${type} === 'Select'}", + enabled: "{= ${items} === undefined || ${items} === null}" + }, + itemData: { + label: this.getI18nProperty("CARD_EDITOR.FILTER.ITEM.DATA"), + path: "data", + type: "json", + visible: "{= ${type} === 'Select'}", + enabled: "{= ${items} === undefined || ${items} === null}" + }, + items: { + label: this.getI18nProperty("CARD_EDITOR.FILTER.ITEMS"), + path: "items", + type: "json", + visible: "{= ${type} === 'Select'}", + enabled: "{= ${item/template/key} === undefined || ${item/template/key} === ''}" + }, + dateRangeOptions: { + label: this.getI18nProperty("CARD_EDITOR.FILTER.OPTIONS"), + path: "options", + type: "multiSelect", + items: this.getAllDateRangeOptions(), + visible: "{= ${type} === 'DateRange'}" + }, + dateRangeValueOption: { + label: this.getI18nProperty("CARD_EDITOR.FILTER.VALUE.OPTION"), + path: "dValue/option", + type: "select", + items: "{selectedOptions}", + visible: "{= ${type} === 'DateRange'}" + }, + dateRangeValues: { + label: this.getI18nProperty("CARD_EDITOR.FILTER.VALUE.VALUES"), + path: "dValue/values", + type: "textArea", + visible: "{= ${type} === 'DateRange'}" + } + } + }; + } else { + // Config scenario + oCustomConfig = { + collapsibleItems: false, + showItemLabel: false, + template: { + type: { + label: this.getI18nProperty("CARD_EDITOR.FILTER.TYPE"), + type: "select", + path: "type", + items: (oConfig["allowedTypes"] || []).map(function(sKey){ return { key: sKey }; }), + allowCustomValues: false, + allowBindings: false + } + } + }; + } + + var oComplexMapConfig = _merge( + {}, + oCustomConfig, + oConfig + ); + return ComplexMapEditor.prototype.onBeforeConfigChange.call(this, oComplexMapConfig); + }; + + FiltersEditor.prototype.getAllDateRangeOptions = function() { + var dateRangeFilter = new DateRangeFilter(); + var oOptions = dateRangeFilter.getOptions(); + var optionsArray = []; + for (var key in oOptions) { + if (oOptions.hasOwnProperty(key)) { + optionsArray.push({ + key: oOptions[key], + title: oOptions[key] + }); + } + } + return optionsArray; + }; + + return FiltersEditor; +}); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006190_fuzzy.js b/pool/shard001/JavaScript/0006190_fuzzy.js new file mode 100644 index 0000000000000000000000000000000000000000..1a426af01292b53b7caa1c2128495a03eb1ea41a --- /dev/null +++ b/pool/shard001/JavaScript/0006190_fuzzy.js @@ -0,0 +1,55 @@ +const leven = require('leven'); +const { localize, } = require('./localize.js'); + +function filterByExactMatch(data, query, key, languageCode) { + const querySet = [...new Set(query.split(' '))]; + + return data.filter(i => { + const localized = localize(i[key], languageCode); + if (!localized) { + return false; + } + + const dataSet = new Set(localized.toLowerCase().split(' ')); + return new Set(querySet.filter(j => dataSet.has(j))).size; + }); +} + +function normalizedLeven(str1, str2) { + return !str1 && !str2 + ? 0 + : leven(str1, str2) / Math.max(str1.length, str2.length); +} + +module.exports = { + filterByGrade: (data, grade) => { + let filtered; + if (!grade) { + filtered = data.filter(i => !i.promote); + } else { + grade = parseInt(grade, 10); + filtered = data.filter(i => i.grade === grade); + } + + return filtered; + }, + fuzzy: (data, query, key, languageCode) => { + // reduce search space if there are exact matches found + const filtered = filterByExactMatch(data, query, key, languageCode); + if (filtered.length !== 0) { + data = filtered; + } + + // calculate normalized levenshtein edit distances between data and query + const distances = data.map(i => { + const localized = localize(i[key], languageCode); + return localized === null + ? 1 // largest distance possible + : normalizedLeven(query, localized.toLowerCase()); + }); + + // get index of the smallest distance (best match) and return obj + const index = distances.indexOf(Math.min(...distances)); + return data[index]; + }, +}; diff --git a/pool/shard001/JavaScript/0006191_rawContentType.js b/pool/shard001/JavaScript/0006191_rawContentType.js new file mode 100644 index 0000000000000000000000000000000000000000..943b833b3e72d7bc3e03325a875ac75b7b06bb91 --- /dev/null +++ b/pool/shard001/JavaScript/0006191_rawContentType.js @@ -0,0 +1,62 @@ +const server = require('./_servers'), + httpServer = server.createHTTPServer(); + +/** + * Parse raw form-data content + * + * @param {String} raw + * @returns {Array} + * + * Reference: https: //tools.ietf.org/html/rfc7578 + * + * @example + * --boundary + * Content-Disposition: form-data; name="foo" + * Content-Type: text/plain + * + * bar + * --boundary + * + * returns -> [{name: 'foo', contentType: 'text/plain'}] + */ +function parseRaw (raw) { + raw = raw.split('\r\n'); + var boundary = raw[0], + result = [], + data, + match, + i, + ii; + + for (i = 0, ii = raw.length; i < ii; i++) { + if (raw[i] !== boundary) { continue; } + + data = {}; + match = (/\sname="(.*?)"/).exec(raw[++i]); + match && (data.name = match[1]); + + match = (/^Content-Type:\s(.*)$/).exec(raw[++i]); + match && (data.contentType = match[1]); + + Object.keys(data).length && result.push(data); + } + + return result; +} + +httpServer.on('/', function (req, res) { + var rawBody = ''; + + req.on('data', function (chunk) { + rawBody += chunk.toString(); // decode buffer to string + }).on('end', function () { + res.writeHead(200, { + 'Content-Type': 'application/json', + Connection: 'close' + }); + res.end(JSON.stringify(parseRaw(rawBody))); + }); +}); + + +module.exports = httpServer; diff --git a/pool/shard001/JavaScript/0006192_TradeListView.js b/pool/shard001/JavaScript/0006192_TradeListView.js new file mode 100644 index 0000000000000000000000000000000000000000..8c9aa1abf5fe42b12e538d0899eee37b6576ddda --- /dev/null +++ b/pool/shard001/JavaScript/0006192_TradeListView.js @@ -0,0 +1,29 @@ +(function(coinswap) { + +coinswap.TradeListView = Backbone.View.extend({ + template: _.template($('#template-trade-list').html()), + tradeTemplate: _.template($('#template-trade-listitem').html()), + + initialize: function() { + _.bindAll(this, 'render'); + coinswap.trade.on('swap', this.render); + this.render(); + }, + + render: function() { + var t = this; + + console.log('rendering trade list'); + + var swaps = coinswap.trade.pendingSwaps(); + t.$el.html(t.template({ swaps: swaps })); + + var listEl = t.$el.find('ul.list'); + _.each(swaps, function(swap) { + var el = $(t.tradeTemplate(swap)); + listEl.append(el); + }); + } +}); + +})(coinswap); diff --git a/pool/shard001/JavaScript/0006198_max_unrecognized_commands.js b/pool/shard001/JavaScript/0006198_max_unrecognized_commands.js new file mode 100644 index 0000000000000000000000000000000000000000..b0f7a8c0e8ab47540de75dc8f1ff3376c230e36c --- /dev/null +++ b/pool/shard001/JavaScript/0006198_max_unrecognized_commands.js @@ -0,0 +1,19 @@ +// Don't let the remote end spew us with unrecognized commands +// Defaults to 10 max unrecognized commands + +exports.hook_connect = function(callback, connection) { + connection.notes.unrecognized_command_max = this.config.get('max_unrecognized_commands') || 10; + connection.notes.unrecognized_command_count = 0; + callback(CONT); +}; + +exports.hook_unrecognized_command = function(callback, connection, cmd) { + this.loginfo("Unrecognized command: " + cmd); + + connection.notes.unrecognized_command_count++; + if (connection.notes.unrecognized_command_count >= connection.notes.unrecognized_command_max) { + this.loginfo("Closing connection. Too many bad commands."); + return callback(DENYDISCONNECT, "Too many bad commands"); + } + callback(CONT); +}; diff --git a/pool/shard001/JavaScript/0006199_OutputSlide.js b/pool/shard001/JavaScript/0006199_OutputSlide.js new file mode 100644 index 0000000000000000000000000000000000000000..ee7fa0a8b464f4b2524f2fbabaf8f1f548ec8fcc --- /dev/null +++ b/pool/shard001/JavaScript/0006199_OutputSlide.js @@ -0,0 +1,22 @@ +import React, {Component} from 'react'; + + +class OutputSlide extends Component { + render() { + const slide = this.props.slides[this.props.index]; + if(this.props.index === 0) { + slide.img[0].src = slide.img[0]['data-source']; + } else { + delete slide.img[0].src; + } + return ( + + +
    {slide.section[0].text}
    +

    {slide.heading[0].text}

    +
    + ) + } +} + +export default OutputSlide; diff --git a/pool/shard001/JavaScript/0006201_test.js b/pool/shard001/JavaScript/0006201_test.js new file mode 100644 index 0000000000000000000000000000000000000000..b95bb13e759e20d1c3029e6e0209c0116103c079 --- /dev/null +++ b/pool/shard001/JavaScript/0006201_test.js @@ -0,0 +1,97 @@ +/** + * http://usejsdoc.org/ + */ + +var Emulator = require("../lib/emulator").Emulator; + +//emulation data +var data = { + coils: { + minaddr: 0, + maxaddr: 10, + vals: [] + }, + discrInps: { + minaddr: 0, + maxaddr: 10, + vals: [] + }, + holdRegs: { + minaddr: 0, + maxaddr: 10, + vals: [] + }, + inpRegs: { + minaddr: 0, + maxaddr: 10, + vals: [] + } +}; + +//data init +for (var i = data.coils.minaddr; i <= data.coils.maxaddr; ++i) { + data.coils.vals[i] = i & 0x1 ? true : false; +} +for (var i = data.discrInps.minaddr; i <= data.discrInps.maxaddr; ++i) { + data.discrInps.vals[i] = i & 0x1 ? true : false; +} +for (var i = data.holdRegs.minaddr; i <= data.holdRegs.maxaddr; ++i) { + data.holdRegs.vals[i] = i; +} +for (var i = data.inpRegs.minaddr; i <= data.inpRegs.maxaddr; ++i) { + data.inpRegs.vals[i] = i; +} + +//start emulation +var emulator = new Emulator( + "/dev/ttyUSB0", //communication device + 1, //slave address + {}, //communication options (default) + { //user functions + readCoils: function(addr, cnt) { //user function for read coils + if (addr >= data.coils.minaddr && addr + cnt <= data.coils.maxaddr) { + return data.coils.vals.slice(addr, addr + cnt); + } + }, + readDiscrInps: function(addr, cnt) { //user function for read discrete inputs + if (addr >= data.discrInps.minaddr && addr + cnt <= data.discrInps.maxaddr) { + return data.discrInps.vals.slice(addr, addr + cnt); + } + }, + readHoldRegs: function(addr, cnt) { //user function for read holding registers + if (addr >= data.holdRegs.minaddr && addr + cnt <= data.holdRegs.maxaddr) { + return data.holdRegs.vals.slice(addr, addr + cnt); + } + }, + readInpRegs: function(addr, cnt) { //user function for read input registers + if (addr >= data.inpRegs.minaddr && addr + cnt <= data.inpRegs.maxaddr) { + return data.inpRegs.vals.slice(addr, addr + cnt); + } + }, + writeCoils: function(addr, vals) { //user function for write coils + var cnt = vals.length; + if (addr >= data.coils.minaddr && addr + cnt <= data.coils.maxaddr) { + for (var i = 0; i < cnt; ++i) { + data.coils.vals[addr + i] = vals[i]; + } + return true; + } + }, + writeRegs: function(addr, vals) { //user function for write holding registers + var cnt = vals.length; + if (addr >= data.holdRegs.minaddr && addr + cnt <= data.holdRegs.maxaddr) { + for (var i = 0; i < cnt; ++i) { + data.holdRegs.vals[addr + i] = vals[i]; + } + return true; + } + } + }, + function(err) { //done callback function + if (err) { + console.error("Emulator constructor error: " + err); + } + } +); + + diff --git a/pool/shard001/JavaScript/0006202_invite.list.view.js b/pool/shard001/JavaScript/0006202_invite.list.view.js new file mode 100644 index 0000000000000000000000000000000000000000..2b1b77108314d292eb9d32dec116571d0c14ffc3 --- /dev/null +++ b/pool/shard001/JavaScript/0006202_invite.list.view.js @@ -0,0 +1,128 @@ +"use strict"; + +/*global require module _M Promise */ +/*jshint es5: true */ + +var InviteView = require('./invite.view'); +var Backbone = require('backbone'); +var $ = require('jquery'); + +var InviteListView = Backbone.View.extend({ + + events: { + "click button.accept-invite": "onAcceptInviteClick", + "click button.reject-invite": "onRejectInviteClick" + }, + + _getInviteId: function ($el) { + return $el.closest('[data-invite-id]').attr("data-invite-id") || null; + }, + + _getInvite: function ($el) { + var inviteid = this._getInviteId($el); + if (inviteid === null) { + return null; + } + var invite = this.collection.get(inviteid); + return invite; + }, + + _acceptInvite: function (invite) { + return _M.accept_invite(invite.get('msg')).then(function (convid) { + console.log("convid accepted:", convid); + invite.set("isAccepted", true); + return new Promise(function (resolve, reject) { + invite.save({ + success: function (model) { + console.log("invite", model.id, "accepted"); + resolve(convid); + }, + error: function (model, response) { + console.log("invite", model.id, "could not be accepted:", response.responseText); + reject(new Error("bad response:" + response.responseText)); + } + }); + }); + }); + }, + + onAcceptInviteClick: function (evt) { + if (evt) { evt.preventDefault(); } + var invite = this._getInvite($(evt.target)); + var that = this; + + if (invite) { + console.log("clicked accept on", invite.id, invite); + that._acceptInvite(invite).catch(function () {}).then(function () { + that.render(); + }); + } else { + console.error("cannot retrieve invite via attributes", evt.target); + } + }, + + _rejectInvite: function (invite) { + return new Promise(function (resolve, reject) { + invite.destroy({ + success: function (model) { + console.log("invite", model.id, "rejected"); + resolve(true); + }, + error: function (model, response) { + console.log("invite", model.id, "could not be rejected:", response.responseText); + reject(new Error("bad response:" + response.responseText)); + } + }); + }); + }, + + onRejectInviteClick: function (evt) { + if (evt) { evt.preventDefault(); } + var invite = this._getInvite($(evt.target)); + var that = this; + + if (invite) { + console.log("clicked reject on", invite.id, invite); + this._rejectInvite(invite).catch(function () {}).then(function () { + that.render(); + }); + } else { + console.error("cannot retrieve invite via attributes", evt.target); + } + }, + + initialize : function () { + this._views = []; + + this.listenTo(this.collection, "change", this.onChange); + this.listenTo(this.collection, "reset", this.onReset); + }, + + onChange: function () { + console.log("invite list changed"); + this.render(); + }, + + onReset: function () { + console.log("invite list reset"); + this.render(); + }, + + render : function () { + var that = this; + + $(this.el).empty(); + + this.collection.each(function (item) { + var v = new InviteView({ + model : item, + tagName : 'li' + }); + + $(that.el).append(v.render().el); + }); + return this; + } +}); + +module.exports = InviteListView; \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006205_TaxiSrv.js b/pool/shard001/JavaScript/0006205_TaxiSrv.js new file mode 100644 index 0000000000000000000000000000000000000000..dddc1e9771f561617e464e6ea49a807c62bc8bb8 --- /dev/null +++ b/pool/shard001/JavaScript/0006205_TaxiSrv.js @@ -0,0 +1,70 @@ +angular.module('viaggia.services.taxi', []) + +/** + * A SERVICE TO WORK WITH TAXI DATA FROM SERVER + */ +.factory('taxiService', function ($http, $q, $filter, Config, GeoLocate) { + var cacheCompanies = {}; + var cacheTaxiPoints = {}; + return { + getCompanies: function (appId, agencyId) { + var deferred = $q.defer(); + if (!cacheCompanies.length || cacheCompanies.length === 0) { + $http.get(Config.getServerURL() + '/getTaxiAgencyContacts/'+agencyId, + Config.getHTTPConfig()) + .success(function (data) { + if (data) { + var all = []; + cacheCompanies = data; + deferred.resolve(data); + + } else { + deferred.resolve(data); + } + }) + .error(function (err) { + deferred.reject(err); + }); + } else { + deferred.resolve(cacheCompanies); + } + + return deferred.promise; + }, + getTaxiPoints: function (appId, agencyId) { + var deferred = $q.defer(); + if (!cacheTaxiPoints.length || cacheTaxiPoints.length === 0) { + $http.get(Config.getServerURL() + '/getTaxiStation/'+agencyId, + Config.getHTTPConfig()) + .success(function (data) { + if (data) { + var all = []; + cacheTaxiPoints = data; + GeoLocate.locate().then(function (pos) { + data.forEach(function (p) { + all.push(GeoLocate.distanceTo(p.location)); + }); + $q.all(all).then(function (positions) { + data.forEach(function (d, idx) { + d.distance = positions[idx]; + }); + deferred.resolve(data); + }); + }, function (err) { + deferred.resolve(data); + }); + } else { + deferred.resolve(data); + } + }) + .error(function (err) { + deferred.reject(err); + }); + } else { + deferred.resolve(cacheTaxiPoints); + } + return deferred.promise; + } + + } +}) diff --git a/pool/shard001/JavaScript/0006208_theme.js b/pool/shard001/JavaScript/0006208_theme.js new file mode 100644 index 0000000000000000000000000000000000000000..b8861fbb47f308d7cbe6211e6e795a0309819edb --- /dev/null +++ b/pool/shard001/JavaScript/0006208_theme.js @@ -0,0 +1,73 @@ +/* === Manage if we're using the light or dark theme === */ +// Read cookie +function readCookie (name) { + var nameEQ = name + '=' + var ca = document.cookie.split(';') + + for (var i = 0; i < ca.length; i++) { + var c = ca[i] + + while (c.charAt(0) === ' ') { + c = c.substring(1, c.length) + } + + if (c.indexOf(nameEQ) === 0) { + return c.substring(nameEQ.length, c.length) + } + } + + return null +} + +// Disable/enable styles from selection +function applyStyle (toggleS) { + var tags = document.getElementsByTagName('link') + + for (var i = 0; i < tags.length; i++) { + if ((tags[i].rel.indexOf('stylesheet') !== -1) && tags[i].title) { + if (tags[i].title === 'dark') { + tags[i].disabled = toggleS + } + + if (tags[i].title === 'light') { + tags[i].disabled = !toggleS + } + } + } +} + +// Toggle function +function toggleDark () { // eslint-disable-line + var toggleS + var status = readCookie('dark') + + if (status !== 'enabled') { + status = 'enabled' + toggleS = false + } else { + status = 'disabled' + toggleS = true + } + + var date = new Date() + date.setTime(date.getTime() + (365 * 24 * 60 * 60 * 1000)) + document.cookie = 'dark=' + status + '; expires=' + date.toGMTString() + '; path=/' + + applyStyle(toggleS) +} + +// Check cookie and apply +function checkStyle () { + var toggleS + var status = readCookie('dark') + + if (status !== 'enabled') { + toggleS = true + } else { + toggleS = false + } + + applyStyle(toggleS) +} + +checkStyle() diff --git a/pool/shard001/JavaScript/0006210_formulas.js b/pool/shard001/JavaScript/0006210_formulas.js new file mode 100644 index 0000000000000000000000000000000000000000..925eeda54455c4e6ce934d08a61a6e11cf6346b5 --- /dev/null +++ b/pool/shard001/JavaScript/0006210_formulas.js @@ -0,0 +1,118 @@ +'use strict'; + +/** + * Module dependencies. + */ +var mongoose = require('mongoose'), + Formula = mongoose.model('Formula'), + _ = require('lodash'); + +module.exports = function(Formulas) { + + return { + /** + * Find formula by id + */ + formula: function(req, res, next, id) { + Formula.load(id, function(err, formula) { + if (err) return next(err); + if (!formula) return next(new Error('Failed to load formula ' + id)); + req.formula = formula; + next(); + }); + }, + /** + * Create an formula + */ + create: function(req, res) { + var formula = new Formula(req.body); + formula.user = req.user; + + formula.save(function(err) { + if (err) { + return res.status(500).json({ + error: 'Cannot save the formula' + }); + } + + Formulas.events.publish('create', { + description: req.user.name + ' created ' + req.body.title + ' formula.' + }); + + res.json(formula); + }); + }, + /** + * Update an formula + */ + update: function(req, res) { + var formula = req.formula; + + formula = _.extend(formula, req.body); + + + formula.save(function(err) { + if (err) { + return res.status(500).json({ + error: 'Cannot update the formula' + }); + } + + Formulas.events.publish('update', { + description: req.user.name + ' updated ' + req.body.title + ' formula.' + }); + + res.json(formula); + }); + }, + /** + * Delete an formula + */ + destroy: function(req, res) { + var formula = req.formula; + + + formula.remove(function(err) { + if (err) { + return res.status(500).json({ + error: 'Cannot delete the formula' + }); + } + + Formulas.events.publish('remove', { + description: req.user.name + ' deleted ' + formula.title + ' formula.' + }); + + res.json(formula); + }); + }, + /** + * Show an formula + */ + show: function(req, res) { + + Formulas.events.publish('view', { + description: req.user.name + ' read ' + req.formula.title + ' formula.' + }); + + res.json(req.formula); + }, + /** + * List of Formulas + */ + all: function(req, res) { + var query = req.acl.query('Formula'); + + query.find({}).sort('-created').populate('user', 'name username').exec(function(err, formulas) { + if (err) { + return res.status(500).json({ + error: 'Cannot list the formulas' + }); + } + + res.json(formulas) + }); + + } + }; +} \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006211_google-analytics.js b/pool/shard001/JavaScript/0006211_google-analytics.js new file mode 100644 index 0000000000000000000000000000000000000000..0b6c8cbcf99114f46e46f78e2d69a43951ea03d1 --- /dev/null +++ b/pool/shard001/JavaScript/0006211_google-analytics.js @@ -0,0 +1,14 @@ +(function(i, s, o, g, r, a, m) { + i['GoogleAnalyticsObject'] = r; + i[r] = i[r] || function() { + (i[r].q = i[r].q || []).push(arguments) + }, i[r].l = 1 * new Date(); + a = s.createElement(o), + m = s.getElementsByTagName(o)[0]; + a.async = 1; + a.src = g; + m.parentNode.insertBefore(a, m) +})(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga'); + +ga('create', 'UA-73442912-1', 'auto'); +ga('send', 'pageview'); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006213_Main.js b/pool/shard001/JavaScript/0006213_Main.js new file mode 100644 index 0000000000000000000000000000000000000000..11772833bb3cfd453fa466be021374bd27250ff0 --- /dev/null +++ b/pool/shard001/JavaScript/0006213_Main.js @@ -0,0 +1,113 @@ +require('normalize.css'); +require('styles//App.scss'); + +import React from 'react'; +import { Modal, Button } from 'react-bootstrap' +import Hammer from 'react-hammerjs'; +import BoardComponent from './BoardComponent'; +import GameEngine from '../engines/GameEngine'; +import Header from './HeaderComponent' + + +class AppComponent extends React.Component { + constructor(props) { + super(props); + this.state = { + board: [ + [0, 0, 4, 0], + [0, 0, 0, 0], + [0, 0, 2, 0], + [0, 0, 0, 0], + ], + score: 0, + maxScore: window.localStorage.getItem('maxScore') || 0, + allowedMoves: { left: true, up: true, down: true, right: true } + }; + this.game = new GameEngine(this.state.board); + } + + updateState() { + var gameStatus = this.game.run(); + this.setState({ board: gameStatus.board, score: gameStatus.score, allowedMoves: gameStatus.allowedMoves }); + if(gameStatus.score >= this.state.maxScore) { + this.setState({maxScore: gameStatus.score}) + window.localStorage.setItem('maxScore', gameStatus.score); + } + } + + handleEvent(e) { + const ARROW_UP = 38, ARROW_DOWN = 40, ARROW_LEFT = 37, ARROW_RIGHT = 39, ESC = 27, + SWIPE_UP = 8, SWIPE_DOWN = 16, SWIPE_LEFT = 2, SWIPE_RIGHT = 4; + + if(e.which === ESC) { + this.game.reset(); + this.updateState(); + } else if(!this.game.isGameOver()) { + switch (true) { + case (e.which === ARROW_LEFT || e.direction === SWIPE_LEFT): + if(this.state.allowedMoves.left) { + this.game.moveLeft(); + this.updateState(); + } + break; + case (e.which === ARROW_UP || e.direction === SWIPE_UP): + if(this.state.allowedMoves.up) { + this.game.moveUp(); + this.updateState(); + } + break; + case (e.which === ARROW_RIGHT || e.direction === SWIPE_RIGHT): + if(this.state.allowedMoves.right) { + this.game.moveRight(); + this.updateState(); + } + break; + case (e.which === ARROW_DOWN || e.direction === SWIPE_DOWN): + if(this.state.allowedMoves.down) { + this.game.moveDown(); + this.updateState(); + } + break; + } + } + setTimeout(() => {}, 500); + } + + resetGame() { + this.game.reset(); + this.updateState(); + } + + componentDidMount() { + document.body.addEventListener('keydown', this.handleEvent.bind(this)); + } + + render() { + var GameOver = ( + {}}> + + Ooh, you are done + + + Your Score is {this.state.score} + + + + + + ) + return ( +
    + {GameOver} +
    + + + +
    + ); + } +} + +AppComponent.displayName = 'App'; + +export default AppComponent; diff --git a/pool/shard001/JavaScript/0006218_sportsStore.js b/pool/shard001/JavaScript/0006218_sportsStore.js new file mode 100644 index 0000000000000000000000000000000000000000..7473fab3c7e466babd60886428755b1375a8c208 --- /dev/null +++ b/pool/shard001/JavaScript/0006218_sportsStore.js @@ -0,0 +1,18 @@ +/** + * Created by KimJin-young on 14. 11. 19.. + */ +angular.module("sportsStore") + .constant("dataUrl", "http://localhost:2403/products") + .controller("sportsStoreCtrl", function($scope, $http, dataUrl){ + + $scope.data = {}; + + $http.get(dataUrl) + .success(function (data) { + $scope.data.products = data; + }) + .error(function (error){ + $scope.data.error = error; + }) + +}); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006219_SampleView.js b/pool/shard001/JavaScript/0006219_SampleView.js new file mode 100644 index 0000000000000000000000000000000000000000..aeca3033c763745ec0b4be02a318263b8f9767cf --- /dev/null +++ b/pool/shard001/JavaScript/0006219_SampleView.js @@ -0,0 +1,19 @@ +var MASlidingView = require('lib/MASlidingView'); + +var SampleView = function(args){ + var view = new MASlidingView({ + backgroundColor:'white' + }); + + view.add(Ti.UI.createLabel({ + text:'Sample View', + color:'#000', + height:24, + width:100, + textAlign:'center', + })); + + return view; +}; + +module.exports = SampleView; \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006220_add.js b/pool/shard001/JavaScript/0006220_add.js new file mode 100644 index 0000000000000000000000000000000000000000..38b55c40ec8ed479156c72be5bc763b4d854fcf2 --- /dev/null +++ b/pool/shard001/JavaScript/0006220_add.js @@ -0,0 +1,53 @@ +'use strict'; + +angular.module('app') + .controller('AddCtrl', function ($scope, $http, apiService, $location, + $routeParams) { + + apiService.getUser().then(function () { + // Great, they're logged in. + }, function (data){ + $location.path('/login'); + }); + + // When 'add,' content is empty to begin with. Otherwise, load the + // content from the backend. + $scope.content = ''; + if ('entryId' in $routeParams) { + $scope.entryId = $routeParams.entryId; + apiService.getEntry($scope.entryId).then(function(data){ + $scope.entry = data; + $scope.edit = true; + }); + } + + var source_textarea = document.getElementById('source'); + tabOverride.set(source_textarea); + + var converter = new Showdown.converter(); + + $scope.markdown = function (input) { + return converter.makeHtml(input); + }; + + $scope.saveEntry = function () { + if ($scope.edit) { + $scope.updateEntry(); + } else { + $scope.postEntry(); + } + }; + + $scope.postEntry = function () { + apiService.postEntry($scope.entry.content).then(function(){ + $location.path('/home'); + }); + }; + + $scope.updateEntry = function () { + apiService.updateEntry($scope.entryId, $scope.entry.content).then( + function(){ + $location.path('/home'); + }) + }; + }); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006222_RuntimeManager.js b/pool/shard001/JavaScript/0006222_RuntimeManager.js new file mode 100644 index 0000000000000000000000000000000000000000..477776cd53566e9a9e67f41092547126571de410 --- /dev/null +++ b/pool/shard001/JavaScript/0006222_RuntimeManager.js @@ -0,0 +1,119 @@ +/* + * Copyright (C) 2013 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. + */ + +WebInspector.RuntimeManager = class RuntimeManager extends WebInspector.Object +{ + constructor() + { + super(); + + // Enable the RuntimeAgent to receive notification of execution contexts. + RuntimeAgent.enable(); + } + + // Public + + evaluateInInspectedWindow(expression, objectGroup, includeCommandLineAPI, doNotPauseOnExceptionsAndMuteConsole, returnByValue, generatePreview, saveResult, callback) + { + if (!expression) { + // There is no expression, so the completion should happen against global properties. + expression = "this"; + } else if (/^\s*\{/.test(expression) && /\}\s*$/.test(expression)) { + // Transform {a:1} to ({a:1}) so it is treated like an object literal instead of a block with a label. + expression = "(" + expression + ")"; + } + + expression = appendWebInspectorSourceURL(expression); + + function evalCallback(error, result, wasThrown, savedResultIndex) + { + this.dispatchEventToListeners(WebInspector.RuntimeManager.Event.DidEvaluate, {objectGroup}); + + if (error) { + console.error(error); + callback(null, false); + return; + } + + if (returnByValue) + callback(null, wasThrown, wasThrown ? null : result, savedResultIndex); + else + callback(WebInspector.RemoteObject.fromPayload(result), wasThrown, savedResultIndex); + } + + if (WebInspector.debuggerManager.activeCallFrame) { + // COMPATIBILITY (iOS 8): "saveResult" did not exist. + DebuggerAgent.evaluateOnCallFrame.invoke({callFrameId: WebInspector.debuggerManager.activeCallFrame.id, expression, objectGroup, includeCommandLineAPI, doNotPauseOnExceptionsAndMuteConsole, returnByValue, generatePreview, saveResult}, evalCallback.bind(this)); + return; + } + + // COMPATIBILITY (iOS 8): "saveResult" did not exist. + var contextId = WebInspector.quickConsole.executionContextIdentifier; + RuntimeAgent.evaluate.invoke({expression, objectGroup, includeCommandLineAPI, doNotPauseOnExceptionsAndMuteConsole, contextId, returnByValue, generatePreview, saveResult}, evalCallback.bind(this)); + } + + saveResult(remoteObject, callback) + { + console.assert(remoteObject instanceof WebInspector.RemoteObject); + + // COMPATIBILITY (iOS 8): Runtime.saveResult did not exist. + if (!RuntimeAgent.saveResult) { + callback(undefined); + return; + } + + function mycallback(error, savedResultIndex) + { + callback(savedResultIndex); + } + + if (remoteObject.objectId) + RuntimeAgent.saveResult(remoteObject.asCallArgument(), mycallback); + else + RuntimeAgent.saveResult(remoteObject.asCallArgument(), WebInspector.quickConsole.executionContextIdentifier, mycallback); + } + + getPropertiesForRemoteObject(objectId, callback) + { + RuntimeAgent.getProperties(objectId, function(error, result) { + if (error) { + callback(error); + return; + } + + var properties = new Map; + for (var property of result) + properties.set(property.name, property); + + callback(null, properties); + }); + } +}; + +WebInspector.RuntimeManager.Event = { + DidEvaluate: "runtime-manager-did-evaluate" +}; + +WebInspector.RuntimeManager.ConsoleObjectGroup = "console"; diff --git a/pool/shard001/JavaScript/0006223_audits.controller.js b/pool/shard001/JavaScript/0006223_audits.controller.js new file mode 100644 index 0000000000000000000000000000000000000000..135dc60ab402a45111dfcedb8caa6314e40ec7d3 --- /dev/null +++ b/pool/shard001/JavaScript/0006223_audits.controller.js @@ -0,0 +1,36 @@ +'use strict'; + +angular.module('scaffoldApp') + .controller('AuditsController', function ($scope, $filter, AuditsService) { + $scope.onChangeDate = function () { + var dateFormat = 'yyyy-MM-dd'; + var fromDate = $filter('date')($scope.fromDate, dateFormat); + var toDate = $filter('date')($scope.toDate, dateFormat); + + AuditsService.findByDates(fromDate, toDate).then(function (data) { + $scope.audits = data; + }); + }; + + // Date picker configuration + $scope.today = function () { + // Today + 1 day - needed if the current day must be included + var today = new Date(); + $scope.toDate = new Date(today.getFullYear(), today.getMonth(), today.getDate() + 1); + }; + + $scope.previousMonth = function () { + var fromDate = new Date(); + if (fromDate.getMonth() === 0) { + fromDate = new Date(fromDate.getFullYear() - 1, 0, fromDate.getDate()); + } else { + fromDate = new Date(fromDate.getFullYear(), fromDate.getMonth() - 1, fromDate.getDate()); + } + + $scope.fromDate = fromDate; + }; + + $scope.today(); + $scope.previousMonth(); + $scope.onChangeDate(); + }); diff --git a/pool/shard001/JavaScript/0006224_loginModal-controller.js b/pool/shard001/JavaScript/0006224_loginModal-controller.js new file mode 100644 index 0000000000000000000000000000000000000000..01a7569306dc1354dc6b31cfccea7a23fa95be9f --- /dev/null +++ b/pool/shard001/JavaScript/0006224_loginModal-controller.js @@ -0,0 +1,85 @@ +(function () { + 'use strict'; + + angular.module('NewsFeed') + .controller('loginModalCtrl', ['$uibModalInstance', '$scope', 'addIdService', 'usersService', '$uibModal', function ($uibModalInstance, $scope, addIdService, usersService) { + + var vm = this; + + vm.signUp = { + email: '', + password: '' + }; + + vm.login = { + email: '', + password: '' + }; + + vm.users = usersService.getUsersArray(); + + vm.openLogIn = true; + + /** + * @ngdoc function + * @name openLogInModal + * @description open signup modal + */ + vm.openSignUpModal = function () { + vm.openLogIn = false; + vm.openSignUp = true; + }; + + /** + * @ngdoc function + * @name openLogInModal + * @description open login modal + */ + vm.openLogInModal = function () { + vm.openLogIn = true; + vm.openSignUp = false; + }; + + //TO DO + vm.forgotPassword = function () { + }; + + /** + * @ngdoc function + * @name logIn + * @description check if user is in usersList + */ + vm.logIn = function () { + for (var i = 0; i < vm.users.length; i++) { + if (vm.users[i].email === vm.login.email && vm.users[i].password === vm.login.password) { + $scope.role = 'user'; + usersService.setRole($scope.role); + } + } + $uibModalInstance.dismiss('cancel'); + }; + + /** + * @ngdoc function + * @name signUp + * @description create new pending user + */ + vm.signUp = function () { + vm.id = addIdService.createId(vm.users); + vm.date = new Date(); + + var user = { + date: vm.date.toLocaleDateString(), + deleted: 'false', + email: vm.signUp.email, + id: vm.id, + name: vm.signUp.email.split('@')[0], + password: vm.signUp.password, + role: 'user', + status: 'pending' + }; + usersService.addUser(user); + $uibModalInstance.dismiss('cancel'); + }; + }]); +})(); diff --git a/pool/shard001/JavaScript/0006226_test-doubled.js b/pool/shard001/JavaScript/0006226_test-doubled.js new file mode 100644 index 0000000000000000000000000000000000000000..3256c793b114769cf084b97463001a34437f7494 --- /dev/null +++ b/pool/shard001/JavaScript/0006226_test-doubled.js @@ -0,0 +1,27 @@ +var doubled = require('../lib/doubled'); + +exports['calculate'] = function (test) { + test.equal(doubled.calculate(2), 4); + test.equal(doubled.calculate(5), 10); + test.throws(function () { doubled.calculate(); }); + test.throws(function () { doubled.calculate(null); }); + test.throws(function () { doubled.calculate(true); }); + test.throws(function () { doubled.calculate([]); }); + test.throws(function () { doubled.calculate({}); }); + test.throws(function () { doubled.calculate('asdf'); }); + test.throws(function () { doubled.calculate('123'); }); + test.done(); +}; + +exports['read a number'] = function (test) { + var ev = new events.EventEmitter(); + process.openStdin = function () { + return ev; + }; + process.exit = test.done; + console.log = function (str) { + test.equal(str, 'doubled: 24'); + }; + doubled.read(); + ev.emit('data', '12'); +}; \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006228_php_dns.js b/pool/shard001/JavaScript/0006228_php_dns.js new file mode 100644 index 0000000000000000000000000000000000000000..acd42fe88016127837c6713534d53479a0cfb686 --- /dev/null +++ b/pool/shard001/JavaScript/0006228_php_dns.js @@ -0,0 +1,61 @@ +var ffi = require('ffi'), + ref = require('ref'), + RefArray = require('ref-array'), + Struct = require('ref-struct'), + Union = require('ref-union'), + _library = require('./../../'); + +loadDependentSymbols(); + +_library._preload['zif_gethostbyaddr'] = ['zval', 'pointer', 'zval', function () { + _library.zif_gethostbyaddr = ['void', ['int', ref.refType(_library.zval), ref.refType(ref.refType(_library.zval)), ref.refType(_library.zval), 'int']]; + _library._functions['zif_gethostbyaddr'] = _library.zif_gethostbyaddr; +}]; + +_library._preload['zif_gethostbyname'] = ['zval', 'pointer', 'zval', function () { + _library.zif_gethostbyname = ['void', ['int', ref.refType(_library.zval), ref.refType(ref.refType(_library.zval)), ref.refType(_library.zval), 'int']]; + _library._functions['zif_gethostbyname'] = _library.zif_gethostbyname; +}]; + +_library._preload['zif_gethostbynamel'] = ['zval', 'pointer', 'zval', function () { + _library.zif_gethostbynamel = ['void', ['int', ref.refType(_library.zval), ref.refType(ref.refType(_library.zval)), ref.refType(_library.zval), 'int']]; + _library._functions['zif_gethostbynamel'] = _library.zif_gethostbynamel; +}]; + +_library._preload['zif_gethostname'] = ['zval', 'pointer', 'zval', function () { + _library.zif_gethostname = ['void', ['int', ref.refType(_library.zval), ref.refType(ref.refType(_library.zval)), ref.refType(_library.zval), 'int']]; + _library._functions['zif_gethostname'] = _library.zif_gethostname; +}]; + +_library._preload['zif_dns_check_record'] = ['zval', 'pointer', 'zval', function () { + _library.zif_dns_check_record = ['void', ['int', ref.refType(_library.zval), ref.refType(ref.refType(_library.zval)), ref.refType(_library.zval), 'int']]; + _library._functions['zif_dns_check_record'] = _library.zif_dns_check_record; +}]; + +_library._preload['zif_dns_get_mx'] = ['zval', 'pointer', 'zval', function () { + _library.zif_dns_get_mx = ['void', ['int', ref.refType(_library.zval), ref.refType(ref.refType(_library.zval)), ref.refType(_library.zval), 'int']]; + _library._functions['zif_dns_get_mx'] = _library.zif_dns_get_mx; +}]; + +_library._preload['zif_dns_get_record'] = ['zval', 'pointer', 'zval', function () { + _library.zif_dns_get_record = ['void', ['int', ref.refType(_library.zval), ref.refType(ref.refType(_library.zval)), ref.refType(_library.zval), 'int']]; + _library._functions['zif_dns_get_record'] = _library.zif_dns_get_record; +}]; + +_library._preload['zm_startup_dns'] = [function () { + _library.zm_startup_dns = ['int', ['int', 'int']]; + _library._functions['zm_startup_dns'] = _library.zm_startup_dns; +}]; + +function loadDependentSymbols() { + require('./../../Zend/zend.js'); + require('./../../Zend/zend_API.js'); + require('./../../Zend/zend_ast.js'); + require('./../../Zend/zend_compile.js'); + require('./../../Zend/zend_hash.js'); + require('./../../Zend/zend_ini.js'); + require('./../../Zend/zend_iterators.js'); + require('./../../Zend/zend_modules.js'); + require('./../../Zend/zend_object_handlers.js'); + require('./../../Zend/zend_types.js'); +} diff --git a/pool/shard001/JavaScript/0006229_json.js b/pool/shard001/JavaScript/0006229_json.js new file mode 100644 index 0000000000000000000000000000000000000000..3a457b226e55f6256500a48fa8b418a71b9d7f75 --- /dev/null +++ b/pool/shard001/JavaScript/0006229_json.js @@ -0,0 +1,61 @@ +/** + * @fileOverview Instance of Exhibit.Exporter for Exhibit JSON. + * @author David Huynh + * @author Ryan Lee + */ + +/** + * @namespace + */ +Exhibit.Exporter.ExhibitJSON = { + _mimeType: "application/json", + exporter: null +}; + +/** + * @param {String} s + * @returns {String} + */ +Exhibit.Exporter.ExhibitJSON.wrap = function(s) { + return "{\n" + + " \"items\": [\n" + + s + + " ]\n" + + "}\n"; +}; + +/** + * @param {String} s + * @param {Boolean} first + * @param {Boolean} last + * @returns {String} + */ +Exhibit.Exporter.ExhibitJSON.wrapOne = function(s, first, last) { + return s + (last ? "" : ",") +"\n"; +}; + +/** + * @param {String} itemID + * @param {Object} o + * @returns {String} + * @depends JSON + */ +Exhibit.Exporter.ExhibitJSON.exportOne = function(itemID, o) { + return JSON.stringify(o); +}; + +/** + * @private + */ +Exhibit.Exporter.ExhibitJSON._register = function() { + Exhibit.Exporter.ExhibitJSON.exporter = new Exhibit.Exporter( + Exhibit.Exporter.ExhibitJSON._mimeType, + Exhibit._("%export.exhibitJsonExporterLabel"), + Exhibit.Exporter.ExhibitJSON.wrap, + Exhibit.Exporter.ExhibitJSON.wrapOne, + Exhibit.Exporter.ExhibitJSON.exportOne + ); +}; + +$(document).one("registerExporters.exhibit", + Exhibit.Exporter.ExhibitJSON._register); diff --git a/pool/shard001/JavaScript/0006232_pingServer.js b/pool/shard001/JavaScript/0006232_pingServer.js new file mode 100644 index 0000000000000000000000000000000000000000..077ec0eff8bcc4422658c48c9a9a580351df2553 --- /dev/null +++ b/pool/shard001/JavaScript/0006232_pingServer.js @@ -0,0 +1,74 @@ +/* + * pingServer.js + * + * EventDance examples + * + * Copyright (C) 2010-2012, Igalia S.L. + * + * Authors: + * Eduardo Lima Mitev + */ + +imports.searchPath.unshift ("../common"); + +const Evd = imports.gi.Evd; + +const LISTEN_PORT = 8080; + +Evd.tls_init (); + +/* daemon */ +var daemon = new Evd.Daemon.get_default (null, null); +daemon.set_pid_file ("/tmp/ping.pid"); + +/* web transport */ +var transport = new Evd.WebTransportServer (); + +function peerOnReceive (t, peer) { + var data = peer.transport.receive_text (peer); + + transport.send_text (peer, data); +} + +if (transport["signal"]) + transport.signal.receive.connect (peerOnReceive); +else + transport.connect ("receive", peerOnReceive); + +/* web dir */ +var webDir = new Evd.WebDir ({ root: "../common" }); + +/* web selector */ +var selector = new Evd.WebSelector (); + +selector.set_default_service (webDir); +transport.selector = selector; + +//selector.tls_autostart = true; +selector.tls_credentials.add_certificate_from_file ("../../tests/certs/x509-server.pem", + "../../tests/certs/x509-server-key.pem", + null, + null, + null); + +/* start listening */ +selector.listen ("0.0.0.0:" + LISTEN_PORT, null, + function (service, result) { + try { + service.listen_finish (result); + print ("Listening, now point your browser to http://localhost:" + LISTEN_PORT + "/ping.html"); + } + catch (e) { + if (e["message"]) + print (e.message); + else + print (e); + + daemon.quit (-1); + } + }, null); + +/* start the show */ +daemon.run (); + +Evd.tls_deinit (); diff --git a/pool/shard001/JavaScript/0006234_address-service.js b/pool/shard001/JavaScript/0006234_address-service.js new file mode 100644 index 0000000000000000000000000000000000000000..af535705ae8c40681ae0087a965f503ac92fc2b2 --- /dev/null +++ b/pool/shard001/JavaScript/0006234_address-service.js @@ -0,0 +1,64 @@ +'use strict'; + +var _ym = require('util/ym.js'); + +var _address = { + getAddressList : function(resolve, reject) { + _ym.request({ + url : _ym.getServerUrl('/shipping/list.do'), + data : { + pageSize : 50, + }, + success : resolve, + error : reject, + }); + }, + + //保存地址 + save : function(addressInfo, resolve, reject) { + _ym.request({ + url : _ym.getServerUrl('/shipping/add.do'), + data : addressInfo, + success : resolve, + error : reject, + }); + }, + + //获取地址 + getAddress : function(shippingId, resolve, reject) { + _ym.request({ + url : _ym.getServerUrl('/shipping/select.do'), + data : { + shippingId : shippingId, + }, + success : resolve, + error : reject, + }); + }, + + //更新收货地址 + update : function(addressInfo, resolve, reject) { + _ym.request({ + url : _ym.getServerUrl('/shipping/update.do'), + data : addressInfo, + success : resolve, + error : reject, + }); + }, + //删除地址 + deleteAddress : function(shippingId, resolve, reject) { + _ym.request({ + url : _ym.getServerUrl('/shipping/delete.do'), + data : { + shippingId : shippingId, + }, + success : resolve, + error : reject, + }); + }, +}; + +module.exports = _address; + + + diff --git a/pool/shard001/JavaScript/0006235_test.js b/pool/shard001/JavaScript/0006235_test.js new file mode 100644 index 0000000000000000000000000000000000000000..29a7abe9e853c946a12e1f20e65410a177949639 --- /dev/null +++ b/pool/shard001/JavaScript/0006235_test.js @@ -0,0 +1,201 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var isnan = require( '@stdlib/math/base/assert/is-nan' ); +var sqrt = require( '@stdlib/math/base/special/sqrt' ); +var incrmeanstdev = require( './../lib' ); + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.equal( typeof incrmeanstdev, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'the function throws an error if not provided an array-like object for an output argument', function test( t ) { + var values; + var i; + + values = [ + '5', + -5.0, + true, + false, + null, + void 0, + NaN, + {}, + function noop() {} + ]; + + for ( i = 0; i < values.length; i++ ) { + t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); + } + t.end(); + + function badValue( value ) { + return function badValue() { + incrmeanstdev( value ); + }; + } +}); + +tape( 'the function returns an accumulator function', function test( t ) { + t.equal( typeof incrmeanstdev(), 'function', 'returns a function' ); + t.end(); +}); + +tape( 'the function returns an accumulator function (output)', function test( t ) { + t.equal( typeof incrmeanstdev( [ 0.0, 0.0 ] ), 'function', 'returns a function' ); + t.end(); +}); + +tape( 'the accumulator function incrementally computes an arithmetic mean and corrected sample standard deviation', function test( t ) { + var expected; + var actual; + var data; + var acc; + var N; + var i; + + data = [ 2.0, 3.0, 2.0, 4.0, 3.0, 4.0 ]; + N = data.length; + + // Test against Julia: + expected = [ + [ 2.0, 0.0 ], + [ 2.5, sqrt( 0.5 ) ], + [ 7.0/3.0, sqrt( 0.33333333333333337 ) ], + [ 11.0/4.0, sqrt( 0.9166666666666666 ) ], + [ 14.0/5.0, sqrt( 0.7 ) ], + [ 18.0/6.0, sqrt( 0.8 ) ] + ]; + + acc = incrmeanstdev(); + + for ( i = 0; i < N; i++ ) { + actual = acc( data[ i ] ); + t.deepEqual( actual, expected[ i ], 'returns expected value' ); + } + t.end(); +}); + +tape( 'the accumulator function incrementally computes an arithmetic mean and corrected sample standard deviation (output)', function test( t ) { + var expected; + var actual; + var data; + var acc; + var out; + var N; + var i; + + data = [ 2.0, 3.0, 2.0, 4.0, 3.0, 4.0 ]; + N = data.length; + + // Test against Julia: + expected = [ + [ 2.0, 0.0 ], + [ 2.5, sqrt( 0.5 ) ], + [ 7.0/3.0, sqrt( 0.33333333333333337 ) ], + [ 11.0/4.0, sqrt( 0.9166666666666666 ) ], + [ 14.0/5.0, sqrt( 0.7 ) ], + [ 18.0/6.0, sqrt( 0.8 ) ] + ]; + out = [ 0.0, 0.0 ]; + acc = incrmeanstdev( out ); + + for ( i = 0; i < N; i++ ) { + actual = acc( data[ i ] ); + t.equal( actual, out, 'returns output array' ); + t.deepEqual( actual, expected[ i ], 'returns expected value' ); + } + t.end(); +}); + +tape( 'if not provided an input value, the accumulator function returns the current mean and corrected sample standard deviation', function test( t ) { + var data; + var acc; + var i; + + data = [ 2.0, 3.0, 1.0 ]; + acc = incrmeanstdev(); + for ( i = 0; i < data.length; i++ ) { + acc( data[ i ] ); + } + t.deepEqual( acc(), [ 2.0, 1.0 ], 'returns expected value' ); + t.end(); +}); + +tape( 'if data has yet to be provided, the accumulator function returns `null`', function test( t ) { + var acc = incrmeanstdev(); + t.equal( acc(), null, 'returns null' ); + t.equal( acc(), null, 'returns null' ); + t.equal( acc(), null, 'returns null' ); + t.end(); +}); + +tape( 'the sample standard deviation is `0` until at least 2 datums have been provided', function test( t ) { + var acc; + var ms; + + acc = incrmeanstdev(); + + ms = acc(); + t.equal( ms, null, 'returns null' ); + + ms = acc( 3.0 ); + t.equal( ms[ 1 ], 0.0, 'returns expected value' ); + + ms = acc(); + t.equal( ms[ 1 ], 0.0, 'returns expected value' ); + + ms = acc( 5.0 ); + t.notEqual( ms[ 1 ], 0.0, 'does not return 0' ); + + ms = acc(); + t.notEqual( ms[ 1 ], 0.0, 'does not return 0' ); + + t.end(); +}); + +tape( 'if provided `NaN`, the accumulated values are `NaN` for all future invocations', function test( t ) { + var data; + var acc; + var v; + var i; + + data = [ NaN, 2.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0 ]; + acc = incrmeanstdev(); + for ( i = 0; i < data.length; i++ ) { + v = acc( data[ i ] ); + t.equal( isnan( v[ 0 ] ), true, 'returns expected value' ); + t.equal( isnan( v[ 1 ] ), true, 'returns expected value' ); + + v = acc(); + t.equal( isnan( v[ 0 ] ), true, 'returns expected value' ); + t.equal( isnan( v[ 1 ] ), true, 'returns expected value' ); + } + t.end(); +}); diff --git a/pool/shard001/JavaScript/0006236_editoradmin.js b/pool/shard001/JavaScript/0006236_editoradmin.js new file mode 100644 index 0000000000000000000000000000000000000000..6acb5d179c399907bd314d516fc427be7efcbfd9 --- /dev/null +++ b/pool/shard001/JavaScript/0006236_editoradmin.js @@ -0,0 +1,20 @@ +/** + * ANDS Editor Admin. Requires JQuery. + */ + +/* Toggle all checkboxes of a given class. If all checkboxes are + * already selected, then deselect all. Otherwise, select all. */ +function toggleCheckboxes(elementStyle) { + var allElements = jQuery("." + elementStyle); + if (allElements.length == jQuery("." + elementStyle + ":checked").length) { + allElements.prop("checked", false); + } else { + allElements.prop("checked", true); + } +}; + +/* Toggle display of the text of a SPARQL Query/Update. */ +function toggle_sparql(id) { + var element = jQuery("." + id); + element.toggle(); +} diff --git a/pool/shard001/JavaScript/0006237_table-header.js b/pool/shard001/JavaScript/0006237_table-header.js new file mode 100644 index 0000000000000000000000000000000000000000..24c0697797e07a2ea9086ade2a38047eca8d36da --- /dev/null +++ b/pool/shard001/JavaScript/0006237_table-header.js @@ -0,0 +1,17 @@ +describe('tableHeaderDirective', function() { + var element, scope + + beforeEach(module('bp')) + + beforeEach(inject(function($rootScope, $compile) { + scope = $rootScope.$new() + element = $compile('A')(scope) + scope.$apply() + })) + + describe('element', function() { + it('should have the role "heading"', function() { + expect(element.attr('role')).toBe('heading') + }) + }) +}) diff --git a/pool/shard001/JavaScript/0006242_loader.js b/pool/shard001/JavaScript/0006242_loader.js new file mode 100644 index 0000000000000000000000000000000000000000..7c87e6e7c495acd156659adf30562287d8024988 --- /dev/null +++ b/pool/shard001/JavaScript/0006242_loader.js @@ -0,0 +1,150 @@ +/** + * ALGO.Loader + */ +ALGO.Loader = (function() { + 'use strict'; + + /** + * [Loader description] + * @param {[type]} _url [description] + */ + ALGO.Loader = function(_url) { + var that = this; + this.loaderURL = _url; + + this.xhr = new XMLHttpRequest(); + this.xhr.onreadystatechange = function(e) { + that.readyStateChange(e); + }; + }; + + /** + * [get description] + * @return {[type]} [description] + */ + function get() { + this.xhr.open('get', this.loaderURL, true); + this.xhr.send(null); + }; + + /** + * [post description] + * @param {[type]} params [description] + * @return {[type]} [description] + */ + function post(params) { + this.xhr.open('post', this.loaderURL, true); + this.xhr.send(params); + }; + + /** + * [readyStateChange description] + * @param {[type]} e [description] + * @return {[type]} [description] + */ + function readyStateChange(e) { + + if (this.xhr.status !== 0) { + + var state_str = this.getReadyStateString(this.xhr.readyState); + + // ALGO.log( e.target ); + // ALGO.log( 'status: ' + this.xhr.status ); + // ALGO.log( 'response: ' + this.xhr.response ); + // ALGO.log( 'responseText: ' + this.xhr.responseText ); + // ALGO.log( 'readyState: ' + state_str ); + // ALGO.log( '' ); + + if (this.xhr.readyState == this.xhr.UNSENT) { + + } else if (this.xhr.readyState == this.xhr.OPENED) { + + } else if (this.xhr.readyState == this.xhr.HEADERS_RECEIVED) { + + } else if (this.xhr.readyState == this.xhr.LOADING) { + + } else if (this.xhr.readyState == this.xhr.DONE) { + var params = {}; + params.status = this.xhr.status; + params.responseText = this.xhr.responseText; + this.completeRequest(params); + } + } + + }; + + /** + * [completeRequest description] + * @param {[type]} params [description] + * @return {[type]} [description] + */ + function completeRequest(params) { + this.complete(params); + this.remove(); + }; + + /** + * [complete description] + * @param {[type]} params [description] + * @return {[type]} [description] + */ + function complete(params) { + }; + + /** + * [remove description] + * @return {[type]} [description] + */ + function remove(){ + this.loaderURL = ''; + this.xhr = null; + }; + + /** + * [getReadyStateString description] + * @param {[type]} ready_state [description] + * @return {[type]} [description] + */ + function getReadyStateString(ready_state) { + var str; + if (ready_state == this.xhr.UNSENT) { + str = 'UNSENT'; + } else if (ready_state == this.xhr.OPENED) { + str = 'OPENED'; + } else if (ready_state == this.xhr.HEADERS_RECEIVED) { + str = 'HEADERS_RECEIVED'; + } else if (ready_state == this.xhr.LOADING) { + str = 'LOADING'; + } else if (ready_state == this.xhr.DONE) { + str = 'DONE'; + } + return str; + } + + ALGO.Loader.prototype = { + constructor: ALGO.Loader, + + /** + * Property + */ + loaderURL: '', + xhr: null, + + /** + * Method + */ + get: get, + post: post, + complete: complete, + remove: remove, + + /** + * Private Method + */ + readyStateChange: readyStateChange, + getReadyStateString: getReadyStateString, + completeRequest: completeRequest + }; + + return ALGO.Loader; +}()); diff --git a/pool/shard001/JavaScript/0006243_MainCtrl.js b/pool/shard001/JavaScript/0006243_MainCtrl.js new file mode 100644 index 0000000000000000000000000000000000000000..fe60386399522b50e31d7ab73c7026de0edf13b4 --- /dev/null +++ b/pool/shard001/JavaScript/0006243_MainCtrl.js @@ -0,0 +1,62 @@ +angular.module('ByomCtrl', []).controller('ByomController', function($scope, $http) { + $scope.formData = {}; + $scope.formLogin = {}; + $scope.loged; + + $http.get('/api/categories/mainCategories') + .success(function(mainCategories) { + $scope.mainCategories = mainCategories; + }) + .error(function(data) { + console.log('Error: ' + data); + }); + + + $http.get('/isloggedin') + .success(function(data) { + $scope.loged = data; + if($scope.loged['auth'] == true) { + $scope.username = $scope.loged['user']['local']['username']; + } + }) + .error(function(data) { + console.log('Error: ' + data); + }); + + $scope.getSubCategoriesOf = function() { + $http.get('/api/categories/'+$scope.mainCat) + .success(function(subCategoriesOf) { + $scope.subCategories = subCategoriesOf; + }) + .error(function(data) { + console.log('Error: ' + data); + }); + } + + $scope.logRootCat = function() { + // console.log($scope.mainCategories); + } + + $scope.createMacro = function() { + $scope.formData.username = $scope.username; + $http.post('/api/macros', $scope.formData) + .success(function(data) { + $scope.formData = {}; + $scope.newMacro = data; + }) + .error(function(data) { + console.log('Error : ' + data); + }); + } + + $scope.login = function() { + $http.post('/signin', $scope.formLogin) + .success(function(data) { + $scope.formLogin = {}; + location.reload(); + }) + .error(function(data) { + console.log('error : ' + data); + }); + } +}); diff --git a/pool/shard001/JavaScript/0006245_cam-tasklist-form.js b/pool/shard001/JavaScript/0006245_cam-tasklist-form.js new file mode 100644 index 0000000000000000000000000000000000000000..eb7584850fd8752b94b863d5874dacd7b04c36c8 --- /dev/null +++ b/pool/shard001/JavaScript/0006245_cam-tasklist-form.js @@ -0,0 +1,288 @@ +'use strict'; +var fs = require('fs'); + +var template = fs.readFileSync(__dirname + '/cam-tasklist-form.html', 'utf8'); + +var EMBEDDED_KEY = 'embedded:', + APP_KEY = 'app:', + ENGINE_KEY = 'engine:', + DEPLOYMENT_KEY = 'deployment:'; + +function compact(arr) { + var a = []; + for (var ay in arr) { + if (arr[ay]) { + a.push(arr[ay]); + } + } + return a; +} + +var noop = function() {}; + +module.exports = [function() { + + return { + + restrict: 'A', + + scope: { + tasklistForm : '=', + + /* + * current options are: + * - hideCompleteButton: to hide the complete button inside the form directive + * - disableCompleteButton: to disable or enable the complete button inside + * the form directive + * - disableForm: to disable or enable the form + * - disableAddVariableButton: to disable or enable the 'Add Variable' button + * inside a generic form + */ + options: '=', + + /* + * contains parameter like taskId, processDefinitionId, processDefinitionKey etc. + */ + params: '=', + + /* will be used to make a callback when the form will be completed */ + onFormCompletionCallback: '&', + + /* + * will be used to register a completion handler, when the completion + * will be trigger from the outside of a form + */ + onFormCompletion: '&', + + /* + * is a callback which will called when the validation state of the + * form changes (pass the flag '$invalid'). + */ + onFormValidation: '&' + }, + + template: template, + + controller: [ + '$scope', + 'Uri', + 'camAPI', + function( + $scope, + Uri, + camAPI + ) { + + var processDefinitionResource = camAPI.resource('process-definition'); + var caseDefinitionResource = camAPI.resource('case-definition'); + var deploymentResource = camAPI.resource('deployment'); + + // setup ////////////////////////////////////////////////////////////////// + + $scope.onFormCompletionCallback = $scope.onFormCompletionCallback() || noop; + $scope.onFormCompletion = $scope.onFormCompletion() || noop; + $scope.onFormValidation = $scope.onFormValidation() || noop; + $scope.completionHandler = noop; + $scope.saveHandler = noop; + + $scope.$loaded = false; + $scope.completeInProgress = false; + + // handle tasklist form /////////////////////////////////////////////////// + + $scope.$watch('tasklistForm', function(value) { + $scope.$loaded = false; + if (value) { + parseForm(value); + } + }); + + $scope.asynchronousFormKey = { + loaded: false, + failure: false + }; + + function setAsynchronousFormKeyFailure(err) { + $scope.asynchronousFormKey.failure = true; + $scope.asynchronousFormKey.error = err; + } + + function setAsynchronousFormKey(formKey) { + $scope.asynchronousFormKey.key = formKey; + $scope.asynchronousFormKey.loaded = true; + } + + function parseForm(form) { + var key = form.key, + applicationContextPath = form.contextPath; + + // structure may be [embedded:][app:]formKey + // structure may be [embedded:][deployment:]formKey + + // structure may be [app:]formKey + // structure may be [deployment:]formKey + + if (!key) { + form.type = 'generic'; + return; + } + + if (key.indexOf(EMBEDDED_KEY) === 0) { + key = key.substring(EMBEDDED_KEY.length); + form.type = 'embedded'; + } else { + form.type = 'external'; + } + + if (key.indexOf(APP_KEY) === 0) { + if (applicationContextPath) { + key = compact([applicationContextPath, key.substring(APP_KEY.length)]) + .join('/') + // prevents multiple "/" in the URI + .replace(/\/([\/]+)/, '/'); + setAsynchronousFormKey(key); + } + } + + else if (key.indexOf(DEPLOYMENT_KEY) === 0) { + var resourceName = key.substring(DEPLOYMENT_KEY.length); + + var loadResourceInDeployment = function(deploymentId) { + deploymentResource.getResources(deploymentId, function(err, resourcesData) { + if (err) { + setAsynchronousFormKeyFailure(err); + } else { + var resourceFound = false; + // Find the resource with the given name from the list of all resources of a deployment + for (var index = 0; index < resourcesData.length; ++index) { + if (resourcesData[index].name === resourceName) { + key = Uri.appUri('engine://engine/:engine/deployment/' + deploymentId + '/resources/' + resourcesData[index].id + '/data'); + setAsynchronousFormKey(key); + resourceFound = true; + break; + } + } + if (!resourceFound) { + setAsynchronousFormKeyFailure(new Error('Resource ' + resourceName + ' not found in deployment')); + } + } + }); + }; + + if ($scope.params.processDefinitionId) { + processDefinitionResource.get($scope.params.processDefinitionId, function(err, deploymentData) { + if (err) { + setAsynchronousFormKeyFailure(err); + } else { + loadResourceInDeployment(deploymentData.deploymentId); + } + }); + } else if ($scope.params.caseDefinitionId) { + caseDefinitionResource.get($scope.params.caseDefinitionId, function(err, deploymentData) { + if (err) { + setAsynchronousFormKeyFailure(err); + } else { + loadResourceInDeployment(deploymentData.deploymentId); + } + }); + } + } + + else if(key.indexOf(ENGINE_KEY) === 0) { + // resolve relative prefix + key = Uri.appUri(key); + setAsynchronousFormKey(key); + } + + else { + setAsynchronousFormKey(key); + } + + form.key = key; + } + + // completion ///////////////////////////////////////////// + + var completionCallback = function(err, result) { + $scope.onFormCompletionCallback(err, result); + $scope.completeInProgress = false; + }; + + var complete = $scope.complete = function() { + $scope.completeInProgress = true; + $scope.completionHandler(completionCallback); + }; + + $scope.onFormCompletion(complete); + + $scope.showCompleteButton = function() { + return $scope.options && + !$scope.options.hideCompleteButton && + $scope.$loaded; + }; + + $scope.disableCompleteButton = function() { + return $scope.completeInProgress || $scope.$invalid || + ($scope.options && $scope.options.disableCompleteButton); + }; + + // save /////////////////////////////////////////////////// + + $scope.save = function(evt) { + $scope.saveHandler(evt); + }; + + // API //////////////////////////////////////////////////// + + this.notifyFormInitialized = function() { + $scope.$loaded = true; + }; + + this.notifyFormInitializationFailed = function(error) { + $scope.tasklistForm.$error = error; + // mark the form as initialized + this.notifyFormInitialized(); + // set the '$invalid' flag to true to + // not be able to complete a task (or start + // a process) + this.notifyFormValidated(true); + }; + + this.notifyFormCompleted = function(err) { + $scope.onFormCompletion(err); + }; + + this.notifyFormValidated = function(invalid) { + $scope.$invalid = invalid; + $scope.onFormValidation(invalid); + }; + + this.notifyFormDirty = function(dirty) { + $scope.$dirty = dirty; + }; + + + this.getOptions = function() { + return $scope.options || {}; + }; + + this.getTasklistForm = function() { + return $scope.tasklistForm; + }; + + this.getParams = function() { + return $scope.params || {}; + }; + + this.registerCompletionHandler = function(fn) { + $scope.completionHandler = fn || noop; + }; + + this.registerSaveHandler = function(fn) { + $scope.saveHandler = fn || noop; + }; + + + }] + }; +}]; diff --git a/pool/shard001/JavaScript/0006246_summary-list-post-example-1.2.x.js b/pool/shard001/JavaScript/0006246_summary-list-post-example-1.2.x.js new file mode 100644 index 0000000000000000000000000000000000000000..8b4447ae641c9f2a99585a1b7a2bef537b941d37 --- /dev/null +++ b/pool/shard001/JavaScript/0006246_summary-list-post-example-1.2.x.js @@ -0,0 +1,17 @@ +// Download the Node helper library from twilio.com/docs/node/install +// These vars are your accountSid and authToken from twilio.com/user/account +const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'; +const authToken = 'your_auth_token'; +const client = require('twilio')(accountSid, authToken); + +client.calls.feedbackSummary.create( + { + startDate: '2014-06-01', + endDate: '2014-06-30', + includeSubaccounts: true, + statusCallback: 'http://www.example.com/feedback', + }, + (err, summary) => { + console.log(summary.sid); + } +); diff --git a/pool/shard001/JavaScript/0006247_WaitlistView.js b/pool/shard001/JavaScript/0006247_WaitlistView.js new file mode 100644 index 0000000000000000000000000000000000000000..e1b1cbb0b32813283fb677493f1418b77b5751da --- /dev/null +++ b/pool/shard001/JavaScript/0006247_WaitlistView.js @@ -0,0 +1,102 @@ +/** + * View for the room waitlist + * @module views/pro/WaitlistView + */ +var WaitlistCollection = require('../../collections/WaitlistCollection'); +var WaitlistUserView = require('./WaitlistUserView'); +var panes = require('./panes'); + +var WaitlistView = Backbone.View.extend( +/** @lends WaitlistView.prototype */ +{ + /** + * Adds DOM elements and functionality for waitlist in the Pro-View + * @class WaitlistView + * + * @augments Backbone.View + * @constructs + */ + initialize: function(){ + var JST = window.plugPro.JST; + this.waitlistHTML = JST['waitlist.html'](); + this.waitlistCollection = new WaitlistCollection(); + }, + + id: "plugpro-waitlist", + + /** + * Render the WaitlistView + */ + render: function(){ + this.$el.append( this.waitlistHTML ); + + this.waitlistCollection.on( "reset", this.onListUpdate.bind(this) ); + API.on( API.WAIT_LIST_UPDATE, this.waitlistCollection.fetch.bind( this.waitlistCollection ) ); + + this.waitlistCollection.fetch(); + }, + + /** + * Re-render the entire waitlist + */ + onListUpdate: function(){ + this.fragment = document.createDocumentFragment(); + this.$el.find('.plugpro-waitlist-list').html(""); + this.childViews = []; + this.waitlistCollection.each( this.appendUser.bind(this) ); + + this.$el.find('.plugpro-waitlist-list').append( this.fragment ); + }, + + /** + * Add user view to the DOM + * @param {object} userModel - Model to use for user view data + */ + appendUser: function( userModel ){ + var userView = new WaitlistUserView({ + model: userModel + }); + + this.childViews.push( userView ); + this.fragment.appendChild( userView.el ); + + userView.render(); + }, + + /** + * Render the WaitlistView + */ + destroy: function(){ + $('#dj-button').attr("style", ""); + this.remove(); + }, + + /** + * Move DOM elements to the correct positions + */ + reposition: function(){ + var windowWidth = $(window).width(); + var windowHeight = $(window).height(); + + var userlistWidth = panes.get('userlist'); + var middleWidth = panes.get('middle'); + var height = (windowHeight - 109) / 2; + + var width = 250; + + this.$el.css({ + "left": (userlistWidth + middleWidth - width) + "px", + "height": height + "px", + "width": width + "px" + }); + + $('#dj-button').width( this.$el.outerWidth() ); + $('#dj-button').css({ + "left": this.$el.css("left") + }); + + } + +}); + +module.exports = WaitlistView; \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006248_logo.js b/pool/shard001/JavaScript/0006248_logo.js new file mode 100644 index 0000000000000000000000000000000000000000..25d684e9073698c8b862dbd4b73c7596cb909d57 --- /dev/null +++ b/pool/shard001/JavaScript/0006248_logo.js @@ -0,0 +1,19 @@ +'use strict'; + +var chalk = require('chalk'); +var figlet = require('figlet'); + +module.exports = { + display: function(description, version) { + console.log( + chalk.cyan.bold( + figlet.textSync('Git-Crucible', { + horizontalLayout: 'fitted' + }) + ) + ); + console.log(""); + console.log(chalk.magenta(description)); + console.log(chalk.green(chalk.gray.bold("Version: ") + version)); + } +}; diff --git a/pool/shard001/JavaScript/0006250_api-tests.js b/pool/shard001/JavaScript/0006250_api-tests.js new file mode 100644 index 0000000000000000000000000000000000000000..d67c906224d80a8e7774a35e21b00eae0cb5eca1 --- /dev/null +++ b/pool/shard001/JavaScript/0006250_api-tests.js @@ -0,0 +1,74 @@ +import * as rpc from 'jrpc2'; +import {GameBuilder} from '../../model/game/game-builder'; +import {Bid} from '../../model/core/bid'; +import {Card} from '../../model/core/card'; +import {Deck} from '../../model/core/deck'; +import {Seat} from '../../model/core/seat'; + +import koa from 'koa'; +import createApiMiddleware from '../api'; + +describe('API Integration Tests', () => { + + let client, server; + + before(() => { + let app = koa(); + let api = createApiMiddleware("/api/", __dirname + "/../api/"); + + app.use(api); + server = app.listen(8081); + + let http = new rpc.httpTransport({port: 8081, hostname: 'localhost', path: '/api/'}); + client = new rpc.Client(http); + }); + + after(() => { + server.close(); + }); + + it('getCard', (done) => { + let gameBuilder = GameBuilder.create().newBoard( + Seat.West, + Deck.fromPBN("N:2...A2 7.7..7 A.A..3 456..."), + Bid.createAll("no bid", "no bid", "no bid", "1NT", "no bid", "no bid", "no bid") + ); + + //single call with named parameters + client.invoke('getCard', { boardState: gameBuilder.currentBoard }, function (err, raw) { + let obj = JSON.parse(raw); + expect(obj.result).to.deep.equal({"pip": 4, "suit": 4}); + done(); + }); + }); + + it('getBid', (done) => { + let gameBuilder = GameBuilder.create().newBoard( + Seat.North, + Deck.fromPBN("N:AKQ63.A97.72.T92 J52.KJT2.J.AQ743 84.865.QT85.KJ86 T97.Q43.AK9643.5") + ); + + // single call with positional parameter + client.invoke('getBid', [ gameBuilder.build() ], function (err, raw) { + let obj = JSON.parse(raw); + expect(obj.result).to.deep.equal({"type": 2, "level": 1, "suit": 4}); + done(); + }); + }); + + it('getBid errors', (done) => { + let gameBuilder = GameBuilder.create().newBoard( + Seat.North, + Deck.fromPBN("N:AAQ63.A97.72.T92 J52.KJT2.J.AQ743 84.865.QT85.KJ86 T97.Q43.AK9643.5") + ); + + // single call with positional parameter + client.invoke('getBid', [ gameBuilder.build() ], function (err, raw) { + let obj = JSON.parse(raw); + expect(obj.error).to.deep.equal({"code": -32099, "message": "Cannot read property 'type' of undefined"}); + expect(obj.result).to.be.undefined; + done(); + }); + }); + +}); diff --git a/pool/shard001/JavaScript/0006255_message.js b/pool/shard001/JavaScript/0006255_message.js new file mode 100644 index 0000000000000000000000000000000000000000..1a95659190124eb13ebc9c45f1dbad5be5687a59 --- /dev/null +++ b/pool/shard001/JavaScript/0006255_message.js @@ -0,0 +1,28 @@ +/** + * @author xialeistudio + * @date 2016/8/9 0009 + */ +'use strict'; +require('should'); +const config = require('../config.json'); +const appid = config.wechat.appId; +const appsecret = config.wechat.appSecret; +const Wechat = require('../lib/wechat'); +const wechat = new Wechat(appid, appsecret); +const Message = require('../lib/message'); +const message = new Message(wechat.getInstance()); +describe('test message', function() { + it('send template message errcode should equal 0', (done)=> { + message.sendTemplate('oA-yljj5cBGSvnwFodHT1iqis7X8', 'G4C9rNCejbhyYzh7xsOh46pieLelrmj_bLQtRhdOqkY', 'http://www.baidu.com', { + orderId: { + value: '20160101' + }, + status: { + value: '已发货' + } + }).then((data)=> { + data.should.have.property('errcode', 0); + done(); + }).catch(done); + }); +}); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006257_vara.js b/pool/shard001/JavaScript/0006257_vara.js new file mode 100644 index 0000000000000000000000000000000000000000..9b045b50d7ec74ab10e6ef3d956199db421b4f43 --- /dev/null +++ b/pool/shard001/JavaScript/0006257_vara.js @@ -0,0 +1,188 @@ + +/* +angular.module('myApp') +.controller('yksikkoController', + ['$scope','$routeParams','$location','$window','$route','userData', function($scope,$routeParams,$location,$window,$route,userData){ + + var kysymykset = []; +// var self = this; + console.log("This on "); + console.dir(this); + + $scope.pisteet = {oikein: 0, + vaarin: 0, + monesko: 1, + maksimi: 5, + //parasTulos:0, + laskeArvosana:function(){return (this.oikein/this.maksimi);}}; + + $scope.asetukset = {taso:'helppo', + kysymyksetLkm:5, + vaikeusTasoMinimi:0, + vaikeusTasoMaksimi:3, + } + // + // Laskee sopivan tason luotavaan kysymykseen + // Käytännössä on vain lineaarikuvaus + $scope.asetukset.ohjaus = function(){ + var palautettava = O.linearMap(1, this.kysymyksetLkm, + this.vaikeusTasoMinimi, this.vaikeusTasoMaksimi, + $scope.pisteet.monesko); + console.log("X1="+1+" X2="+this.kysymyksetLkm+" Y1="+this.vaikeusTasoMinimi+" Y2="+this.vaikeusTasoMaksimi+ + " X="+$scope.pisteet.monesko+" =>"+palautettava); + return palautettava; + + } + + $scope.asetukset.peliMoodi = "PISTEET" + // + // ALUSTA + $scope.alusta = function(){ + console.log("routeparams:"); + console.dir($routeParams); + + $scope.asetukset.peliLaji = $routeParams.peliLaji; + $scope.asetukset.peliMoodi = $routeParams.peliMoodi; + $scope.asetukset.taso = $routeParams.taso; + $scope.pisteet.maksimi = parseInt($routeParams.kysymyksienLkm); + + // + // AlkuAsetukset + if($scope.asetukset.peliMoodi === 'pistepeli'){ + // $scope.asetukset.peliMoodi = "PISTEET" + + if($scope.asetukset.taso === 'helppo'){ + $scope.asetukset.vaikeusTasoMinimi = 1; + $scope.asetukset.vaikeusTasoMaksimi = 3; + } + else if($scope.asetukset.taso === 'normaali'){ + $scope.asetukset.vaikeusTasoMinimi = 3; + $scope.asetukset.vaikeusTasoMaksimi = 7; + } + else if($scope.asetukset.taso === 'vaikea'){ + $scope.asetukset.vaikeusTasoMinimi = 7; + $scope.asetukset.vaikeusTasoMaksimi = 10; + } + } + $scope.kysymys = new Kysymys[$scope.asetukset.peliLaji](); + $scope.kysymys.luoKysymys($scope.asetukset.ohjaus()); + console.log("Kysymyksen taso tulee olemaan:"+$scope.asetukset.ohjaus()) + console.log("Kysymys on valmis:") + console.dir($scope.kysymys); + + } + + $scope.vastausKentta = { arvo:"" }; + // TILA kertoo ohjelman tilan: 0 - Uusi kysymys, 1 - Vastaus oli oikein, 2 - Vastaus oli väärin, 3 - Kysymykset loppuneet viimeinen oikein, 4 - Kysymykset loppuneet viimeinen väärin + $scope.TILA = 'UUSI'; + + $scope.esitaKysymys = function(){ + return $scope.kysymys.esitaKysymys(); + } + + $scope.esitaKysymyksenYksikko = function(){ + return $scope.kysymys.esitaKysymyksenYksikko(); + } + + $scope.esitaSelitys = function(){ + console.log($scope.kysymys.esitaSelitys()); + //setTimeout(function(){$scope.$apply();},1000); + setTimeout(function(){ + console.log('Päivitys Math'); + function f(x) { console.log("-->"+x); }; + MathJax.Hub.Queue([f,15],["Typeset",MathJax.Hub,"matikka"]); + MathJax.Callback.Queue([f,12],["Typeset",MathJax.Hub,"matikka"]); + + },1000); + + var returnTeksti = $scope.kysymys.esitaSelitys(); + console.log("Tämä sivulle:->"+returnTeksti); + return returnTeksti; + } + + $scope.matikka = function() { + MathJax.Hub.Queue(["Reprocess",MathJax.Hub,"matikka"],["Typeset",MathJax.Hub]); + } + + $scope.debugOikein = function(){ + $scope.vastausKentta.arvo = $scope.kysymys.oikeaVastaus(); + $scope.vastaa(); + $scope.seuraavaKysymys(); + } + $scope.debugVaarin = function(){ + $scope.vastausKentta.arvo = $scope.kysymys.oikeaVastaus() + 1; + $scope.vastaa(); + $scope.seuraavaKysymys(); + } + + + // + // VASTAA + // 1. Tarkistaa onko vastaus oikein + // 1. Korottaa oikein menneitä pisteitä + // 2. Muuttaa VIEWin tilaksi OIKEIN + // Talletetaan että vastaus oli oikein + // 2.Vastaus oli vaarin + // 1. Korottaa vaarin menneitä pisteitä + // 2. Muuttaa VIEWin tilaksi VAARIN + // Talletetaan, että vastaus oli väärin + + $scope.vastaa = function() { + // Validoi muoto + var vastaus = parseFloat($scope.vastausKentta.arvo)//.toFixed(3);//validoi($scope.vastaus) + console.log("Vastasit "+vastaus); + + if( $scope.vastausKentta.arvo == $scope.kysymys.oikeaVastaus() ){ + console.debug("Oikein!"); + $scope.pisteet.oikein++; + kysymykset.push({kysymys:$scope.kysymys,oikein:true}); + $scope.TILA = 'OIKEIN'; + } + else{ + $scope.pisteet.vaarin++; + console.debug("Väärin"); + $scope.TILA = 'VAARIN'; + kysymykset.push({kysymys:$scope.kysymys,oikein:false}) + } + + } // Vastaa-funktio loppuu + + // + // SEURAAVA + // 1.asettaa VIEWssä vastauskenttään tyhjän arvon + // + // 2.Talleta vanha kysymys + // + // 3.Tutkii oliko edellinen viimeine tehtävä + // Se oli + // Aseta VIEW näyttämään loppupisteen + // Laheta kysymysten tiedot serverille + // Se ei ollut + // Aseta VIEW näyttämään uusi kysymys + // Korota tehtyjen kysymysten määrää + // Talleta vanha kysymys + // Luo uusi kysymys sopivan tason mukaisesti + // + $scope.seuraavaKysymys = function(){ + $scope.vastausKentta.arvo = ""; + + if($scope.pisteet.monesko === $scope.pisteet.maksimi){ + console.log(">Sama oli joten asetetaan tila LOPPU") + $scope.TILA = 'LOPPU'; + userData.paivitaPeliTilanne(kysymykset); + } + else{ + console.log(">Sama oli joten asetetaan tila UUSI") + $scope.TILA = 'UUSI'; + $scope.pisteet.monesko++; + $scope.kysymys = new Kysymys[$scope.asetukset.peliLaji](); + $scope.kysymys.luoKysymys($scope.asetukset.ohjaus()); + } + console.log("Kysymykset") + console.dir(kysymykset); + + }; // seuraavaKysymys-funktio loppuu + + + $scope.alusta(); +}]); diff --git a/pool/shard001/JavaScript/0006258_tags.js b/pool/shard001/JavaScript/0006258_tags.js new file mode 100644 index 0000000000000000000000000000000000000000..997189504f0135fa5d58b61a60d4f91fc4243ab8 --- /dev/null +++ b/pool/shard001/JavaScript/0006258_tags.js @@ -0,0 +1,37 @@ +'use strict'; + +const Tag = require('../../common/models/tag'); +const Joi = require('joi'); +const Boom = require('boom'); +const _ = require('lodash'); + +module.exports = [ + { + path: '/api/tags/auto-complete', + method: 'GET', + config: { + validate: { + query: { + query: Joi.string().max(25).allow(''), + top: Joi.number().min(3).max(25).default(5) + } + } + }, + handler: (request, reply) => { + var query = Tag.find() + .sort('-rank') + .limit(request.query.top); + + if (request.query.query && request.query.query.length > 0) { + query.where('tag', new RegExp('^' + request.query.query, 'i')); + } + + query + .exec() + .then(tags => { + reply(_.map(tags, tag => tag.tag)); + }) + .catch(err => reply(Boom.badImplementation(err))); + } + } +]; diff --git a/pool/shard001/JavaScript/0006262_script.js b/pool/shard001/JavaScript/0006262_script.js new file mode 100644 index 0000000000000000000000000000000000000000..fd253b56f1f59f2a1197e73555df2a4930f5a475 --- /dev/null +++ b/pool/shard001/JavaScript/0006262_script.js @@ -0,0 +1,108 @@ +(function($){ + var toTop = $('#toTop').length ? $('#toTop').offset().top - $(window).height() + 20 : 0; + + // Share + $('body').on('click', function(){ + $('.article-share-box.on').removeClass('on'); + }).on('click', '.article-share-link', function(e){ + e.stopPropagation(); + + var $this = $(this), + url = $this.attr('data-url'), + encodedUrl = encodeURIComponent(url), + id = 'article-share-box-' + $this.attr('data-id'), + offset = $this.offset(); + + if ($('#' + id).length){ + var box = $('#' + id); + + if (box.hasClass('on')){ + box.removeClass('on'); + return; + } + } else { + var html = [ + '
    ', + '', + '
    ', + '', + '', + '', + '', + '', + '
    ', + '
    ' + ].join(''); + + var box = $(html); + + $('body').append(box); + } + + $('.article-share-box.on').hide(); + + box.css({ + top: offset.top + 25, + left: offset.left + }).addClass('on'); + }).on('click', '.article-share-box', function(e){ + e.stopPropagation(); + }).on('click', '.article-share-box-input', function(){ + $(this).select(); + }).on('click', '.article-share-box-link', function(e){ + e.preventDefault(); + e.stopPropagation(); + + window.open(this.href, 'article-share-box-window-' + Date.now(), 'width=500,height=450'); + }); + + // Caption + $('.article-entry').each(function(i){ + $(this).find('img').each(function(){ + if ($(this).parent().hasClass('fancybox')) return; + if ($(this).hasClass('nofancy')) return; + + var alt = this.alt; + + if (alt) $(this).after('' + alt + ''); + + $(this).wrap(''); + }); + + $(this).find('.fancybox').each(function(){ + $(this).attr('rel', 'article' + i); + }); + }); + + if ($.fancybox){ + $('.fancybox').fancybox(); + } + + // Profile card + $(document).on('click', function () { + $('#profile').removeClass('card'); + }).on('click', '#profile-anchor', function (e) { + e.stopPropagation(); + $('#profile').toggleClass('card'); + }).on('click', '.profile-inner', function (e) { + e.stopPropagation(); + }); + + // To Top + $(document).on('scroll', function () { + if ($(document).width() >= 800) { + if($(this).scrollTop() > toTop) { + $('#toTop').addClass('fix'); + $('#toTop').css('left', $('#sidebar').offset().left); + } else { + $('#toTop').removeClass('fix'); + } + } else { + $('#toTop').addClass('fix'); + $('#toTop').css('right', 20); + } + }).on('click', '#toTop', function () { + $(document).scrollTop(0); + }); + +})(jQuery); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006265_controller.js b/pool/shard001/JavaScript/0006265_controller.js new file mode 100644 index 0000000000000000000000000000000000000000..df83a8fa9292e0d76a585208f7041e0d459d9ecc --- /dev/null +++ b/pool/shard001/JavaScript/0006265_controller.js @@ -0,0 +1,28 @@ +'use strict'; + +angular.module('blog.controllers', [ 'blog.services']) +.controller('BlogCtrl', ['$scope', 'blogService', +function($scope, blogService) { + $scope.blogs = blogService.blogs; + + $scope.selectBlog = function(row) { + $scope.selectedRow = row; + }; + + $scope.deletePost = function(blog, index) { + //console.log('delete blog by id='+ blog._id); + blogService.deleteById(blog.id); + $scope.blogs.splice(index, 1); + }; +}]) +.controller('BlogViewCtrl', ['$scope', 'blog', function($scope,blog) { + $scope.blog = blog; + $scope.markdown_content = blog.body; +}]) +.controller('AppCtrl', ['$scope', 'SITE_NAME', function($scope,SITE_NAME) { + $scope.site_name = SITE_NAME; +}]) +.controller('AboutCtrl', ['$scope', 'blog', function($scope,blog) { + $scope.blog = blog; + $scope.markdown_content = blog.body; +}]); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006266_jquery.bootpag.js b/pool/shard001/JavaScript/0006266_jquery.bootpag.js new file mode 100644 index 0000000000000000000000000000000000000000..08f2b00eb751cd4f3a1c547a4174503c84a13a63 --- /dev/null +++ b/pool/shard001/JavaScript/0006266_jquery.bootpag.js @@ -0,0 +1,120 @@ +/* + * bootpag - jQuery plugin for dynamic pagination + * + * Copyright (c) 2013 botmonster@7items.com + * + * Licensed under the MIT license: + * http://www.opensource.org/licenses/mit-license.php + * + * Project home: + * http://botmonster.github.com/jquery-bootpag + * + * Version: 1.0.2 + * + */ +(function($, window) { + + $.fn.bootpag = function(options){ + + var $owner = this, + settings = $.extend({ + total: 0, + page: 1, + maxVisible: null, + leaps: true, + href: 'javascript:void(0);', + hrefVariable: '{{number}}', + next: '»', + prev: '«' + }, + $owner.settings || {}, + options || {}); + + if(settings.total <= 0) + return this; + + if(!settings.maxVisible){ + settings.maxVisible = settings.total; + } + + $owner.settings = settings; + + function renderPage($bootpag, page){ + + var lp, + vis = Math.floor(page / settings.maxVisible) * settings.maxVisible, + $page = $bootpag.find('li'); + + $page.removeClass('disabled'); + lp = page - 1 < 1 ? 1 : + settings.leaps && page - 1 > settings.maxVisible ? + Math.floor((page - 1) / settings.maxVisible) * settings.maxVisible : page - 1; + $page + .first() + .toggleClass('disabled', page === 1) + .attr('data-lp', lp) + .find('a').attr('href', href(lp)); + lp = page + 1 > settings.total ? settings.total : + settings.leaps && page + 1 < settings.total - settings.maxVisible ? + vis + settings.maxVisible + 1: page + 1; + $page + .last() + .toggleClass('disabled', page === settings.total) + .attr('data-lp', lp) + .find('a').attr('href', href(lp));; + + var $currPage = $page.filter('[data-lp='+page+']'); + if(!$currPage.not('.next,.prev').length){ + var d = page <= vis ? -settings.maxVisible : 0; + $page.not('.next,.prev').each(function(index){ + lp = index + 1 + vis + d; + $(this) + .attr('data-lp', lp) + .toggle(lp <= settings.total) + .find('a').html(lp).attr('href', href(lp)); + }); + $currPage = $page.filter('[data-lp='+page+']'); + } + $currPage.addClass('disabled'); + $owner.trigger('page', page); + } + + + function href(c){ + + return settings.href.replace(settings.hrefVariable, c); + } + + return this.each(function(){ + + var $bootpag, lp, me = $(this), + p = ['
      ']; + + if(settings.prev){ + p.push(''); + } + for(var c = 1; c <= Math.min(settings.total, settings.maxVisible); c++){ + p.push('
    • '+c+'
    • '); + } + if(settings.next){ + lp = settings.leaps && settings.total > settings.maxVisible + ? Math.min(settings.maxVisible + 1, settings.total) : 2; + p.push(''); + } + p.push('
    '); + me.find('ul.bootpag').remove(); + me.append(p.join('')).addClass('pagination'); + $bootpag = me.find('ul.bootpag'); + me.find('li').click(function paginationClick(){ + + var me = $(this); + if(me.hasClass('disabled')){ + return; + } + renderPage($bootpag, parseInt(me.attr('data-lp'), 10)); + }); + renderPage($bootpag, settings.page); + }); + } + +})(jQuery, window); diff --git a/pool/shard001/JavaScript/0006271_JsonHelper.js b/pool/shard001/JavaScript/0006271_JsonHelper.js new file mode 100644 index 0000000000000000000000000000000000000000..e713b1a1833b7545cf3a89a3413068a7ca91015d --- /dev/null +++ b/pool/shard001/JavaScript/0006271_JsonHelper.js @@ -0,0 +1,30 @@ +exports.diffUsingJS = function(copyBase, copyNew) { + + // get the baseText and newText values from the two textboxes, and split them into lines + var base = difflib.stringAsLines(JSON.stringify(copyBase, null, "\t")); + var newtxt = difflib.stringAsLines(JSON.stringify(copyNew, null, "\t")); + + // create a SequenceMatcher instance that diffs the two sets of lines + var sm = new difflib.SequenceMatcher(base, newtxt); + + // get the opcodes from the SequenceMatcher instance + // opcodes is a list of 3-tuples describing what changes should be made to the base text + // in order to yield the new text + var opcodes = sm.get_opcodes(); + var diffoutputdiv = document.getElementById("diffoutput"); + + if(diffoutputdiv) { + while (diffoutputdiv.firstChild) diffoutputdiv.removeChild(diffoutputdiv.firstChild); + // build the diff view and add it to the current DOM + diffoutputdiv.appendChild(diffview.buildView({ + baseTextLines: base, + newTextLines: newtxt, + opcodes: opcodes, + viewType: 0 + })); + } +} + +exports.showCommon = function(json) { + $('#json-renderer').jsonViewer(json); +} \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006273_dstr-obj-rest-to-property-with-setter.js b/pool/shard001/JavaScript/0006273_dstr-obj-rest-to-property-with-setter.js new file mode 100644 index 0000000000000000000000000000000000000000..4c315aed6e9f5b01db25ec7fdfd11d4c64dbfdac --- /dev/null +++ b/pool/shard001/JavaScript/0006273_dstr-obj-rest-to-property-with-setter.js @@ -0,0 +1,48 @@ +// This file was procedurally generated from the following sources: +// - src/dstr-assignment/obj-rest-to-property-with-setter.case +// - src/dstr-assignment/default/for-of.template +/*--- +description: When DestructuringAssignmentTarget is an object property setter, its value should be binded as rest object. (For..of statement) +esid: sec-for-in-and-for-of-statements-runtime-semantics-labelledevaluation +es6id: 13.7.5.11 +features: [object-rest, destructuring-binding] +flags: [generated] +info: | + IterationStatement : + for ( LeftHandSideExpression of AssignmentExpression ) Statement + + 1. Let keyResult be the result of performing ? ForIn/OfHeadEvaluation(« », + AssignmentExpression, iterate). + 2. Return ? ForIn/OfBodyEvaluation(LeftHandSideExpression, Statement, + keyResult, assignment, labelSet). + + 13.7.5.13 Runtime Semantics: ForIn/OfBodyEvaluation + + [...] + 4. If destructuring is true and if lhsKind is assignment, then + a. Assert: lhs is a LeftHandSideExpression. + b. Let assignmentPattern be the parse of the source text corresponding to + lhs using AssignmentPattern as the goal symbol. + [...] +---*/ +var settedValue; +var executedGetter = false; +var src = { + get y() { executedGetter = true; }, + set y(v) { + settedValue = v; + } +} +src.y = undefined; + +var counter = 0; + +for ({...src.y} of [{ x: 1, y: 2}]) { + assert.sameValue(settedValue.x, 1); + assert.sameValue(settedValue.y, 2); + assert(!executedGetter, "The property should not be accessed"); + + counter += 1; +} + +assert.sameValue(counter, 1); diff --git a/pool/shard001/JavaScript/0006274_unit.js b/pool/shard001/JavaScript/0006274_unit.js new file mode 100644 index 0000000000000000000000000000000000000000..037881290d73941e3ffb628ac2341fb419f35abd --- /dev/null +++ b/pool/shard001/JavaScript/0006274_unit.js @@ -0,0 +1,49 @@ +'use strict'; + +const QUnit = require( 'qunit' ); +const cssjanus = require( '../src/cssjanus' ); + +const testData = require( './data.json' ); + +for ( const name in testData ) { + const data = testData[ name ]; + const args = data.args || [ data.options || {} ]; + + QUnit.test( name, ( assert ) => { + for ( let i = 0; i < data.cases.length; i++ ) { + const input = data.cases[ i ][ 0 ]; + const noop = data.cases[ i ][ 1 ] === undefined; + const output = noop ? input : data.cases[ i ][ 1 ]; + const roundtrip = data.roundtrip !== undefined ? data.roundtrip : !noop; + + assert.equal( + cssjanus.transform( + input, + args[ 0 ], + args[ 1 ] + ), + output, + `case #${i + 1}` + ); + + if ( roundtrip ) { + // Round-trip + assert.equal( + cssjanus.transform( + output, + args[ 0 ], + args[ 1 ] + ), + input, + `case #${i + 1} roundtrip` + ); + + // Keep test data clean + assert.true( + data.cases[ i ][ 1 ] !== input, + `case #${i + 1} should not specify output if it matches the input` + ); + } + } + } ); +} diff --git a/pool/shard001/JavaScript/0006276_visualize.js b/pool/shard001/JavaScript/0006276_visualize.js new file mode 100644 index 0000000000000000000000000000000000000000..42cc085b24a2029a93719013ad267468ed8f6dff --- /dev/null +++ b/pool/shard001/JavaScript/0006276_visualize.js @@ -0,0 +1,138 @@ +$(document).ready(function() { + + var mapCanvas = $('#map-canvas'); + var mapOptions = { + center: { lat: 60.1841396, lng: 24.8300838 }, + zoom: 12, + scaleControl: true + }; + var map = new google.maps.Map(mapCanvas[0], mapOptions); + + var infoWindow = new google.maps.InfoWindow; + function showTitlePopup(event) { + var pre = document.createElement('pre'); + var title = event.feature.getProperty('title'); + if (typeof(title) == 'undefined') + return; + pre.innerHTML = title; + infoWindow.setContent(pre); + infoWindow.setPosition(event.latLng); + infoWindow.open(map); + } + map.data.addListener('click', showTitlePopup); + + map.data.setStyle(function(feature) { + var type = feature.getProperty('type'); + var title = feature.getProperty('title'); + var pointColor = getActivityColor(feature.getProperty('activity')); + if (type === 'raw-point') { + return { + icon: { + path: google.maps.SymbolPath.CIRCLE, + scale: 3, + strokeColor: pointColor, + strokeOpacity: 0.5 + }, + title: title + }; + } else if (type === 'route-point') { + return { + icon: { + path: google.maps.SymbolPath.BACKWARD_CLOSED_ARROW, + scale: 3, + fillColor: 'gold', + fillOpacity: 1.0, + strokeColor: 'black', + strokeWeight: 1 + }, + title: title + }; + } else if (type === 'trace-line') { + return { + strokeColor: pointColor, + + // white is rather invisible at low opacity + strokeOpacity: (pointColor == 'white' && .8 || .333) + }; + } else if (type === 'dest-line') { + return { + strokeColor: '#66F', + strokeWeight: 30, + strokeOpacity: 0.4, + title: title + }; + } else if (type === 'regular-destination') { + return { + icon: { + path: google.maps.SymbolPath.CIRCLE, +// scale: 3 * feature.getProperty('visits')^(1/3), + scale: 5, + strokeColor: 'darkred', + strokeWeight: 1, + fillColor: 'darkred', + fillOpacity: 0.2 + }, + title: title + }; + } else if (type === 'legend-cluster') { + var stop = feature.getProperty('stop'); + var color = stop ? 'darkblue' : 'darkgreen'; + return { + icon: { + path: google.maps.SymbolPath.CIRCLE, +// scale: 3 * feature.getProperty('visits')^(1/3), + scale: stop ? 8 : 5, + strokeColor: color, + strokeWeight: 1, + fillColor: color, + fillOpacity: 0.2 + }, + title: title + }; + } + }); + + var currentDate; + + function update(date) { + if (date === currentDate) + return; + currentDate = date; + + mapCanvas.css('opacity', 0.1); + map.data.forEach(function(feature) { + map.data.remove(feature); + }); + $.getJSON( + device_id + '/geojson' + + (location.search ? location.search + '&' : '?') + + 'date=' + date, + function(response) { + map.data.addGeoJson(response); + mapCanvas.css('opacity', ''); + if (response.features.length > 1) { + var bounds = new google.maps.LatLngBounds(); + response.features.forEach(function (feature) { + // coordinates may be a pair or a list of pairs + var coordlist = feature.geometry.coordinates; + if (! (coordlist[0] instanceof Array)) + coordlist = [coordlist]; + coordlist.forEach(function (coords) { + bounds.extend(new google.maps.LatLng( + coords[1], coords[0])); + }); + }); + map.fitBounds(bounds); + } + }); + } + + function hashchange() { + var date = location.hash.split("#").splice(-1)[0]; + var today = (new Date()).toISOString().slice(0, 10); + update(date || today); + } + + $(window).on("hashchange", hashchange); + hashchange(); +}); diff --git a/pool/shard001/JavaScript/0006277_GridHandler.js b/pool/shard001/JavaScript/0006277_GridHandler.js new file mode 100644 index 0000000000000000000000000000000000000000..1b6c5df23f936f0be512cef14d65d8c8b9a556cd --- /dev/null +++ b/pool/shard001/JavaScript/0006277_GridHandler.js @@ -0,0 +1,96 @@ +WalmartListingGridHandler = Class.create(ListingGridHandler, { + + // --------------------------------------- + + getComponent: function() + { + return 'walmart'; + }, + + getLogViewUrl: function(rowId) + { + return M2ePro.url.get('adminhtml_walmart_log/listingProduct', { + listing_product_id: rowId + }); + }, + + // --------------------------------------- + + getMaxProductsInPart: function() + { + return 10; + }, + + // --------------------------------------- + + prepareActions: function($super) + { + $super(); + this.movingHandler = new ListingMovingHandler(this); + this.actionHandler = new WalmartListingActionHandler(this); + this.templateCategoryHandler = new WalmartListingTemplateCategoryHandler(this); + this.variationProductManageHandler = new WalmartListingVariationProductManageHandler(this); + this.editChannelDataHandler = new WalmartListingProductEditChannelDataHandler(this); + + this.actions = Object.extend(this.actions, { + + duplicateAction: this.duplicateProducts.bind(this), + + movingAction: this.movingHandler.run.bind(this.movingHandler), + deleteAndRemoveAction: this.actionHandler.deleteAndRemoveAction.bind(this.actionHandler), + resetProductsAction: this.actionHandler.resetProductsAction.bind(this.actionHandler), + + changeTemplateCategoryIdAction: (function(id) { + id = id || this.getSelectedProductsString(); + this.templateCategoryHandler.validateProductsForTemplateCategoryAssign(id, null) + }).bind(this) + + }); + + }, + + // --------------------------------------- + + tryToMove: function(listingId) + { + this.movingHandler.submit(listingId, this.onSuccess); + }, + + onSuccess: function() + { + this.unselectAllAndReload(); + }, + + // --------------------------------------- + + duplicateProducts: function() + { + this.scroll_page_to_top(); + MagentoMessageObj.clearAll(); + + new Ajax.Request(M2ePro.url.get('adminhtml_walmart_listing/duplicateProducts'), { + method: 'post', + parameters: { + component: this.getComponent(), + ids: this.getSelectedProductsString() + }, + onSuccess: (function(transport) { + + try { + var response = transport.responseText.evalJSON(); + + MagentoMessageObj['add' + response.type[0].toUpperCase() + response.type.slice(1)](response.message); + + if (response.type != 'error') { + this.unselectAllAndReload(); + } + + } catch (e) { + MagentoMessageObj.addError('Internal Error.'); + } + }).bind(this) + }); + } + + // --------------------------------------- +}); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006278_role.route.js b/pool/shard001/JavaScript/0006278_role.route.js new file mode 100644 index 0000000000000000000000000000000000000000..90d998be76b63363e34d1d06d1199fdfa2917625 --- /dev/null +++ b/pool/shard001/JavaScript/0006278_role.route.js @@ -0,0 +1,22 @@ +(function() { + 'use strict'; + + var roleController = require('./../controllers/role.controller'), + userAuth = require('./../middlewares/userAuth'), + roleAuth = require('./../middlewares/roleAuth'), + verifyAdmin = require('./../middlewares/verifyAdmin'); + + module.exports = function(router) { + + // allow admin to create and read roles + router.route('/roles') + .post(userAuth, verifyAdmin, roleController.createRole) + .get(userAuth, verifyAdmin, roleController.getAllRoles); + + // allow authorized role to update or delete a particular role + router.route('/roles/:id') + .get(userAuth, roleAuth, roleController.getRoleById) + .put(userAuth, roleAuth, roleController.updateRole) + .delete(userAuth, roleAuth, roleController.deleteRole); + }; +})(); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006282_collectionView.js b/pool/shard001/JavaScript/0006282_collectionView.js new file mode 100644 index 0000000000000000000000000000000000000000..bdae04f795612846cc30ceef8f3d293e62ec5b57 --- /dev/null +++ b/pool/shard001/JavaScript/0006282_collectionView.js @@ -0,0 +1,183 @@ +'use strict'; + +var Collection = require('ampersand-collection'); +var SubCollection = require('ampersand-subcollection'); +var React = require('react'); +var merge = require('lodash.merge'); +var view = require('./view'); +var constructCollection = require('../util/ensureInstance').collection; + +function bindIfFn(fn, ctx) { + if (typeof fn === 'function') { + return fn.bind(ctx); + } + return fn; +} + +module.exports = function(config) { + if (config == null) { + throw new Error('config parameter is required'); + } + if (config.itemView == null) { + throw new Error('itemView attribute is required'); + } + var configCollection = config.collection; + delete config.collection; + + // items = array of item views + // collection = ampersand collection + var CollectionViewMixin = { + collectionName: 'modelView', + propTypes: { + collection: React.PropTypes.oneOfType([ + React.PropTypes.func, + React.PropTypes.object, + React.PropTypes.instanceOf(Collection) + ]), + data: React.PropTypes.arrayOf(React.PropTypes.object), + query: React.PropTypes.object, + offset: React.PropTypes.number, + limit: React.PropTypes.number, + where: React.PropTypes.object, + filter: React.PropTypes.func, + filters: React.PropTypes.arrayOf(React.PropTypes.func), + watch: React.PropTypes.arrayOf(React.PropTypes.string), + sort: React.PropTypes.oneOfType([ + React.PropTypes.string, + React.PropTypes.func + ]) + }, + + // most options can be passed via config or props + // props takes precedence + getDefaultProps: function(){ + return { + collection: configCollection, + data: config.data, + query: config.query, + offset: config.offset, + limit: config.limit, + where: config.where, + filter: config.filter, + filters: config.filters, + watch: config.watch, + sort: config.sort + }; + }, + + // on component mount we initialize everything + componentWillMount: function() { + this._initialize(this.props); + this._computeItemsWithContext(); + }, + + componentWillReceiveProps: function(nextProps) { + this._configureItems(nextProps); + }, + + componentWillUpdate: function(){ + this._computeItemsWithContext(true); + }, + + _collectionFetchFailed: function(m, res) { + var notFound = res.status === 404 || res.status === 204; + var handled404 = notFound && this.collectionNotFound; + if (this.collectionFetchFailed) { + this.collectionFetchFailed.apply(this, arguments); + } + if (handled404) { + this.collectionNotFound.apply(this, arguments); + } + + this.collection = null; + if (!this.collectionFetchFailed && !handled404) { + throw new Error('Collection fetch failed with a ' + res.status); + } + }, + + _initialize: function(props) { + // get sync and create collection based on model + // model passed in via props or config + var collection = constructCollection(props.collection, props); + + var setCollection = (function() { + this.collection = collection; + // create items sub-collection + this._items = new SubCollection(this.collection); + this._configureItems(props); + // TODO: remove events on prop change switch up or destroy + this._items.on('add change remove sort reset', this.tryUpdate); + if (this.collectionDidFetch) { + this.collectionDidFetch(); + } + this.tryUpdate(); + }).bind(this); + + // TODO: override all sync behavior to run errors and success + // through our hooks + if (collection._needsInitialFetch) { + collection.fetch({ + success: setCollection, + error: this._collectionFetchFailed + }); + } else { + setCollection(); + } + }, + + // internal fn to sync props to shadow collection + _configureItems: function(props) { + if (typeof props !== 'object') { + throw new Error('_configureItems called with invalid props'); + } + // not initialized yet + if (!this._items) { + return; + } + this._items.configure({ + where: props.where, + filter: props.filter, + limit: props.limit, + offset: props.offset, + comparator: bindIfFn(props.sort, this) + }, true); + }, + + // internal fn to sync this.items with collection + _computeItemsWithContext: function(runFilters) { + var runTheTrap = this._computeItems.bind(this, runFilters); + React.withContext(this.context, runTheTrap); + }, + _computeItems: function(runFilters) { + // nothing to compute, data hasnt been constructed yet + if (!this._items) { + return; + } + + // TODO: switch to transform when available + // https://github.com/AmpersandJS/ampersand-subcollection/issues/31 + if (runFilters) { + this._items.off('add change remove sort', this.tryUpdate); + this._items._runFilters(); + this._items.on('add change remove sort', this.tryUpdate); + } + this.items = this._items.map(function(m, idx) { + var fissionProps = { + model: m, + index: idx, + key: m.cid + }; + + // if itemview props transform, use that merged w/ defaults + // otherwise just defaults + var itemProps = this.getItemViewProps ? + merge(this.getItemViewProps(m, idx), fissionProps) : + fissionProps; + + return this.itemView(itemProps); + }, this); + } + }; + + return view(config, [CollectionViewMixin]); +}; \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006285_request.js b/pool/shard001/JavaScript/0006285_request.js new file mode 100644 index 0000000000000000000000000000000000000000..2f0be5dba36e55e456d80af5c6de050d36cd32b7 --- /dev/null +++ b/pool/shard001/JavaScript/0006285_request.js @@ -0,0 +1,51 @@ +var _ = require('lodash'); +_.mergeDefaults = require('merge-defaults'); +var request = require('request'); +var fs = require('fs'); +var functions = reqfile('lib/functions'); +var pathObj = require("object-path"); + +module.exports.load = function(bot, options) { + if (!options) { options = {}; } + options = _.mergeDefaults(options, { + call: '!request', + url: 'http://private-7c96a-test3920.apiary-mock.com/test/__REQUEST__', + select: 'items.0.name', + message: 'Here is your information: __SELECT__', + helper: { + title: 'Get specific info', + command: ' [query]', + example: ' unicorn' + } + }); + + _.each(['onMessage', 'onPrivateMessage'], function(messageType){ + var call = options.call + ' (.+)'; + + var priv = false; + if (messageType === 'onPrivateMessage') { priv = true; } + bot[messageType](new RegExp('^' + call + '$', 'i'), onMessage(options, priv)); + }); + + return options; +}; + +var onMessage = function(options, priv) { + return function(channel, from, message, matches) { + var _this = this; + + if (priv) { matches = message; message = from; from = null; } + + var search = encodeURI(matches[1]); + + var url = options.url.replace('__REQUEST__', search); + + request.get(url, function(err, resp, body){ + var response = JSON.parse(body); + var select = pathObj.get(response, options.select); + var message = options.message.replace('__SELECT__', select); + + _this.message(channel, message); + }); + }; +}; \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006288_mongoose.js b/pool/shard001/JavaScript/0006288_mongoose.js new file mode 100644 index 0000000000000000000000000000000000000000..fffabb0ba075f8087bc5ae6eb3c559ca3d635159 --- /dev/null +++ b/pool/shard001/JavaScript/0006288_mongoose.js @@ -0,0 +1,17 @@ +module.exports = function(CONFIG){ + var mongoose = require('mongoose'); + var db = mongoose.connection; + + db.on('error', console.error.bind(console, 'connection error:')); + + db.once('open', function callback(){ + console.log('Connected to DB'); + }); + + mongoose.connect('mongodb://'+CONFIG.mongo.host+':'+CONFIG.mongo.port+'/'+CONFIG.mongo.db, CONFIG.mongo.options); + + return mongoose; +} + + + diff --git a/pool/shard001/JavaScript/0006289_auth.js b/pool/shard001/JavaScript/0006289_auth.js new file mode 100644 index 0000000000000000000000000000000000000000..3c23d4d45575f6b9fd1f0a27d621492b6742172e --- /dev/null +++ b/pool/shard001/JavaScript/0006289_auth.js @@ -0,0 +1,154 @@ +const credentials = require('./credentials/credential.service.js'); +const users = require('./consumers/user.service.js'); +const applications = require('./consumers/application.service.js'); +const tokens = require('./tokens/token.service.js'); +const utils = require('./utils'); +const config = require('../config'); + +const s = {}; + +s.authenticateCredential = function (id, password, type) { + if (!id || !password || !type) { + return Promise.resolve(false); + } + + if (type === 'key-auth' || type === 'jwt') { + return credentials.getCredential(id, type, { includePassword: true }) + .then(credential => { + if (!credential || !credential.isActive || credential.keySecret !== password) { + return false; + } + return this.validateConsumer(credential.consumerId, { checkUsername: true }); + }); + } + + return this.validateConsumer(id, { checkUsername: true }) + .then((consumer) => { + if (!consumer) { + return false; + } + return Promise.all([consumer, credentials.getCredential(consumer.id, type, { includePassword: true })]); + }).then((validateResult) => { + if (!validateResult) { + return false; + } + + const [consumer, credential] = validateResult; + + if (!credential || !credential.isActive) { + return false; + } + + return Promise.all([ + consumer, + utils.compareSaltAndHashed(password, credential[config.models.credentials.properties[type].properties.passwordKey.default]) + ]); + }).then((credentialResult) => { + if (!credentialResult) { + return false; + } + const [consumer, authenticated] = credentialResult; + + if (!authenticated) { + return false; + } + + return consumer; + }); +}; + +s.authenticateToken = function (token) { + let tokenObj; + const tokenPassword = token.split('|')[1]; + + return tokens.get(token) + .then(_tokenObj => { + tokenObj = _tokenObj; + + if (!tokenObj) { + return null; + } + + return this.validateConsumer(tokenObj.consumerId); + }) + .then(consumer => { + if (!consumer || !consumer.isActive) { + return false; + } else return tokenObj.tokenDecrypted === tokenPassword ? { token: tokenObj, consumer } : false; + }); +}; + +s.authorizeToken = function (_token, authType, scopes) { + if (!scopes || scopes.length === 0) { + return Promise.resolve(true); + } + + scopes = Array.isArray(scopes) ? scopes : [scopes]; + + return tokens.get(_token) + .then(token => { + if (!token) { + return false; + } + + if (scopes && scopes.length && !token.scopes) { + return false; + } + + return scopes.every(scope => token.scopes.indexOf(scope) !== -1); + }); +}; + +s.authorizeCredential = function (id, authType, scopes) { + if (!scopes || !scopes.length) { + return Promise.resolve(true); + } + + return credentials.getCredential(id, authType) + .then(credential => { + if (credential) { + if (!credential.scopes) { + return false; + } + return scopes.every(scope => credential.scopes.indexOf(scope) !== -1); + } + }); +}; + +s.validateConsumer = function (id, options = {}) { + return applications.get(id) + .then(app => { + if (app && app.isActive) { + return createApplicationObject(app); + } + + return users.get(id) + .then(_user => { + if (_user && _user.isActive) { + return createUserObject(_user); + } + + if (options.checkUsername) { + const username = id; + return users.find(username) + .then(user => { + if (user && user.isActive) { + return createUserObject(user); + } else return null; + }); + } + + return null; + }); + }); +}; + +function createUserObject (user) { + return Object.assign({ type: 'user' }, user); +} + +function createApplicationObject (app) { + return Object.assign({ type: 'application' }, app); +} + +module.exports = s; diff --git a/pool/shard001/JavaScript/0006290_pad-zeropadding.js b/pool/shard001/JavaScript/0006290_pad-zeropadding.js new file mode 100644 index 0000000000000000000000000000000000000000..5b36a167a8e04eb9a91f8613d874b13e1803c768 --- /dev/null +++ b/pool/shard001/JavaScript/0006290_pad-zeropadding.js @@ -0,0 +1,31 @@ +/* +CryptoJS v3.0.1 +code.google.com/p/crypto-js +(c) 2009-2012 by Jeff Mott. All rights reserved. +code.google.com/p/crypto-js/wiki/License +*/ +/** + * Zero padding strategy. + */ +CryptoJS.pad.ZeroPadding = { + pad: function (data, blockSize) { + // Shortcut + var blockSizeBytes = blockSize * 4; + + // Pad + data.clamp(); + data.sigBytes += blockSizeBytes - ((data.sigBytes % blockSizeBytes) || blockSizeBytes); + }, + + unpad: function (data) { + // Shortcut + var dataWords = data.words; + + // Unpad + var i = data.sigBytes - 1; + while (!((dataWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff)) { + i--; + } + data.sigBytes = i + 1; + } +}; diff --git a/pool/shard001/JavaScript/0006291_yarn-spec.js b/pool/shard001/JavaScript/0006291_yarn-spec.js new file mode 100644 index 0000000000000000000000000000000000000000..25174df63d0f27f66647e960b109ea4af0676a32 --- /dev/null +++ b/pool/shard001/JavaScript/0006291_yarn-spec.js @@ -0,0 +1,73 @@ +'use strict'; +const expect = require('chai').expect; +const proxyquire = require('proxyquire'); +const sinon = require('sinon'); + +let yarn; + +describe('Unit: yarn', function () { + let currentEnv; + let execa; + + beforeEach(function () { + currentEnv = process.env; + process.env = {}; + + execa = sinon.stub().returns(new Promise((resolve) => {resolve();})); + yarn = proxyquire('../../../lib/utils/yarn', { + execa: execa + }); + }); + + afterEach(function () { + process.env = currentEnv; + }); + + it('spawns yarn process with no arguments correctly', function () { + let promise = yarn(); + + return promise.then(function () { + expect(execa.calledOnce).to.be.true; + expect(execa.args[0]).to.be.ok; + expect(execa.args[0]).to.have.lengthOf(3); + expect(execa.args[0][1]).to.deep.equal([]); + }); + }); + + it('spawns yarn process with correct arguments', function () { + let promise = yarn(['cache', 'clear']); + + return promise.then(function () { + expect(execa.calledOnce).to.be.true; + expect(execa.args[0]).to.be.ok; + expect(execa.args[0]).to.have.lengthOf(3); + expect(execa.args[0][1]).to.deep.equal(['cache', 'clear']); + }); + }); + + it('correctly passes through options', function () { + let promise = yarn([], {cwd: 'test'}); + + return promise.then(function () { + expect(execa.calledOnce).to.be.true; + expect(execa.args[0]).to.be.ok; + expect(execa.args[0]).to.have.lengthOf(3); + expect(execa.args[0][2]).to.be.an('object'); + expect(execa.args[0][2].cwd).to.equal('test'); + }); + }); + + it('respects process.env overrides but doesn\'t mutate process.env', function () { + process.env.TESTENV = 'test'; + + let promise = yarn([], {env: {TESTENV: 'override'}}); + + return promise.then(() => { + expect(execa.calledOnce).to.be.true; + expect(execa.args[0][2]).to.be.an('object'); + expect(execa.args[0][2].env).to.be.an('object'); + expect(execa.args[0][2].env.TESTENV).to.equal('override'); + expect(process.env.TESTENV).to.equal('test'); + }); + }); +}); diff --git a/pool/shard001/JavaScript/0006293_app.js b/pool/shard001/JavaScript/0006293_app.js new file mode 100644 index 0000000000000000000000000000000000000000..a83cac36f5bbdf7c9be5a9ed59617205ba42dc5c --- /dev/null +++ b/pool/shard001/JavaScript/0006293_app.js @@ -0,0 +1,48 @@ +import React from 'react' +import ReactDOM from 'react-dom' +import {Provider} from 'react-redux' +import {syncHistoryWithStore} from 'react-router-redux' +import {Router, hashHistory} from 'react-router' + +import store from './store/configureStore' + +const history = syncHistoryWithStore(hashHistory, store); + +const routes = { + + path: '/', + indexRoute: { onEnter: (nextState, replace) => replace('/home') }, + childRoutes: [ + require('./routes/home').default, + require('./routes/settings').default, + + + // require('./routes/dashboard').default, + // require('./routes/smartadmin-intel').default, + // require('./routes/widgets').default, + // require('./routes/outlook').default, + // require('./routes/tables').default, + // require('./routes/ui').default, + // require('./routes/graphs').default, + // require('./routes/e-commerce').default, + // require('./routes/misc').default, + // require('./routes/auth').default, + // require('./routes/app-views').default, + // require('./routes/maps').default, + // require('./routes/calendar').default, + // require('./routes/forms').default, + + + // comment unused routes when develop + // this will speed up builds + ] +}; + +ReactDOM.render(( + + + +), document.getElementById('smartadmin-root')); diff --git a/pool/shard001/JavaScript/0006295_popover.js b/pool/shard001/JavaScript/0006295_popover.js new file mode 100644 index 0000000000000000000000000000000000000000..a5020ff3dc14cee30572a829d26d59ddb90366a6 --- /dev/null +++ b/pool/shard001/JavaScript/0006295_popover.js @@ -0,0 +1,177 @@ +var locastyle = locastyle || {}; + +locastyle.popover = (function() { + 'use strict'; + + var config = { + module : '[data-ls-module="popover"]', + idPopover : '#ls-popover-', + popoverClass : '.ls-popover', + trigger : 'click', + events: { + clickAnywhere: 'click.clickanywhere', + opened: 'popover:opened', + closed: 'popover:closed', + destroyed: 'popover:destroyed' + } + } + + function init() { + clickAnywhereClose(); + bindPopover(); + } + + // When click or hover elements, show the popovers + function bindPopover() { + $(config.module).each(function(index, popoverTrigger) { + var trigger = $(popoverTrigger).attr('data-trigger') === 'hover' ? 'mouseover' : config.trigger; + // Add attr data-target to popover triggers + $(popoverTrigger).attr('data-target', config.idPopover+index); + var popoverTarget = $(popoverTrigger).data('target'); + + // unbind + $(popoverTrigger).off(trigger); + + $(popoverTrigger).on(trigger, function(event) { + event.preventDefault(); + event.stopPropagation(); + + if ($(popoverTarget).hasClass('ls-active')) { + hide(popoverTarget); + } else { + if (!$(config.idPopover+index).length) { + buildPopover(index, popoverTrigger); + } + + show(popoverTarget); + clickAnywhereClose(popoverTarget) + } + + if (trigger === 'mouseover') { + $(popoverTrigger).on('mouseout', function() { + hide(popoverTarget); + }); + } + + // Define position of popovers based on his triggers + setPosition(popoverTrigger); + }); + + $(window).on('breakpoint-updated', function(){ + setPosition(popoverTrigger); + }); + + + // When page load popover has to open + if($(this).attr('data-ls-popover') === 'open') { + var target = $(this).data('target'); + + buildPopover(index, popoverTrigger); + show(popoverTarget); + setPosition(popoverTrigger); + } + }); + + } + + // If popover was not created, we build the HTML using a template + function buildPopover(index, popoverTrigger) { + var data = { + index : index, + title : $(popoverTrigger).data('title'), + content : $(popoverTrigger).data('content'), + placement : $(popoverTrigger).data('placement'), + customClasses: $(popoverTrigger).data('custom-class') + } + + $('body').append(locastyle.templates.popover(data)); + + } + + // Define position of popovers + function setPosition(popoverTrigger) { + var data = { + target : $(popoverTrigger).data('target'), + top : $(popoverTrigger).offset().top, + left : $(popoverTrigger).offset().left, + width : $(popoverTrigger).outerWidth(), + height : $(popoverTrigger).outerHeight(), + placement : $(popoverTrigger).data('placement') + } + + // Define the position of popovers and your elements triggers + switch (data.placement) { + case 'right': + $(data.target).css({ + top : data.top += (data.height/2 -2), + left: data.left += (data.width + 12) + }); + break; + case 'bottom': + $(data.target).css({ + top : data.top += (data.height + 12), + left: data.left += (data.width/2) + }); + break; + case 'left': + $(data.target).css({ + top : data.top += (data.height/2 -2 ), + left: data.left -= 12 + }); + break; + default: + case 'top': + $(data.target).css({ + top : data.top -= 12, + left: data.left += (data.width/2) + }); + + } + + } + + // Show called popover + function show(target) { + $(target).addClass('ls-active'); + $(target).off(config.events.closed).trigger(config.events.opened); + } + + // Hide all or visible popovers + function hide(target) { + $(target || '.ls-popover.ls-active').removeClass('ls-active'); + $(target).trigger(config.events.closed).off(config.events.opened); + + if(!$('.ls-popover.ls-active').length) { + $(document).off(config.events.clickAnywhere); + } + + } + + // Destroy all created popovers + function destroy() { + $(config.popoverClass).remove(); + + // Unbind all events. + $.each(config.events, function(index, event) { + $(document).unbind(event); + }); + + $(document).trigger(config.events.destroyed); + } + + function clickAnywhereClose(target) { + $(document).on(config.events.clickAnywhere, function(event){ + if(!$(event.target).parents('.ls-popover').length){ + hide(target); + } + }); + } + + return { + init : init, + show : show, + hide : hide, + destroy: destroy + }; + +}()); diff --git a/pool/shard001/JavaScript/0006296_insertToMysql.js b/pool/shard001/JavaScript/0006296_insertToMysql.js new file mode 100644 index 0000000000000000000000000000000000000000..b9a9ff822124f03152018251dd80fe9fb38bba8b --- /dev/null +++ b/pool/shard001/JavaScript/0006296_insertToMysql.js @@ -0,0 +1,76 @@ +#!/usr/local/bin/node +/*** + * 解析信息到 mysql 数据库 + */ +let mysql = require('mysql') +const readline = require('readline') +const fs = require('fs') + +let con = mysql.createConnection({ + host: 'localhost', + user: 'root', + password: 'abcd' +}) + +con.querySync = async (sql) => { + return new Promise((resolve, reject) => { + con.query(sql, (err, result) => { + if (err) { + console.error(err) + return resolve(null, err) + } else { + return resolve(result) + } + }) + }) +} + +con.connectSync = async () => { + return new Promise((resolve, reject) => { + con.connect(err => { + if (err) { + return reject(err) + } else { + return resolve(err) + } + }) + }) +} + +async function run () { + await con.connectSync() + await con.querySync(`CREATE DATABASE IF NOT EXISTS mobile_area`) + await con.querySync(`USE mobile_area`) + await con.querySync(`CREATE TABLE IF NOT EXISTS mobile_area (phone VARCHAR(255), areanumber VARCHAR(255), areaname VARCHAR(255), note VARCHAR(255))`) + + // 插入数据 + const rl = readline.createInterface({ + input: fs.createReadStream('mobilearea.txt') + }) + let subSqls = [] + await new Promise((resolve, reject) => { + rl.on('line', async (line) => { + if (!line.includes('手机前缀')) { + const [phone, areanumber, areaname, note] = line.split('|') + const subSql = `(${phone}, ${areanumber}, '${areaname}', '${note}')` + subSqls.push(subSql) + } + }) + rl.on('close', async () => { + resolve() + }) + }) + + // 不要放在 rl.on 中 + let chunk = 2000 + for (let i = 0, j = subSqls.length; i < j; i += chunk) { + const sql = `INSERT INTO mobile_area.mobile_area (phone, areanumber, areaname, note) VALUES ${subSqls.slice(i, i + chunk).join(',')}` + await con.querySync(sql) + } + process.exit(1) +} +try { + run() +} catch (err) { + console.error(err) +} diff --git a/pool/shard001/JavaScript/0006298_BinTree.js b/pool/shard001/JavaScript/0006298_BinTree.js new file mode 100644 index 0000000000000000000000000000000000000000..92edd2fff75db6e2ff0349e9b59eed5fbbda5f6b --- /dev/null +++ b/pool/shard001/JavaScript/0006298_BinTree.js @@ -0,0 +1,266 @@ +//BinTree.js +//Stophin +//20160417 + +function BinNode(role) +{ + this.role = role; + this.value = role.uniqueID; + + this.left = null; + this.right = null; + this.parent = null; + + this.color = RB_Color.Black; + + BinNode.prototype.uncle = function() + { + if (this.parent == this.grandPa().left) + { + return this.grandPa().right; + } + return this.grandPa().left; + } + BinNode.prototype.grandPa = function() + { + return this.parent.parent; + } +} + +function BinTree() +{ + this.header = null; + + BinTree.prototype.insertNode = function(role) + { + var node = new BinNode(role); + var target_pos = this.header; + + var parent = null; + var be_in_left = 1; + + while(target_pos) + { + parent = target_pos; + if (this.compare(node, target_pos)) // Insert into right tree + { + target_pos = target_pos.right; + be_in_left = 0; + } + else // Inser into left tree + { + target_pos = target_pos.left; + be_in_left = 1 + } + } + + node.parent = parent; + if (parent) + { + if (be_in_left) + { + parent.left = node; + } + else + { + parent.right = node; + } + } + else + { + this.header = node; + } + + this.adjustPath(node); + } + + BinTree.prototype.getRole = function(key) + { + var temp = this.getNode(key); + if (temp) + { + return temp.role; + } + return null; + } + + BinTree.prototype.getNode = function(key) + { + return this.traverse(this.header, key); + } + + BinTree.prototype.traverse = function(node, key) + { + if (!node) + { + return null; + } + if (node.value == key) + { + return node; + } + if (key > node.value) + { + return this.traverse(node.right, key); + } + else + { + return this.traverse(node.left, key); + } + } + + BinTree.prototype.compare = function(l, r) + { + if (parseInt(l.value) > parseInt(r.value)) + { + return 1; + } + return 0; + } + BinTree.prototype.adjustPath = function(node) + { + var w = null; + while(node != this.header && node.parent.color == RB_Color.Red) + { + // Left tree + if (node.parent == node.grandPa().left) + { + w = node.uncle(); + // If uncle is red then put unclue and paren to black + // and grandpa to red, if grandpa's parent might be + // red, which need to be adjusted later + if (w != null && red == w.color) + { + w.color = RB_Color.Black; + node.parent.color = RB_Color.Black; + node.grandPa().color = RB_Color.Red; + node = node.grandPa(); + } + else + { + // Right tree + if (node == node.parent.right) + { + node = node.parent; + this.rotate_left(node); + } + + node.parent.color = RB_Color.Black; + node.grandPa().color = RB_Color.Red; + + this.rotate_right(node.grandPa()); + } + } + // Right tree + else + { + w = node.uncle(); + + // If uncle is red then put unclue and paren to black + // and grandpa to red, if grandpa's parent might be + // red, which need to be adjusted later + if (w != null && red == w.color) + { + w.color = RB_Color.Black; + node.parent.color = RB_Color.Black; + node.grandPa().color = RB_Color.Red; + node = node.grandPa(); + } + else + { + // Right tree + if (node == node.parent.left) + { + node = node.parent; + this.rotate_right(node); + } + + node.parent.color = RB_Color.Black; + node.grandPa().color = RB_Color.Red; + + this.rotate_left(node.grandPa()); + } + } + } + + this.header.color = RB_Color.Black; + } + + BinTree.prototype.rotate_left = function(node) + { + var parent = node.parent; + var right = node.right; + + var rleft = right.left; + + // Put node as right tree's left tree, + // and right tree's left tree as node's right tree + right.left = node; + node.parent = right; + node.right = rleft; + + // Replace node with right tree + if (parent != null) + { + // If it's original left tree + if (node == parent.left) + { + parent.left = right; + } + else + { + parent.right = right; + } + } + right.parent = parent; + + // Put right tree's original left tree into the root + if (rleft) + { + rleft.parent = node; + } + if (parent == null) + { + this.header = right; + } + } + + BinTree.prototype.rotate_right = function(node) + { + var parent = node.parent; + var left = node.left; + + var lrigt = left.right; + + // Put node as left tree's right tree + left.right = node; + node.parent = left; + node.left = lrigt; + + // Replace node with left tree + if (parent != null) + { + // If it's original left tree + if (node == parent.left) + { + parent.left = left; + } + else + { + parent.right = left; + } + } + left.parent = parent; + + // Put left tree's original right tree into the root + if (lrigt) + { + lrigt.parent = node; + } + if (parent == null) + { + this.header = left; + } + } + +} \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006301_socketService.js b/pool/shard001/JavaScript/0006301_socketService.js new file mode 100644 index 0000000000000000000000000000000000000000..861107de19a29bcc3838479abc7e56c11385529a --- /dev/null +++ b/pool/shard001/JavaScript/0006301_socketService.js @@ -0,0 +1,41 @@ +/** + * Created by Peter on 9-8-2015. + */ +(function() { + ngApp.factory('socketService', [function () { + var socket = io("http://"+window.location.hostname+":3100"); + socket.on('fn', function (body) { + var fnName = body.fn; + if (typeof myStore.fns[fnName] == 'function') { + myStore.fns[fnName](body.parameters); + } + }); + var myStore = { + fns: { + // The update contains the new definition of an entity + updateModel: function (update) { + myStore.model[update.type] = update.model; + }, + // Data updates come in the form of an identifier and a payload. + updateData: function (update) { + if(myStore.data[update.id].loadProperties) + myStore.data[update.id].loadProperties(update.payload); + else + myStore.data[update.id] = update.payload; + } + }, + model: {}, + data: {} + }; + var outgoingMsgId = 0; + socket.updateData = function (update) { + socket.emit("fn", {fn: "updateData", msgId: outgoingMsgId++, parameters: update}); + }; + socket.findEntity = function (id) { + socket.emit("fn", {fn: "findEntity", parameters: id}); + }; + socket.data = myStore.data; + + return socket; + }]); +})(); diff --git a/pool/shard001/JavaScript/0006303_jquery.dataTables.bootstrap.js b/pool/shard001/JavaScript/0006303_jquery.dataTables.bootstrap.js new file mode 100644 index 0000000000000000000000000000000000000000..2bcff05917fdbbb11e47809ddad7189a9bc474ed --- /dev/null +++ b/pool/shard001/JavaScript/0006303_jquery.dataTables.bootstrap.js @@ -0,0 +1,254 @@ + +/* Set the defaults for DataTables initialisation */ +$.extend( true, $.fn.dataTable.defaults, { + "sDom": + "<'row'<'col-xs-6'l><'col-xs-6'f>r>"+ + "t"+ + "<'row'<'col-xs-6'i><'col-xs-6'p>>", + "oLanguage": { + "sLengthMenu": "_MENU_ records per page" + } +} ); + + +/* Default class modification */ +$.extend( $.fn.dataTableExt.oStdClasses, { + "sWrapper": "dataTables_wrapper form-inline", + "sFilterInput": "form-control input-sm", + "sLengthSelect": "form-control input-sm" +} ); + +// In 1.10 we use the pagination renderers to draw the Bootstrap paging, +// rather than custom plug-in +if ( $.fn.dataTable.Api ) { + $.fn.dataTable.defaults.renderer = 'bootstrap'; + + $.fn.dataTable.ext.renderer.pageButton.bootstrap = function ( settings, host, idx, buttons, page, pages ) { + var api = new $.fn.dataTable.Api( settings ); + var classes = settings.oClasses; + var lang = settings.oLanguage.oPaginate; + var btnDisplay, btnClass; + + var attach = function( container, buttons ) { + var i, ien, node, button; + var clickHandler = function ( e ) { + e.preventDefault(); + if ( e.data.action !== 'ellipsis' ) { + api.page( e.data.action ).draw( false ); + } + }; + + for ( i=0, ien=buttons.length ; i 0 ? + '' : ' disabled'); + break; + + case 'previous': + btnDisplay = lang.sPrevious; + btnClass = button + (page > 0 ? + '' : ' disabled'); + break; + + case 'next': + btnDisplay = lang.sNext; + btnClass = button + (page < pages-1 ? + '' : ' disabled'); + break; + + case 'last': + btnDisplay = lang.sLast; + btnClass = button + (page < pages-1 ? + '' : ' disabled'); + break; + + default: + btnDisplay = button + 1; + btnClass = page === button ? + 'active' : ''; + break; + } + + if ( btnDisplay ) { + node = $('
  • ', { + 'class': classes.sPageButton+' '+btnClass, + 'aria-controls': settings.sTableId, + 'tabindex': settings.iTabIndex, + 'id': idx === 0 && typeof button === 'string' ? + settings.sTableId +'_'+ button : + null + } ) + .append( $('', { + 'href': '#' + } ) + .html( btnDisplay ) + ) + .appendTo( container ); + + settings.oApi._fnBindAction( + node, {action: button}, clickHandler + ); + } + } + } + }; + + attach( + $(host).empty().html('
      ').children('ul'), + buttons + ); + } +} +else { + // Integration for 1.9- + $.fn.dataTable.defaults.sPaginationType = 'bootstrap'; + + /* API method to get paging information */ + $.fn.dataTableExt.oApi.fnPagingInfo = function ( oSettings ) + { + return { + "iStart": oSettings._iDisplayStart, + "iEnd": oSettings.fnDisplayEnd(), + "iLength": oSettings._iDisplayLength, + "iTotal": oSettings.fnRecordsTotal(), + "iFilteredTotal": oSettings.fnRecordsDisplay(), + "iPage": oSettings._iDisplayLength === -1 ? + 0 : Math.ceil( oSettings._iDisplayStart / oSettings._iDisplayLength ), + "iTotalPages": oSettings._iDisplayLength === -1 ? + 0 : Math.ceil( oSettings.fnRecordsDisplay() / oSettings._iDisplayLength ) + }; + }; + + /* Bootstrap style pagination control */ + $.extend( $.fn.dataTableExt.oPagination, { + "bootstrap": { + "fnInit": function( oSettings, nPaging, fnDraw ) { + var oLang = oSettings.oLanguage.oPaginate; + var fnClickHandler = function ( e ) { + e.preventDefault(); + if ( oSettings.oApi._fnPageChange(oSettings, e.data.action) ) { + fnDraw( oSettings ); + } + }; + + $(nPaging).append( + '' + ); + var els = $('a', nPaging); + $(els[0]).bind( 'click.DT', { action: "previous" }, fnClickHandler ); + $(els[1]).bind( 'click.DT', { action: "next" }, fnClickHandler ); + }, + + + "fnUpdate": function ( oSettings, fnDraw ) { + var iListLength = 5; + var oPaging = oSettings.oInstance.fnPagingInfo(); + var an = oSettings.aanFeatures.p; + var i, ien, j, sClass, iStart, iEnd, iHalf=Math.floor(iListLength/2); + + if ( oPaging.iTotalPages < iListLength) { + iStart = 1; + iEnd = oPaging.iTotalPages; + } + else if ( oPaging.iPage <= iHalf ) { + iStart = 1; + iEnd = iListLength; + } else if ( oPaging.iPage >= (oPaging.iTotalPages-iHalf) ) { + iStart = oPaging.iTotalPages - iListLength + 1; + iEnd = oPaging.iTotalPages; + } else { + iStart = oPaging.iPage - iHalf + 1; + iEnd = iStart + iListLength - 1; + } + + for ( i=0, ien=an.length ; i'+j+'') + .insertBefore( $('li:last', an[i])[0] ) + .bind('click', function (e) { + e.preventDefault(); + oSettings._iDisplayStart = (parseInt($('a', this).text(),10)-1) * oPaging.iLength; + fnDraw( oSettings ); + } ); + } + + // Add / remove disabled classes from the static elements + if ( oPaging.iPage === 0 ) { + $('li:first', an[i]).addClass('disabled'); + } else { + $('li:first', an[i]).removeClass('disabled'); + } + + if ( oPaging.iPage === oPaging.iTotalPages-1 || oPaging.iTotalPages === 0 ) { + $('li:last', an[i]).addClass('disabled'); + } else { + $('li:last', an[i]).removeClass('disabled'); + } + } + } + } + } ); +} + + +/* + * TableTools Bootstrap compatibility + * Required TableTools 2.1+ + */ +if ( $.fn.DataTable.TableTools ) { + // Set the classes that TableTools uses to something suitable for Bootstrap + $.extend( true, $.fn.DataTable.TableTools.classes, { + "container": "DTTT btn-group", + "buttons": { + "normal": "btn btn-default", + "disabled": "disabled" + }, + "collection": { + "container": "DTTT_dropdown dropdown-menu", + "buttons": { + "normal": "", + "disabled": "disabled" + } + }, + "print": { + "info": "DTTT_print_info modal" + }, + "select": { + "row": "active" + } + } ); + + // Have the collection use a bootstrap compatible dropdown + $.extend( true, $.fn.DataTable.TableTools.DEFAULTS.oTags, { + "collection": { + "container": "ul", + "button": "li", + "liner": "a" + } + } ); +} + diff --git a/pool/shard001/JavaScript/0006304_surveys_variables_table.js b/pool/shard001/JavaScript/0006304_surveys_variables_table.js new file mode 100644 index 0000000000000000000000000000000000000000..5bc2be2794637f136e43ae5bc19548192edae51f --- /dev/null +++ b/pool/shard001/JavaScript/0006304_surveys_variables_table.js @@ -0,0 +1,163 @@ +var pag; +var variableDataTable; +var variableDataSource; + +function selectVisibleVariableCheckboxes(checked) { + var visible_records = pag.getPageRecords(); + var rs = variableDataTable.getRecordSet(); + for (var index=visible_records[0]; index < visible_records[1] + 1; index++) { + rs.getRecord(index).setData('Select',checked); + var id = rs.getRecord(index).getData().id; + selectVariable(id); + } + variableDataTable.render(); +} +function selectAllVariableCheckboxes(checked){ + var rs = variableDataTable.getRecordSet(); + len = rs.getLength(); + + for (var index=0; index < len; index++) { + rs.getRecord(index).setData('Select',checked); + var id = rs.getRecord(index).getData().id; + selectVariable(id); + } + variableDataTable.render(); +} +function invertAllVariableCheckboxes(){ + var rs = variableDataTable.getRecordSet(); + len = rs.getLength(); + + for (var index=0; index < len; index++) { + rs.getRecord(index).setData('Select',!rs.getRecord(index).getData('Select')); + var id = rs.getRecord(index).getData().id; + selectVariable(id); + } + variableDataTable.render(); +} + +function updateTable(data) { +variableDataSource.liveData = data; +variableDataTable.getDataSource().sendRequest(null, + {success: variableDataTable.onDataReturnInitializeTable}, + variableDataTable); +} + +function createTable(survey_id) { +YAHOO.util.Event.addListener(window, "load", function() { + YAHOO.example.Basic = function() { + var expansionFormatter = function(el, oRecord, oColumn, oData) { + var cell_element = el.parentNode; + + //Set trigger + if( oData ){ //Row is closed + YAHOO.util.Dom.addClass( cell_element, + "yui-dt-expandablerow-trigger" ); + } + + }; + var variablesURLFormatter = function(elLiner, oRecord, oColumn, oData) { + var id = oRecord.getData().id; + var name = oRecord.getData().name; + elLiner.innerHTML = "" + name + ""; + }; + var datasetsURLFormatter = function(elLiner, oRecord, oColumn, oData) { + var id = oRecord.getData().dataset_id; + var name = oRecord.getData().dataset; + elLiner.innerHTML = "" + name + ""; + }; + var surveysURLFormatter = function(elLiner, oRecord, oColumn, oData) { + var id = oRecord.getData().survey_id; + var name = oRecord.getData().survey; + elLiner.innerHTML = "" + name + ""; + }; + // Add the custom formatter to the shortcuts + YAHOO.widget.DataTable.Formatter.variableVariablesFormatter = variablesURLFormatter; + YAHOO.widget.DataTable.Formatter.variableDatasetsFormatter = datasetsURLFormatter; + YAHOO.widget.DataTable.Formatter.variableSurveysFormatter = surveysURLFormatter; + + var categoryURLFormatter = function(elLiner, oRecord, oColumn, oData) { + var category = oRecord.getData().category; + if (category != null && category != 'N/A') { + elLiner.innerHTML = "" + category + ""; + } else { + elLiner.innerHTML = "N/A"; + } + }; + // Add the custom formatter to the shortcuts + YAHOO.widget.DataTable.Formatter.categoryFormatter = categoryURLFormatter; + + var columnDefs = [ + { label: "", formatter: YAHOO.widget.VariableRowExpansionDataTable.formatRowExpansion}, + { key:"Select", label: "", formatter: "checkbox"}, + { key: "name", label: "Title", formatter:"variableVariablesFormatter", sortable: true, resizeable: true }, + { key: "description", label: "Description", sortable: true, width: 300, resizeable: true }, + { key: "category", label: "Category", formatter:"categoryFormatter", sortable: true, resizeable: true }, + //no point sorting for a single survey or showing the dataset + { key: "dataset", label: dataset, formatter:"variableDatasetsFormatter", sortable: false, resizeable: true }, + //{ key: "survey", label: survey, formatter:"variableSurveysFormatter", sortable: false, resizeable: true }, + { key: "year", label: "Year", sortable: true, resizeable: true }//, + //{ key: "popularity", label: "Popularity", sortable: true, resizeable: true } + ]; + //request which is sent to the server + var generateRequest = function(oState, oSelf) { + // Get states or use defaults + oState = oState || { pagination: null, sortedBy: null }; + var sort = (oState.sortedBy) ? oState.sortedBy.key : "name"; + var dir = (oState.sortedBy && oState.sortedBy.dir === YAHOO.widget.DataTable.CLASS_DESC) ? "desc" : "asc"; + var startIndex = (oState.pagination) ? oState.pagination.recordOffset : 0; + var results = (oState.pagination) ? oState.pagination.rowsPerPage : 20; + + // Build custom request + return "sort=" + sort + + "&dir=" + dir + + "&startIndex=" + startIndex + + "&results=" + (startIndex + results) + + "&id=" + survey_id; + }; + // DataTable configuration + var myConfigs = { + generateRequest: generateRequest, + initialRequest: generateRequest(), // Initial request for first page of data + dynamicData: true, // Enables dynamic server-driven data + sortedBy : {key:"name", dir:YAHOO.widget.DataTable.CLASS_ASC}, // Sets UI initial sort arrow + paginator: new YAHOO.widget.Paginator({ rowsPerPage:20 }), // Enables pagination + rowExpansionTemplate :'{id}', + draggableColumns:true + }; + + variableDataSource = new YAHOO.util.DataSource(survey_variables_url + "?"); + variableDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON; + variableDataSource.responseSchema = { + resultsList : "results", + fields: ["id","name","description","survey", "dataset","survey_id","dataset_id","category","popularity", "year"], + metaFields: { + totalRecords: "totalRecords", + startIndex: "startIndex" + } + }; +//to sort the vars add this to the table config sortedBy : { key: "name", dir: YAHOO.widget.DataTable.CLASS_ASC }, + //pag = new YAHOO.widget.Paginator({rowsPerPage: 50, totalRecords: results.total_entries}); + variableDataTable = new YAHOO.widget.VariableRowExpansionDataTable("variables_table", + columnDefs, variableDataSource, myConfigs); + variableDataTable.subscribe( 'cellClickEvent', variableDataTable.onEventToggleRowExpansion ); + variableDataTable.doBeforeLoadData = function(oRequest, oResponse, oPayload) { + oPayload.totalRecords = oResponse.meta.totalRecords; + oPayload.pagination.recordOffset = oResponse.meta.startIndex; + return oPayload; + }; + return { + oDS: variableDataSource, + oDT: variableDataTable + }; + }(); + variableDataTable.subscribe("checkboxClickEvent", function(oArgs){ + var elCheckbox = oArgs.target; + var newValue = elCheckbox.checked; + var record = variableDataTable.getRecord(elCheckbox); + var column = variableDataTable.getColumn(elCheckbox); + record.setData(column.key,newValue); + var id = record.getData().id; + selectVariable(id); + }); +}); +} diff --git a/pool/shard001/JavaScript/0006309_index.js b/pool/shard001/JavaScript/0006309_index.js new file mode 100644 index 0000000000000000000000000000000000000000..0c4ce706daaf255dc037ba0a3facdcb956ed6e51 --- /dev/null +++ b/pool/shard001/JavaScript/0006309_index.js @@ -0,0 +1,43 @@ +/* eslint no-param-reassign: "off" */ + +import React from 'react'; +import _ from 'lodash'; +import defaultConfig from './config'; + +export default { + + defaults: { + dialog: defaultConfig + }, + + load: function(lore) { + const { + muiTheme, + domElementId, + buildDialogContainer, + renderDialogToDom + } = lore.config.dialog; + + if (!muiTheme) { + throw new Error('Must provide muiTheme in config/dialog.js in order to use lore-hook-dialog-material-ui'); + } + + lore.dialog = {}; + + lore.dialog.show = function(component, options = {}) { + const dialog = _.isFunction(component) ? component() : component; + + if (!dialog) { + throw new Error('Must provide a component to lore.dialog.show'); + } + + const DialogContainer = buildDialogContainer(lore, options); + + // Find the proper DOM element and mount the dialog to it + renderDialogToDom(options.domElementId || domElementId, ( + + )); + } + } + +}; diff --git a/pool/shard001/JavaScript/0006311_sass.js b/pool/shard001/JavaScript/0006311_sass.js new file mode 100644 index 0000000000000000000000000000000000000000..8368cd91bdbc7cf53c9e854c07872ff62b8eeb4d --- /dev/null +++ b/pool/shard001/JavaScript/0006311_sass.js @@ -0,0 +1,100 @@ +/* + * grunt-contrib-sass + * http://gruntjs.com/ + * + * Copyright (c) 2013 Sindre Sorhus, contributors + * Licensed under the MIT license. + */ +'use strict'; + +module.exports = function (grunt) { + var path = require('path'); + var dargs = require('dargs'); + var numCPUs = require('os').cpus().length; + + var bannerCallback = function (filename, banner) { + var content; + grunt.log.verbose.writeln('Writing CSS banner for ' + filename); + + content = grunt.file.read(filename); + grunt.file.write(filename, banner + grunt.util.linefeed + content); + }; + + grunt.registerMultiTask('sass', 'Compile Sass to CSS', function () { + var cb = this.async(); + var options = this.options(); + var passedArgs; + var bundleExec; + var banner; + + // Unset banner option if set + if (options.banner) { + banner = options.banner; + delete options.banner; + } + + passedArgs = dargs(options, ['bundleExec']); + bundleExec = options.bundleExec; + + grunt.verbose.writeflags(options, 'Options'); + + grunt.util.async.forEachLimit(this.files, numCPUs, function (file, next) { + var src = file.src[0]; + if (typeof src !== 'string') { + src = file.orig.src[0]; + } + + if (!grunt.file.exists(src)) { + grunt.log.warn('Source file "' + src + '" not found.'); + return next(); + } + + var args = [ + src, + file.dest, + '--load-path', path.dirname(src) + ].concat(passedArgs); + + if (process.platform === 'win32') { + args.unshift('sass.bat'); + } else { + args.unshift('sass'); + } + + if (bundleExec) { + args.unshift('bundle', 'exec'); + } + + // If we're compiling scss or css files + if (path.extname(src) === '.css') { + args.push('--scss'); + } + + // Make sure grunt creates the destination folders + grunt.file.write(file.dest, ''); + + grunt.util.spawn({ + cmd: args.shift(), + args: args, + opts: { + stdio: 'inherit' + } + }, function (error, result, code) { + if (code === 127) { + return grunt.warn( + 'You need to have Ruby and Sass installed and in your PATH for\n' + + 'this task to work. More info:\n' + + 'https://github.com/gruntjs/grunt-contrib-sass' + ); + } + + // Callback to insert banner + if (banner) { + bannerCallback(file.dest, banner); + } + + next(error); + }); + }, cb); + }); +}; diff --git a/pool/shard001/JavaScript/0006312_plugin.dev.js b/pool/shard001/JavaScript/0006312_plugin.dev.js new file mode 100644 index 0000000000000000000000000000000000000000..8f5d69b786eb11781048d4a467eca048873a4921 --- /dev/null +++ b/pool/shard001/JavaScript/0006312_plugin.dev.js @@ -0,0 +1,119 @@ +/** + * Inline development version. Only to be used while developing since it uses document.write to load scripts. + */ + +/*jshint smarttabs:true, undef:true, latedef:true, curly:true, bitwise:true, camelcase:true */ +/*globals $code */ + +(function(exports) { + "use strict"; + + var html = "", baseDir; + var modules = {}, exposedModules = [], moduleCount = 0; + + var scripts = document.getElementsByTagName('script'); + for (var i = 0; i < scripts.length; i++) { + var src = scripts[i].src; + + if (src.indexOf('/plugin.dev.js') != -1) { + baseDir = src.substring(0, src.lastIndexOf('/')); + } + } + + function require(ids, callback) { + var module, defs = []; + + for (var i = 0; i < ids.length; ++i) { + module = modules[ids[i]] || resolve(ids[i]); + if (!module) { + throw 'module definition dependecy not found: ' + ids[i]; + } + + defs.push(module); + } + + callback.apply(null, defs); + } + + function resolve(id) { + var target = exports; + var fragments = id.split(/[.\/]/); + + for (var fi = 0; fi < fragments.length; ++fi) { + if (!target[fragments[fi]]) { + return; + } + + target = target[fragments[fi]]; + } + + return target; + } + + function register(id) { + var target = exports; + var fragments = id.split(/[.\/]/); + + for (var fi = 0; fi < fragments.length - 1; ++fi) { + if (target[fragments[fi]] === undefined) { + target[fragments[fi]] = {}; + } + + target = target[fragments[fi]]; + } + + target[fragments[fragments.length - 1]] = modules[id]; + } + + function define(id, dependencies, definition) { + if (typeof id !== 'string') { + throw 'invalid module definition, module id must be defined and be a string'; + } + + if (dependencies === undefined) { + throw 'invalid module definition, dependencies must be specified'; + } + + if (definition === undefined) { + throw 'invalid module definition, definition function must be specified'; + } + + require(dependencies, function() { + modules[id] = definition.apply(null, arguments); + }); + + if (--moduleCount === 0) { + for (var i = 0; i < exposedModules.length; i++) { + register(exposedModules[i]); + } + } + } + + function expose(ids) { + exposedModules = ids; + } + + function writeScripts() { + document.write(html); + } + + function load(path) { + html += '\n'; + moduleCount++; + } + + // Expose globally + exports.define = define; + exports.require = require; + + expose(["tinymce/tableplugin/TableGrid","tinymce/tableplugin/Quirks","tinymce/tableplugin/CellSelection","tinymce/tableplugin/Plugin"]); + + load('classes/TableGrid.js'); + load('classes/Quirks.js'); + load('classes/CellSelection.js'); + load('classes/Plugin.js'); + + writeScripts(); +})(this); + +// $hash: d0716e6a484e7ffb243be87c5dec6c7f \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006315_app.js b/pool/shard001/JavaScript/0006315_app.js new file mode 100644 index 0000000000000000000000000000000000000000..f8b14f4d6518b94764b8b5df68002cdc51c392f9 --- /dev/null +++ b/pool/shard001/JavaScript/0006315_app.js @@ -0,0 +1,93 @@ +(function($) { + + "use strict"; + var day=new Date(); + var m=day.getMonth()+1; + var d=day.getDate(); + var y=day.getFullYear(); + var today=y+"-"+m+"-"+d; + console.log(today); + + var options = { + events_source: 'events.json.php', + view: 'month', + tmpl_path: 'tmpls/', + tmpl_cache: false, + day: today, + onAfterEventsLoad: function(events) { + if(!events) { + return; + } + var list = $('#eventlist'); + list.html(''); + + $.each(events, function(key, val) { + $(document.createElement('li')) + .html('' + val.title + '') + .appendTo(list); + }); + }, + onAfterViewLoad: function(view) { + $('.page-header h3').text(this.getTitle()); + $('.btn-group button').removeClass('active'); + $('button[data-calendar-view="' + view + '"]').addClass('active'); + }, + classes: { + months: { + general: 'label' + } + } + }; + + var calendar = $('#calendar').calendar(options); + + $('.btn-group button[data-calendar-nav]').each(function() { + var $this = $(this); + $this.click(function() { + calendar.navigate($this.data('calendar-nav')); + }); + }); + + $('.btn-group button[data-calendar-view]').each(function() { + var $this = $(this); + $this.click(function() { + calendar.view($this.data('calendar-view')); + }); + }); + + $('#first_day').change(function(){ + var value = $(this).val(); + value = value.length ? parseInt(value) : null; + calendar.setOptions({first_day: value}); + calendar.view(); + }); + + $('#language').change(function(){ + calendar.setLanguage($(this).val()); + calendar.view(); + }); + + $('#events-in-modal').change(function(){ + var val = $(this).is(':checked') ? $(this).val() : null; + calendar.setOptions({modal: val}); + }); + $('#format-12-hours').change(function(){ + var val = $(this).is(':checked') ? true : false; + calendar.setOptions({format12: val}); + calendar.view(); + }); + $('#show_wbn').change(function(){ + var val = $(this).is(':checked') ? true : false; + calendar.setOptions({display_week_numbers: val}); + calendar.view(); + }); + $('#show_wb').change(function(){ + var val = $(this).is(':checked') ? true : false; + calendar.setOptions({weekbox: val}); + calendar.view(); + }); + $('#events-modal .modal-header, #events-modal .modal-footer').click(function(e){ + //e.preventDefault(); + //e.stopPropagation(); + }); +}(jQuery)); diff --git a/pool/shard001/JavaScript/0006316_sequence.spec.js b/pool/shard001/JavaScript/0006316_sequence.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..af9717060742be3e3dd1d057c8a7c2492b608702 --- /dev/null +++ b/pool/shard001/JavaScript/0006316_sequence.spec.js @@ -0,0 +1,108 @@ +/** + * Created by knut on 14-11-18. + */ +var sq = require('./parser/sequence').parser; + +//console.log(sq.parse('a12:d12\na24:d24')); + +str = 'a12:d12\n\na24:d24'; +//console.log(str); +//console.log(sq.parse(str)); +//console.log(sq.parse('[]\n[]')); + +str = 'bfs:queue\n\nbfs3:queue\n'; +str = str + 'bfs:message=someNode.setLevel\n'; +str = str + 'bfs:message2=someNode.setLevel2'; +//console.log(str); +//console.log(sq.parse(str)); + +str = 'bfs:BFS\n'; +str = str + 'someNode:SomeNode\n'; +str = str + 'bfs:queue.new\n'; +str = str + 'bfs:someNode.setLevel'; +//console.log(str); +//console.log(sq.parse(str)); + + +describe('when parsing a sequence it',function() { + var parseError; + beforeEach(function () { + sq = require('./parser/sequence').parser; + sq.yy = require('./sequenceDb'); + sq.yy.clear(); + parseError = function(err, hash) { + console.log('Syntax error:' + err); + }; + sq.yy.parseError = parseError; + }); + + it('should handle a sequence defintion', function () { + str = 'sequence TB\nbfs1:queue'; + + sq.parse(str); + var actors = sq.yy.getActors(); + actors.bfs1.description = 'queue'; + }); + + it('should handle an actor', function () { + str = 'sequence TB\nbfs1:queue'; + + sq.parse(str); + var actors = sq.yy.getActors(); + actors.bfs1.description = 'queue'; + }); + + it('should handle an actor with space in its description', function () { + str = 'sequence TB\nbfs1:The queue\n'; + + sq.parse(str); + var actors = sq.yy.getActors(); + actors.bfs1.description = 'queue'; + }); + + it('should handle a statement ending with a newline', function () { + str = 'sequence TB\nbfs1:queue\n'; + + sq.parse(str); + var actors = sq.yy.getActors(); + actors.bfs1.description = 'queue'; + }); + + xit('should handle a errors', function () { + str = 'sequence TB\nbfs1!!!!queue\n'; + + spyOn('sq.yy',parseError); + sq.parse(str); + + //expect(sq.yy.parseError).toHaveBeenCalled(); + }); + + it('should handle multiple actors', function () { + str = 'sequence TB\nbfs1:queue\n\nbfs2:queue'; + + sq.parse(str); + var actors = sq.yy.getActors(); + actors.bfs1.description = 'queue'; + actors.bfs2.description = 'queue'; + }); + + it('should handle a message with response', function () { + str = 'sequence TB\nbfs1:queue\n\nbfs2:queue\n'; + str = str + 'bfs1:message=bfs2.setLevel(0)'; + //console.log(str); + sq.parse(str); + var messages = sq.yy.getMessages(); + expect(messages.length).toBe(1); + expect(messages[0].from).toBe('bfs1'); + }); + + it('should handle a message with no response', function () { + str = 'sequence TB\nbfs1:queue\n\nbfs2:queue\n'; + str = str + 'bfs1:bfs2.start'; + //console.log(str); + sq.parse(str); + var messages = sq.yy.getMessages(); + expect(messages.length).toBe(1); + expect(messages[0].from).toBe('bfs1'); + }); +}); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006317_index.js b/pool/shard001/JavaScript/0006317_index.js new file mode 100644 index 0000000000000000000000000000000000000000..5c040a46c4932bd659f865cda7cdcab8c7959612 --- /dev/null +++ b/pool/shard001/JavaScript/0006317_index.js @@ -0,0 +1,54 @@ +import React, { Component } from 'react'; +import { Text, View, ScrollView, Image, TouchableHighlight } from 'react-native'; +import { Theme } from '../../theme'; +import { Loader } from '../Loader'; + +export default class Results extends Component { + constructor(props) { + super(props); + this.state = { + loading: true + } + } + + componentDidMount() { + setTimeout(()=>{ + this.setState({loading: false}); + }, 2000); + } + + render() { + let finalValue = this.props.value; + let results = this.props.results; + let character = ""; + for(var name in results) { + if(results[name] <= finalValue) { + character = name; + } + } + //TODO: Maybe return an image of the character? + return ( + + + { this.state.loading ? + + + + : + + + YOU ARE: {character} + + + + {this.props.navigator.popToTop()}} style={Theme.button}> + START OVER + + + + } + + + ); + } +} diff --git a/pool/shard001/JavaScript/0006319_Random.js b/pool/shard001/JavaScript/0006319_Random.js new file mode 100644 index 0000000000000000000000000000000000000000..a15ad0d618d11116df705881de7ae15fe331da27 --- /dev/null +++ b/pool/shard001/JavaScript/0006319_Random.js @@ -0,0 +1,34 @@ +/** + * @author Richard Davey + * @copyright 2018 Photon Storm Ltd. + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} + */ + +var Point = require('../point/Point'); + +/** + * Returns a random point on a given Line. + * + * @function Phaser.Geom.Line.Random + * @since 3.0.0 + * + * @generic {Phaser.Geom.Point} O - [out,$return] + * + * @param {Phaser.Geom.Line} line - The Line to calculate the random Point on. + * @param {(Phaser.Geom.Point|object)} [out] - An instance of a Point to be modified. + * + * @return {(Phaser.Geom.Point|object)} A random Point on the Line. + */ +var Random = function (line, out) +{ + if (out === undefined) { out = new Point(); } + + var t = Math.random(); + + out.x = line.x1 + t * (line.x2 - line.x1); + out.y = line.y1 + t * (line.y2 - line.y1); + + return out; +}; + +module.exports = Random; diff --git a/pool/shard001/JavaScript/0006324_custom.js b/pool/shard001/JavaScript/0006324_custom.js new file mode 100644 index 0000000000000000000000000000000000000000..1d7f7713254456125c2d03f50b0a2d3615525fce --- /dev/null +++ b/pool/shard001/JavaScript/0006324_custom.js @@ -0,0 +1,66 @@ +/** + * Created by sanjeevbudha on 6/18/16. + */ + +function displayMessage(message,messageType){ + noty({ + layout: 'topRight', + text: message, + type: messageType, + timeout: 3000 + }); +} + +function customReloadWindow(delayTime){ + setTimeout( + function() + { + window.location.reload() + + }, delayTime); +} + + +function displayLoginMessage(message,messageType){ + noty({ + layout:'topCenter', + text:message, + type:messageType, + timeout:3000 + }) +} + +function checkDuplicate(input_id,controller,span_id) { + + var input_text = document.getElementById(input_id).value; + + var mode ='check'; + + $.ajax({ + type:"POST", + url:'../controller/'+controller, + data:"mode="+mode+"&input_txt="+input_text, + success:function(data){ + + var data = JSON.parse(data); + + + if(data.message == 'success'){ + document.getElementById(span_id).style.display = 'block'; + document.getElementById(span_id).style.color = 'red'; + + $('button[type=submit]').attr('disabled','disabled'); + } + else { + document.getElementById(span_id).style.display = 'none'; + $('button[type=submit]').removeAttr('disabled'); + + } + + },error: function (er) { + alert("Error while Creating" +er); + } + }); + + return false; +} \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006328_foundation.core.js b/pool/shard001/JavaScript/0006328_foundation.core.js new file mode 100644 index 0000000000000000000000000000000000000000..6aeb9dad0d33c2b921cb7d6aa75fbc86cb387fd4 --- /dev/null +++ b/pool/shard001/JavaScript/0006328_foundation.core.js @@ -0,0 +1,163 @@ +(function() { + 'use strict'; + + angular.module('foundation.core', [ + 'foundation.core.animation' + ]) + .service('FoundationApi', FoundationApi) + .service('FoundationAdapter', FoundationAdapter) + .factory('Utils', Utils) + ; + + FoundationApi.$inject = ['FoundationAnimation']; + + function FoundationApi(FoundationAnimation) { + var listeners = {}; + var settings = {}; + var uniqueIds = []; + var service = {}; + + service.subscribe = subscribe; + service.unsubscribe = unsubscribe; + service.publish = publish; + service.getSettings = getSettings; + service.modifySettings = modifySettings; + service.generateUuid = generateUuid; + service.toggleAnimate = toggleAnimate; + service.closeActiveElements = closeActiveElements; + service.animate = animate; + + return service; + + function subscribe(name, callback) { + if (!listeners[name]) { + listeners[name] = []; + } + + listeners[name].push(callback); + return true; + } + + function unsubscribe(name, callback) { + if (listeners[name] !== undefined) { + delete listeners[name]; + } + if (typeof callback == 'function') { + callback.call(this); + } + } + + function publish(name, msg) { + if (!listeners[name]) { + listeners[name] = []; + } + + listeners[name].forEach(function(cb) { + cb(msg); + }); + + return; + } + + function getSettings() { + return settings; + } + + function modifySettings(tree) { + settings = angular.extend(settings, tree); + return settings; + } + + function generateUuid() { + var uuid = ''; + + //little trick to produce semi-random IDs + do { + uuid += 'zf-uuid-'; + for (var i=0; i<15; i++) { + uuid += Math.floor(Math.random()*16).toString(16); + } + } while(!uniqueIds.indexOf(uuid)); + + uniqueIds.push(uuid); + return uuid; + } + + function toggleAnimate(element, futureState) { + FoundationAnimation.toggleAnimate(element, futureState); + } + + function closeActiveElements(options) { + var self = this; + options = options || {}; + var activeElements = document.querySelectorAll('.is-active[zf-closable]'); + // action sheets are nested zf-closable elements, so we have to target the parent + var nestedActiveElements = document.querySelectorAll('[zf-closable] > .is-active') + + if (activeElements.length) { + angular.forEach(activeElements, function(el) { + if (options.exclude !== el.id) { + self.publish(el.id, 'close'); + } + }); + } + if (nestedActiveElements.length) { + angular.forEach(nestedActiveElements, function(el) { + var parentId = el.parentNode.id; + if (options.exclude !== parentId) { + self.publish(parentId, 'close'); + } + }) + } + } + + function animate(element, futureState, animationIn, animationOut) { + FoundationAnimation.animate(element, futureState, animationIn, animationOut); + } + } + + FoundationAdapter.$inject = ['FoundationApi']; + + function FoundationAdapter(foundationApi) { + + var service = {}; + + service.activate = activate; + service.deactivate = deactivate; + + return service; + + function activate(target) { + foundationApi.publish(target, 'show'); + } + + function deactivate(target) { + foundationApi.publish(target, 'hide'); + } + } + + + function Utils() { + var utils = {}; + + utils.throttle = throttleUtil; + + return utils; + + function throttleUtil(func, delay) { + var timer = null; + + return function () { + var context = this, args = arguments; + + if (timer === null) { + timer = setTimeout(function () { + func.apply(context, args); + timer = null; + }, delay); + } + }; + } + } + +})(); diff --git a/pool/shard001/JavaScript/0006329_can.list.sort.js b/pool/shard001/JavaScript/0006329_can.list.sort.js new file mode 100644 index 0000000000000000000000000000000000000000..789fb350a23b1e08e83f8bf227822b18dca302af --- /dev/null +++ b/pool/shard001/JavaScript/0006329_can.list.sort.js @@ -0,0 +1,146 @@ +/*! + * CanJS - 2.0.4 + * http://canjs.us/ + * Copyright (c) 2013 Bitovi + * Mon, 23 Dec 2013 19:49:29 GMT + * Licensed MIT + * Includes: can/map/sort + * Download from: http://canjs.com + */ +(function(can) { + + var proto = can.List.prototype, + _changes = proto._changes, + setup = proto.setup; + + // extend the list for sorting support + can.extend(proto, { + comparator: undefined, + sortIndexes: [], + + + sortedIndex: function(item) { + var itemCompare = item.attr(this.comparator), + equaled = 0, + i; + + for (var i = 0, length = this.length; i < length; i++) { + if (item === this[i]) { + equaled = -1; + continue; + } + + if (itemCompare <= this[i].attr(this.comparator)) { + return i + equaled; + } + } + + return i + equaled; + }, + + + sort: function(method, silent) { + var comparator = this.comparator, + args = comparator ? [ + function(a, b) { + a = (typeof a[comparator] === 'function') ? a[comparator]() : a[comparator]; + b = (typeof b[comparator] === 'function') ? b[comparator]() : b[comparator]; + return a === b ? 0 : (a < b ? -1 : 1); + } + ] : [method], + res = [].sort.apply(this, args); + + !silent && can.trigger(this, "reset"); + } + }); + + // create push, pop, shift, and unshift + // converts to an array of arguments + var getArgs = function(args) { + return args[0] && can.isArray(args[0]) ? + args[0] : + can.makeArray(args); + }; + + can.each({ + + push: "length", + + unshift: 0 + }, + // adds a method where + // - name - method name + // - where - where items in the array should be added + + function(where, name) { + var proto = can.List.prototype, + old = proto[name]; + + proto[name] = function() { + // get the items being added + var args = getArgs(arguments), + // where we are going to add items + len = where ? this.length : 0; + + // call the original method + var res = old.apply(this, arguments); + + // cause the change where the args are: + // len - where the additions happened + // add - items added + // args - the items added + // undefined - the old value + if (this.comparator && args.length) { + this.sort(null, true); + can.batch.trigger(this, "reset", [args]); + this._triggerChange("" + len, "add", args, undefined); + } + + return res; + } + }); + + //- override changes for sorting + proto._changes = function(ev, attr, how, newVal, oldVal) { + if (this.comparator && /^\d+./.test(attr)) { + // get the index + var index = +(/^\d+/).exec(attr)[0], + // and item + item = this[index]; + + if (typeof item != "undefined") { + // and the new item + var newIndex = this.sortedIndex(item); + + if (newIndex !== index) { + // move ... + [].splice.call(this, index, 1); + [].splice.call(this, newIndex, 0, item); + + can.trigger(this, "move", [item, newIndex, index]); + can.trigger(this, "change", [ + attr.replace(/^\d+/, newIndex), + how, + newVal, + oldVal + ]); + + return; + } + } + } + + _changes.apply(this, arguments); + }; + + //- override setup for sorting + proto.setup = function(instances, options) { + setup.apply(this, arguments); + + if (this.comparator) { + this.sort() + } + }; + + return can.Map; +})(can); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006334_browserify.js b/pool/shard001/JavaScript/0006334_browserify.js new file mode 100644 index 0000000000000000000000000000000000000000..17afb5643ab833d4c166f1de6ec5a7b0bf6ecd76 --- /dev/null +++ b/pool/shard001/JavaScript/0006334_browserify.js @@ -0,0 +1,106 @@ +'use strict'; + +var gulp = require('gulp'); +var browserify = require('browserify'); +var watchify = require('watchify'); +var bundleLogger = require('../utils/bundle-logger'); +var source = require('vinyl-source-stream'); +var buffer = require('vinyl-buffer'); +var transform = require('vinyl-transform'); +var errorHandler = require('./../utils/error-handler'); +var ngAnnotate = require('gulp-ng-annotate'); +var uglify = require('gulp-uglify'); +var gulpif = require('gulp-if'); +var lazypipe = require('lazypipe'); +var config = require('../config').browserify; +var size = require('gulp-size'); +var glob = require("glob"); +var path = require('path'); +var yamlify = require('yamlify'); +var md5 = require("gulp-md5-plus"); +var inject = require('../config').inject; + + +gulp.task('browserify', ['bower'], function () { + + var isDebug = !global.release; + + var browserifyThis = function (file) { + var bundler = browserify({ + // Required watchify args + cache: {}, + packageCache: {}, + basedir: '', + + fullPaths: isDebug, + // Specify the entry point of your app + entries: file, + // Add file extentions to make optional in your requires + extensions: config.extensions, + // Enable source maps! + debug: isDebug + }); + + config.transformList.forEach(function(transformItem){ + if(Array.isArray(transformItem)){ + bundler.transform( + transformItem[0],transformItem[1] + ); + }else{ + bundler.transform(transformItem); + } + }); + + var bundle = function () { + // Log when bundling starts + bundleLogger.start(file); + + var compress = lazypipe() + .pipe(ngAnnotate) + .pipe(uglify); + + var baseDir = config.baseDir ? config.baseDir : path.dirname(file) + '/'; + var newFileName = file.replace(baseDir, ''); + return bundler + .bundle() + .on('error', errorHandler) + .pipe(source(newFileName)) + .pipe(buffer()) + .pipe(gulpif(!isDebug, compress())) + .pipe(size()) + .pipe(gulpif(!isDebug, md5(10 ,inject.dest))) + .pipe(gulp.dest(config.dest)) + .on('end', reportFinished); + }; + + if (global.isWatching) { + // Wrap with watchify and rebundle on changes + bundler = watchify(bundler); + // Rebundle on update + bundler.on('update', bundle); + } + + var reportFinished = function () { + // Log when bundling completes + bundleLogger.end(file); + }; + + return bundle(); + }; + + function LoopEntries(entries) { + glob(entries, function (er, files) { + files.forEach(function (file) { + browserifyThis(file); + }); + }) + } + + if (Array.isArray(config.entries)) { + config.entries.forEach(LoopEntries) + } else { + LoopEntries(config.entries) + } + + +}); diff --git a/pool/shard001/JavaScript/0006338_app.js b/pool/shard001/JavaScript/0006338_app.js new file mode 100644 index 0000000000000000000000000000000000000000..945333d25a0634817d7918247e1d5c44a89dacba --- /dev/null +++ b/pool/shard001/JavaScript/0006338_app.js @@ -0,0 +1,39 @@ +/** + * Created by ANGULAR on 10/05/2016. + */ +var express=require('express'); +var app=express(); + +var MongoClient=require('mongodb').MongoClient; +var assert= require('assert'); +var ObjectId=require('mongodb').ObjectID; +var url='mongodb://localhost:27017/test'; + +app.get('/ejemplo1',function(req,res){ + MongoClient.connect(url,function (err, db) { + assert.equal(null,err); + function findRestaurants(db, callback) { + var cursor=db.collection('restaurants').find({"borough":"Bronx","address.zipcode":"10460","address.street":"Devoe Avenue"}); + cursor.each(function(err,doc){ + assert.equal(err,null); + if(doc!=null){ + console.dir(doc); + res.json(doc); + } else { + callback(); + } + }); + }; + + findRestaurants(db,function () { + db.close(); + }); + }); +}); +app.get('/user',function(req,res){ + res.json({usuario:'User1',id:1}); +}); + +app.listen(3000,function(){ + console.log('Estos es un ejemplo de liste en puerto 3000'); +}); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006340_BrigTimer.js b/pool/shard001/JavaScript/0006340_BrigTimer.js new file mode 100644 index 0000000000000000000000000000000000000000..cdaf77ac99b414739add04e8a1029a884db7e043 --- /dev/null +++ b/pool/shard001/JavaScript/0006340_BrigTimer.js @@ -0,0 +1,62 @@ +import { Fragment } from 'inferno'; +import { act } from '../byond'; +import { Button, Section } from '../components'; +import { createLogger } from '../logging'; + +const logger = createLogger('AirAlarm'); + +export const BrigTimer = props => { + const { state } = props; + const { config, data } = state; + const { ref } = config; + return ( + +
      +
      +
      + ); +}; diff --git a/pool/shard001/JavaScript/0006341_RootCloseWrapper.js b/pool/shard001/JavaScript/0006341_RootCloseWrapper.js new file mode 100644 index 0000000000000000000000000000000000000000..78614887079db7e1995a2be8f92d929888ae0d40 --- /dev/null +++ b/pool/shard001/JavaScript/0006341_RootCloseWrapper.js @@ -0,0 +1,114 @@ +'use strict'; + +var _inherits = require('babel-runtime/helpers/inherits')['default']; + +var _classCallCheck = require('babel-runtime/helpers/class-call-check')['default']; + +var _interopRequireDefault = require('babel-runtime/helpers/interop-require-default')['default']; + +exports.__esModule = true; + +var _react = require('react'); + +var _react2 = _interopRequireDefault(_react); + +var _utilsDomUtils = require('./utils/domUtils'); + +var _utilsDomUtils2 = _interopRequireDefault(_utilsDomUtils); + +var _utilsEventListener = require('./utils/EventListener'); + +// TODO: Merge this logic with dropdown logic once #526 is done. + +// TODO: Consider using an ES6 symbol here, once we use babel-runtime. + +var _utilsEventListener2 = _interopRequireDefault(_utilsEventListener); + +var CLICK_WAS_INSIDE = '__click_was_inside'; + +function suppressRootClose(event) { + // Tag the native event to prevent the root close logic on document click. + // This seems safer than using event.nativeEvent.stopImmediatePropagation(), + // which is only supported in IE >= 9. + event.nativeEvent[CLICK_WAS_INSIDE] = true; +} + +var RootCloseWrapper = (function (_React$Component) { + _inherits(RootCloseWrapper, _React$Component); + + function RootCloseWrapper(props) { + _classCallCheck(this, RootCloseWrapper); + + _React$Component.call(this, props); + + this.handleDocumentClick = this.handleDocumentClick.bind(this); + this.handleDocumentKeyUp = this.handleDocumentKeyUp.bind(this); + } + + RootCloseWrapper.prototype.bindRootCloseHandlers = function bindRootCloseHandlers() { + var doc = _utilsDomUtils2['default'].ownerDocument(this); + + this._onDocumentClickListener = _utilsEventListener2['default'].listen(doc, 'click', this.handleDocumentClick); + this._onDocumentKeyupListener = _utilsEventListener2['default'].listen(doc, 'keyup', this.handleDocumentKeyUp); + }; + + RootCloseWrapper.prototype.handleDocumentClick = function handleDocumentClick(e) { + // This is now the native event. + if (e[CLICK_WAS_INSIDE]) { + return; + } + + this.props.onRootClose(); + }; + + RootCloseWrapper.prototype.handleDocumentKeyUp = function handleDocumentKeyUp(e) { + if (e.keyCode === 27) { + this.props.onRootClose(); + } + }; + + RootCloseWrapper.prototype.unbindRootCloseHandlers = function unbindRootCloseHandlers() { + if (this._onDocumentClickListener) { + this._onDocumentClickListener.remove(); + } + + if (this._onDocumentKeyupListener) { + this._onDocumentKeyupListener.remove(); + } + }; + + RootCloseWrapper.prototype.componentDidMount = function componentDidMount() { + this.bindRootCloseHandlers(); + }; + + RootCloseWrapper.prototype.render = function render() { + // Wrap the child in a new element, so the child won't have to handle + // potentially combining multiple onClick listeners. + return _react2['default'].createElement( + 'div', + { onClick: suppressRootClose }, + _react2['default'].Children.only(this.props.children) + ); + }; + + RootCloseWrapper.prototype.getWrappedDOMNode = function getWrappedDOMNode() { + // We can't use a ref to identify the wrapped child, since we might be + // stealing the ref from the owner, but we know exactly the DOM structure + // that will be rendered, so we can just do this to get the child's DOM + // node for doing size calculations in OverlayMixin. + return _react2['default'].findDOMNode(this).children[0]; + }; + + RootCloseWrapper.prototype.componentWillUnmount = function componentWillUnmount() { + this.unbindRootCloseHandlers(); + }; + + return RootCloseWrapper; +})(_react2['default'].Component); + +exports['default'] = RootCloseWrapper; + +RootCloseWrapper.propTypes = { + onRootClose: _react2['default'].PropTypes.func.isRequired +}; +module.exports = exports['default']; \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006347_conduct-form-add-shinryou-subform.js b/pool/shard001/JavaScript/0006347_conduct-form-add-shinryou-subform.js new file mode 100644 index 0000000000000000000000000000000000000000..dbc1a3d81e5483852f6e4f305f483e171bd185c1 --- /dev/null +++ b/pool/shard001/JavaScript/0006347_conduct-form-add-shinryou-subform.js @@ -0,0 +1,140 @@ +"use strict"; + +var $ = require("jquery"); +var hogan = require("hogan.js"); +var tmplSrc = require("raw!./conduct-form-add-shinryou-subform.html"); +var task = require("../task"); +var service = require("myclinic-service-api"); +var resultTmplSrc = require("raw!./conduct-form-add-shinryou-subform-search-result.html"); +var resultTmpl = hogan.compile(resultTmplSrc); + +exports.create = function(at, conductId){ + var dom = $(tmplSrc); + var ctx = { + shinryoucode: undefined + }; + bindEnter(dom, conductId, at, ctx); + bindCancel(dom); + bindSearch(dom, at); + bindSearchResultSelect(dom, at, ctx); + return dom; +}; + +var nameSelector = "> [mc-name=disp-area] [mc-name=name]"; +var enterSelector = "> .commandbox [mc-name=enterLink]"; +var cancelSelector = "> .commandbox [mc-name=cancelLink]"; +var searchFormSelector = "> form[mc-name=search-form]"; +var searchTextSelector = "> form[mc-name=search-form] input[mc-name=searchText]"; +var searchResultSelector = "> form[mc-name=search-form] select[mc-name=searchResult]"; + +function getSearchResultDom(dom){ + return dom.find(searchResultSelector); +} + +function getSearchText(dom){ + return dom.find(searchTextSelector).val().trim(); +} + +function updateName(dom, name){ + dom.find(nameSelector).text(name); +} + +function bindEnter(dom, conductId, at, ctx){ + dom.on("click", enterSelector, function(event){ + event.preventDefault(); + var shinryoucode = ctx.shinryoucode; + if( !shinryoucode ){ + alert("診療行為が指定されていません。"); + return; + } + shinryoucode = +shinryoucode; + var newConduct; + task.run([ + function(done){ + service.enterConductShinryou({ + visit_conduct_id: conductId, + shinryoucode: shinryoucode + }, done); + }, + function(done){ + service.getFullConduct(conductId, at, function(err, result){ + if( err ){ + done(err); + return; + } + newConduct = result; + done(); + }) + } + ], function(err){ + if( err ){ + alert(err); + return; + } + dom.trigger("conduct-modified", [conductId, newConduct]); + }) + }); +} + +function bindCancel(dom){ + dom.on("click", cancelSelector, function(event){ + event.preventDefault(); + dom.trigger("cancel"); + }) +} + +function bindSearch(dom, at){ + dom.on("submit", searchFormSelector, function(event){ + event.preventDefault(); + var text = getSearchText(dom); + if( text === "" ){ + return; + } + var searchResult; + task.run(function(done){ + service.searchShinryouMaster(text, at, function(err, result){ + if( err ){ + done(err); + return; + } + searchResult = result; + done(); + }) + }, function(err){ + if( err ){ + alert(err); + return; + } + getSearchResultDom(dom).html(resultTmpl.render({list: searchResult})); + }) + }); +} + +function setShinryou(dom, master, ctx){ + ctx.shinryoucode = master.shinryoucode; + updateName(dom, master.name); +} + +function bindSearchResultSelect(dom, at, ctx){ + dom.on("change", searchResultSelector, function(event){ + var shinryoucode = dom.find(searchResultSelector + " option:selected").val(); + var master; + task.run(function(done){ + service.getShinryouMaster(shinryoucode, at, function(err, result){ + if( err ){ + done(err); + return; + } + master = result; + done(); + }); + }, function(err){ + if( err ){ + alert(err); + return; + } + setShinryou(dom, master, ctx); + }) + }); +} + diff --git a/pool/shard001/JavaScript/0006353_test-system.js b/pool/shard001/JavaScript/0006353_test-system.js new file mode 100644 index 0000000000000000000000000000000000000000..3c453b2f2a5af9fafb117bebb8300748f57798c9 --- /dev/null +++ b/pool/shard001/JavaScript/0006353_test-system.js @@ -0,0 +1,34 @@ +#!/usr/bin/env node + +var async = require('async'), + fs = require('fs'), + shell = require('shelljs'), + path = require('path'), + chalk = require('chalk'), + Mocha = require('mocha'); + +module.exports = function (exit) { + console.log(chalk.bold.yellow('Running system tests in updater module...')); + async.series([ + function (next) { + var mocha = new Mocha(), + src = path.join(__dirname, '..', 'tests', 'system'); + + fs.readdir(src, (err, files) => { // eslint-disable-line consistent-return + if (err) { return next(err); } + + files.filter((file) => { + return (file.substr(-8) === '.test.js'); + }).forEach((file) => { + mocha.addFile(path.join(src, file)); + }); + + mocha.run(next); + mocha = null; + + }); + } + ], exit); +}; + +!module.parent && module.exports(shell.exit); diff --git a/pool/shard001/JavaScript/0006354_platformIos.js b/pool/shard001/JavaScript/0006354_platformIos.js new file mode 100644 index 0000000000000000000000000000000000000000..b295dde55fc8979d5f896041519b98f08109f26f --- /dev/null +++ b/pool/shard001/JavaScript/0006354_platformIos.js @@ -0,0 +1,175 @@ + +myPager.addTask('platformIos', { + + + init: function (pageId, pageContent, event, dom, scope) { + //console.log('---> init', pageId, pageContent, event, dom, scope); + + + var xmlDoc = helper.configParse(); + var platform = xmlDoc.querySelector('platform[name="ios"]'); + + return function () { + + var active = document.getElementById('editor.platform.ios.active'); + if (platform) { + active.checked = true; + } else { + active.checked = false; + helper.platformDisableForm(dom); + + } + active.onchange = function (e) { + if (e.target.checked) { + helper.configAddPlatform('ios'); + myPager.switch(pageId,'platformIos.init',pageContent,{container:'editor.content'}); + return false; + } else { + helper.configRemovePlatform('ios'); + helper.platformDisableForm(dom); + } + }; + + + if (platform) { + + var iconsDom = document.getElementById('editor.platform.ios.icons'); + var nodes = platform.querySelectorAll('icon'); + var length = nodes.length; + for (var i = 0; i < length; i++) { + var node = iconsDom.querySelector('input[rel="'+nodes[i].getAttribute('width')+'-'+nodes[i].getAttribute('height')+'"]'); + node.value = nodes[i].getAttribute('src'); + node.parentNode.querySelector('.preview').style.backgroundImage = 'url(file://'+_globals.appActive.data.localPath+'/'+node.value+')'; + } + + + var iconsDom = document.getElementById('editor.platform.ios.splash'); + var nodes = platform.querySelectorAll('splash'); + var length = nodes.length; + for (var i = 0; i < length; i++) { + var node = iconsDom.querySelector('input[rel="'+nodes[i].getAttribute('width')+'-'+nodes[i].getAttribute('height')+'"]'); + node.value = nodes[i].getAttribute('src'); + node.parentNode.querySelector('.preview').style.backgroundImage = 'url(file://'+_globals.appActive.data.localPath+'/'+node.value+')'; + } + + var form = new cForm('configForm'); + + helper.configFieldsUi('editor.platform.ios.ui', xmlDoc, 'ios', { change: function () { + form.validate({required: 'invalide'}); + }, + saved: function (xmlStr) { + //console.log('done', xmlStr); + //_globals.tabConfig.editor.setValue(xmlStr+''); + } }); + + + } + + if (event && event.target) { + helper.editorSwitchTab(event.target); + } + + }; + }, + iconAdd: function (pageId, pageContent, event, dom, scope) { + + const dialog = remote.require('dialog') + var path = dialog.showOpenDialog({ + properties: ['openFile'], + filters: [ + { name: 'Images', extensions: ['png'] } + ] + }); + var params = JSON.parse(pageContent); + if (path[0] && params.file) { + + helper.makeIconFolder('ios', function (err) { + if (err) { + return false; + } + var newPathFile = 'res/icon/ios/'+params.file+'.png'; + var newPath = _globals.appActive.data.localPath+'/'+newPathFile; + + helper.copyFile(path[0], newPath, function () { + helper.configAppendIcon('ios', newPathFile, params.w, params.h, null, function () { + event.target.parentNode.querySelector('input[name="src"]').value = newPathFile; + event.target.parentNode.querySelector('.preview').style.backgroundImage = 'url(file://'+_globals.appActive.data.localPath+'/'+newPathFile+')'; + }); + }); + }); + } + + }, + iconRemove: function (pageId, pageContent, event, dom, scope) { + + var path = event.target.parentNode.querySelector('input[name="src"]').value + if (!path) { + return false; + } + var r = confirm("Also delete the locale file?"); + if (r == true) { + var pathLong = _globals.appActive.data.localPath +'/'+ path; + helper.delteFile(pathLong); + } + helper.configRemoveIcon('ios', path, function () { + event.target.parentNode.querySelector('input[name="src"]').value = ''; + event.target.parentNode.querySelector('.preview').style.backgroundImage = 'url()'; + }); + + }, + splashAdd: function (pageId, pageContent, event, dom, scope) { + + const dialog = remote.require('dialog') + var path = dialog.showOpenDialog({ + properties: ['openFile'], + filters: [ + { name: 'Images', extensions: ['png'] } + ] + }); + var params = JSON.parse(pageContent); + if (path[0] && params.file) { + + helper.makeSplashFolder('ios', function (err) { + if (err) { + return false; + } + var newPathFile = 'res/splash/ios/'+params.file+'.png'; + var newPath = _globals.appActive.data.localPath+'/'+newPathFile; + + helper.copyFile(path[0], newPath, function () { + helper.configAppendSplash('android', newPathFile, params.w, params.h, null, function () { + event.target.parentNode.querySelector('input[name="src"]').value = newPathFile; + event.target.parentNode.querySelector('.preview').style.backgroundImage = 'url(file://'+_globals.appActive.data.localPath+'/'+newPathFile+')'; + }); + }); + }); + } + + }, + splashRemove: function (pageId, pageContent, event, dom, scope) { + + var path = event.target.parentNode.querySelector('input[name="src"]').value + if (!path) { + return false; + } + var r = confirm("Also delete the locale file?"); + if (r == true) { + var pathLong = _globals.appActive.data.localPath +'/'+ path; + helper.delteFile(pathLong); + } + helper.configRemoveSplash('ios', path, function () { + event.target.parentNode.querySelector('input[name="src"]').value = ''; + event.target.parentNode.querySelector('.preview').style.backgroundImage = 'url()'; + }); + + }, + tab: function (pageId, pageContent, event, dom, scope) { + + helper.switchTab(pageContent, 'editor.platform.ios.tabnav', event.target); + + } + + + + +}); diff --git a/pool/shard001/JavaScript/0006356_jquery.dcverticalmegamenu.1.1.js b/pool/shard001/JavaScript/0006356_jquery.dcverticalmegamenu.1.1.js new file mode 100644 index 0000000000000000000000000000000000000000..26a253ab3d263d4735d0131bab8a92e5cb6a26d2 --- /dev/null +++ b/pool/shard001/JavaScript/0006356_jquery.dcverticalmegamenu.1.1.js @@ -0,0 +1,205 @@ +/* + * DC Vertical Mega Menu - jQuery vertical mega menu + * Copyright (c) 2011 Design Chemical + * + * Dual licensed under the MIT and GPL licenses: + * http://www.opensource.org/licenses/mit-license.php + * http://www.gnu.org/licenses/gpl.html + * + */ +(function($){ + + //define the new for the plugin ans how to call it + $.fn.dcVerticalMegaMenu = function(options){ + //set default options + var defaults = { + classParent: 'dc-mega', + arrow: true, + classArrow: 'dc-mega-icon', + classContainer: 'sub-container', + classSubMenu: 'sub', + classMega: 'mega', + classSubParent: 'mega-hdr', + classSubLink: 'mega-hdr', + classRow: 'row', + rowItems: 3, + speed: 'fast', + effect: 'show', + direction: 'right' + }; + + //call in the default otions + var options = $.extend(defaults, options); + var $dcVerticalMegaMenuObj = this; + + //act upon the element that is passed into the design + return $dcVerticalMegaMenuObj.each(function(options){ + + $mega = $(this); + if(defaults.direction == 'left'){ + $mega.addClass('left'); + } else { + $mega.addClass('right'); + } + // Get Menu Width + var megaWidth = $mega.width(); + + // Set up menu + $('> li',$mega).each(function(){ + + var $parent = $(this); + var $megaSub = $('> ul',$parent); + + if($megaSub.length > 0){ + + $('> a',$parent).addClass(defaults.classParent).append(''); + $megaSub.addClass(defaults.classSubMenu).wrap('
      '); + var $container = $('.'+defaults.classContainer,$parent); + + if($('ul',$megaSub).length > 0){ + + $parent.addClass(defaults.classParent+'-li'); + $container.addClass(defaults.classMega); + + // Set sub headers + $('> li',$megaSub).each(function(){ + $(this).addClass('mega-unit'); + if($('> ul',this).length){ + $(this).addClass(defaults.classSubParent); + $('> a',this).addClass(defaults.classSubParent+'-a'); + } else { + $(this).addClass(defaults.classSubLink); + $('> a',this).addClass(defaults.classSubLink+'-a'); + } + }); + + // Create Rows + var hdrs = $('.mega-unit',$parent); + rowSize = parseInt(defaults.rowItems); + for(var i = 0; i < hdrs.length; i+=rowSize){ + hdrs.slice(i, i+rowSize).wrapAll('
      '); + } + + // Get mega dimensions + var itemWidth = $('.mega-unit',$megaSub).outerWidth(true); + var rowItems = $('.row:eq(0) .mega-unit',$megaSub).length; + var innerItemWidth = itemWidth * rowItems; + var totalItemWidth = innerItemWidth + containerPad; + + // Set mega header height + $('.row',this).each(function(){ + $('.mega-unit:last',this).addClass('last'); + var maxValue = undefined; + $('.mega-unit > a',this).each(function(){ + var val = parseInt($(this).height()); + if (maxValue === undefined || maxValue < val){ + maxValue = val; + } + }); + $('.mega-unit > a',this).css('height',maxValue+'px'); + $(this).css('width',innerItemWidth+'px'); + }); + var subWidth = $megaSub.outerWidth(true); + var totalWidth = $container.outerWidth(true); + var containerPad = totalWidth - subWidth; + // Calculate Row Height + $('.row',$megaSub).each(function(){ + var rowHeight = $(this).height(); + $(this).parent('.row').css('height',rowHeight+'px'); + }); + $('.row:last',$megaSub).addClass('last'); + $('.row:first',$megaSub).addClass('first'); + } else { + $container.addClass('non-'+defaults.classMega); + } + } + + var $container = $('.'+defaults.classContainer,$parent); + // Get flyout height + var subHeight = $container.height(); + var itemHeight = $parent.outerHeight(true); + // Set position to top of parent + $container.css({ + height: subHeight+'px', + marginTop: -itemHeight+'px', + zIndex: '1000', + width: subWidth+'px' + }).hide(); + }); + + // HoverIntent Configuration + var config = { + sensitivity: 2, // number = sensitivity threshold (must be 1 or higher) + interval: 100, // number = milliseconds for onMouseOver polling interval + over: megaOver, // function = onMouseOver callback (REQUIRED) + timeout: 0, // number = milliseconds delay before onMouseOut + out: megaOut // function = onMouseOut callback (REQUIRED) + }; + + $('li',$dcVerticalMegaMenuObj).hoverIntent(config); + + function megaOver(){ + $(this).addClass('mega-hover'); + var $link = $('> a',this); + var $subNav = $('.sub',this); + var $container = $('.sub-container',this); + var width = $container.width(); + var outerHeight = $container.outerHeight(true); + var height = $container.height(); + var itemHeight = $(this).outerHeight(true); + var offset = $link.offset(); + var scrollTop = $(window).scrollTop(); + offset = offset.top - scrollTop + var bodyHeight = $(window).height(); + var maxHeight = bodyHeight - offset; + var xsHeight = maxHeight - outerHeight - itemHeight; + + if(xsHeight < 0){ + var containerMargin = xsHeight - itemHeight; + $container.css({marginTop: containerMargin+'px'}); + } + + var containerPosition = {right: megaWidth}; + if(defaults.direction == 'right'){ + containerPosition = {left: megaWidth}; + } + + if(defaults.effect == 'fade'){ + $container.css(containerPosition).fadeIn(defaults.speed); + } + if(defaults.effect == 'show'){ + $container.css(containerPosition).show(); + } + if(defaults.effect == 'slide'){ + $container.css({ + width: 0, + height: 0, + opacity: 0}); + + if(defaults.direction == 'right'){ + + $container.show().css({ + left: megaWidth + }); + } else { + + $container.show().css({ + right: megaWidth + }); + } + $container.animate({ + width: width, + height: height, + opacity: 1 + }, defaults.speed); + } + } + + function megaOut(){ + $(this).removeClass('mega-hover'); + var $container = $('.sub-container',this); + $container.hide(); + } + }); + }; +})(jQuery); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006357_events.js b/pool/shard001/JavaScript/0006357_events.js new file mode 100644 index 0000000000000000000000000000000000000000..3f352ede2e6e1cf56def95f5eb4dc71eef901d3a --- /dev/null +++ b/pool/shard001/JavaScript/0006357_events.js @@ -0,0 +1,117 @@ +function Events(toFrage) { + var localContainer = { + version: "1", + frage: toFrage + }; + + localContainer.actionEvent = function(config) { + var local = { + triggers: [], + returnOnSuccess: [], + triggered: false + }; + this.frage.Base.extend(this.frage.Base.orderedObject(config), local); + + local.updateEvent = function(input) { + if (!this.triggered) var passToCallback = {}; + for (var index=0; index < this.triggers.length; index++) { + var trigger = this.triggers[index]; + if (!input[trigger]) { + this.triggered = false; + return input; + } else if (!this.triggered) { + passToCallback[trigger] = input[trigger]; + } + } + + if (!this.triggered) { + this.triggered = true; + + // Call callbacks. + this.iterateOverObjects(function(callback) { + callback(passToCallback); + }); + + // Delete keys + for (var index=0; index < this.returnOnSuccess.length; index++) { + delete input[this.returnOnSuccess[index]]; + } + } + + return input; + }; + + return local; + }; + + localContainer.stateEvent = function(config) { + var local = { + triggers: [], // ["shift", "control", "w"] // It will be turned into keycodes - not human readable. + returnOnSuccess: [] // ["shift", "control"] // Could be used for evil.. (╯°□°)╯︵ ┻━┻ Much power, great responsibility. ~ Doge + }; + this.frage.Base.extend(this.frage.Base.orderedObject(config), local); + + local.updateEvent = function(input) { + var passToCallback = {}; + // Check if all the required keys are active, bail out otherwise + for (var index=0; index < this.triggers.length; index++) { + var trigger = this.triggers[index]; + if (!input[trigger]) return input; + else passToCallback[trigger] = input[trigger]; + } + + // Call callbacks. + this.iterateOverObjects(function(callback) { + callback(passToCallback); + }); + + // Delete keys + for (var index=0; index < this.returnOnSuccess.length; index++) { + delete input[this.returnOnSuccess[index]]; + } + + return input; + }; + + return local; + }; + + localContainer.getEventContext = function(config) { + var local = { + onHold: false, + validate: function(object) { + if (object.updateEvent) return true; + } + }; + this.frage.Base.extend(this.frage.Base.orderedObject(), local, true); + this.frage.Base.extend(config, local); + + local.suspend = function() { + this.onHold = true; + }; + + local.resume = function(name) { + this.onHold = false; + }; + + local.state = function() { + return this.onHold; + }; + + local.update = function(input) { + if (!this.onHold) { + var remaining = input; + this.iterateOverObjects(function(object, name) { + if (remaining) remaining = object.updateEvent(input); + else return true; + }); + return remaining; + } + return input; + }; + + return local; + }; + + return localContainer; +}; diff --git a/pool/shard001/JavaScript/0006365_application.js b/pool/shard001/JavaScript/0006365_application.js new file mode 100644 index 0000000000000000000000000000000000000000..6fc657929207ea01e3c76759aa1e311537b8ea0a --- /dev/null +++ b/pool/shard001/JavaScript/0006365_application.js @@ -0,0 +1,52 @@ +// This is a manifest file that'll be compiled into including all the files listed below. +// Add new JavaScript/Coffee code in separate files in this directory and they'll automatically +// be included in the compiled file accessible from http://example.com/assets/application.js +// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the +// the compiled file. +// +//= require jquery +//= require jquery-ui +//= require jquery_ujs +//= require jquery.easyModal +//= require_tree ./ReactComponents + + +/** Modal windows, powered by jQuery.easyModal. */ + +function ModalMarkus(elem) { + this.modal_dialog = jQuery(elem).easyModal({ + updateZIndexOnOpen: false + }); +} + +ModalMarkus.prototype.open = function() { + this.modal_dialog.trigger('openModal'); +} + +ModalMarkus.prototype.close = function() { + this.modal_dialog.trigger('closeModal'); +} + + +/** Helper functions for managing DOM elements' classes via pure JavaScript. */ + +Element.prototype.addClass = function(className) { + if (this.classList) + this.classList.add(className); + else + this.className += ' ' + className; +} + +Element.prototype.removeClass = function(className) { + if (this.classList) + this.classList.remove(className); + else + this.className = this.className.replace(new RegExp('(^|\\b)' + className.split(' ').join('|') + '(\\b|$)', 'gi'), ' '); +} + +Element.prototype.hasClass = function(className) { + if (this.classList) + return this.classList.contains(className); + else + return new RegExp('(^| )' + className + '( |$)', 'gi').test(this.className); +} diff --git a/pool/shard001/JavaScript/0006367_S13.2.2_A3_T1.js b/pool/shard001/JavaScript/0006367_S13.2.2_A3_T1.js new file mode 100644 index 0000000000000000000000000000000000000000..10b21f60612f7875bb1cfdc9e2484ad2879475aa --- /dev/null +++ b/pool/shard001/JavaScript/0006367_S13.2.2_A3_T1.js @@ -0,0 +1,33 @@ +// Copyright 2009 the Sputnik authors. All rights reserved. +/** + * When the [[Construct]] property for a Function object F is called: + * A new native ECMAScript object is created. + * It gets the value of the [[Prototype]] property of the F(Denote it PROTO_VAL). + * If PROTO_VAL is not an object, sets the [[Prototype]] property of native ECMAScript object just created + * to the original Object prototype object as described in 15.2.3.1 + * + * @path ch13/13.2/S13.2.2_A3_T1.js + * @description Declaring a function with "function __FACTORY()" + */ + +function __FACTORY(){}; +__FACTORY.prototype=1; + +////////////////////////////////////////////////////////////////////////////// +//CHECK#1 +if (typeof __FACTORY.prototype !== 'number') { + $ERROR('#1: typeof __FACTORY.prototype === \'number\'. Actual: typeof __FACTORY.prototype ==='+(typeof __FACTORY.prototype)); +} +// +////////////////////////////////////////////////////////////////////////////// + +var __device = new __FACTORY(); + +////////////////////////////////////////////////////////////////////////////// +//CHECK#2 +if (!(Object.prototype.isPrototypeOf(__device))) { + $ERROR('#2: Object.prototype.isPrototypeOf(__device) === true'); +} +// +////////////////////////////////////////////////////////////////////////////// + diff --git a/pool/shard001/JavaScript/0006371_main.js b/pool/shard001/JavaScript/0006371_main.js new file mode 100644 index 0000000000000000000000000000000000000000..5a98761e5e18f9122ad574598fe02272253b0a95 --- /dev/null +++ b/pool/shard001/JavaScript/0006371_main.js @@ -0,0 +1,38 @@ +require('./_breakpoints'); +require('./_sidebar-menu'); +require('./_collapsible'); +require('./_dropdown'); +require('./_sidebar-toggle'); + +(function($){ + "use strict"; + + /** + * jQuery plugin wrapper for compatibility with Angular UI.Utils: jQuery Passthrough + */ + $.fn.tkSidebar = function (options) { + + if (! this.length) return; + + var settings = $.extend({ + menuType: false, + toggleBar: false + }, options); + + var sidebar = this; + + if (settings.menuType == "collapse") { + sidebar.tkSidebarCollapse(); + } + + if (settings.menuType == "dropdown") { + sidebar.tkSidebarDropdown(); + } + + if (settings.toggleBar === true) { + sidebar.tkSidebarToggleBar(); + } + + }; + +})(jQuery); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006374_Link.js b/pool/shard001/JavaScript/0006374_Link.js new file mode 100644 index 0000000000000000000000000000000000000000..369e798bfaafa61af0871acdca16220e03fc6c9a --- /dev/null +++ b/pool/shard001/JavaScript/0006374_Link.js @@ -0,0 +1,185 @@ +/*! + * ${copyright} + */ + +// Provides control sap.ui.commons.Link. +sap.ui.define([ + 'jquery.sap.global', + './library', + 'sap/ui/core/Control', + 'sap/ui/core/EnabledPropagator', + 'sap/ui/core/LabelEnablement', + "./LinkRenderer" +], + function(jQuery, library, Control, EnabledPropagator, LabelEnablement, LinkRenderer) { + "use strict"; + + + + /** + * Constructor for a new Link. + * + * @param {string} [sId] id for the new control, generated automatically if no id is given + * @param {object} [mSettings] initial settings for the new control + * + * @class + * + * Provides an absolute or relative reference to an internal or external URL. The classical target parameters are supported. + * Another usage scenario is triggering an action, for example to open a popup window. In both cases, the link is a hypertext link. + * @extends sap.ui.core.Control + * @implements sap.ui.commons.ToolbarItem,sap.ui.commons.FormattedTextViewControl, sap.ui.core.IFormContent + * + * @author SAP SE + * @version ${version} + * + * @constructor + * @public + * @deprecated Since version 1.38. Instead, use the sap.m.Link control. + * @alias sap.ui.commons.Link + * @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel + */ + var Link = Control.extend("sap.ui.commons.Link", /** @lends sap.ui.commons.Link.prototype */ { metadata : { + + interfaces : [ + "sap.ui.commons.ToolbarItem", + "sap.ui.commons.FormattedTextViewControl", + "sap.ui.core.IFormContent" + ], + library : "sap.ui.commons", + properties : { + + /** + * + * Link text to be displayed. + */ + text : {type : "string", group : "Appearance", defaultValue : ''}, + + /** + * Whether the link can be triggered by the user. + */ + enabled : {type : "boolean", group : "Behavior", defaultValue : true}, + + /** + * + * Unique identifier used for help service. + */ + helpId : {type : "string", group : "Behavior", defaultValue : ''}, + + /** + * The link target URI. Supports standard hyperlink behavior. If an action should be triggered, this should not be set, but instead an event handler for the "press" event should be registered. + */ + href : {type : "sap.ui.core.URI", group : "Data", defaultValue : null}, + + /** + * + * Options are _self, _top, _blank, _parent, _search. Alternatively, a frame name can be entered. + */ + target : {type : "string", group : "Data", defaultValue : null}, + + /** + * Width of text link. When it is set (CSS-size such as % or px), this is the exact size. When left blank, the text defines the size. + * @since 1.8.0 + */ + width : {type : "sap.ui.core.CSSSize", group : "Dimension", defaultValue : null} + }, + associations : { + + /** + * Association to controls / ids which describe this control (see WAI-ARIA attribute aria-describedby). + */ + ariaDescribedBy : {type : "sap.ui.core.Control", multiple : true, singularName : "ariaDescribedBy"}, + + /** + * Association to controls / ids which label this control (see WAI-ARIA attribute aria-labelledby). + */ + ariaLabelledBy : {type : "sap.ui.core.Control", multiple : true, singularName : "ariaLabelledBy"} + }, + events : { + + /** + * + * Event is fired when the user clicks the control. + */ + press : {allowPreventDefault : true} + } + }}); + + + /** + * Puts the focus to the link. + * + * @name sap.ui.commons.Link#focus + * @function + * @type void + * @public + * @ui5-metamodel This method also will be described in the UI5 (legacy) designtime metamodel + */ + + + EnabledPropagator.call(Link.prototype); + + /** + * Required adaptations before rendering. + * + * @private + */ + Link.prototype.onBeforeRendering = function() { + // add/remove self reference for aria-labelledby to fix reading issues + this.removeAssociation("ariaLabelledBy", this.getId(), true); + if (this.getAriaLabelledBy().length > 0 || LabelEnablement.getReferencingLabels(this).length > 0) { + this.addAssociation("ariaLabelledBy", this.getId(), true); + } + }; + + /** + * Also trigger link activation when space is pressed on the focused control + */ + Link.prototype.onsapspace = function(oEvent) { + Link.prototype.onclick.apply(this, arguments); + }; + + /** + * Function is called when Link is clicked. + * + * @param {jQuery.Event} oEvent + * @private + */ + Link.prototype.onclick = function(oEvent) { + if (this.getEnabled()) { + // the default behavior will be supressed, when oEvent.preventDefault() is + // called or when the link doesn't contain a valid href (#)). + // The last thing will trigger the onbeforeunload event in IE when not + // preventing the default behavior + if (!this.firePress() || !this.getHref()) { + oEvent.preventDefault(); + } + } else { + oEvent.preventDefault(); + } + }; + + /** + * The Link handles the enter by itself + * @since 1.16.2 + */ + Link.prototype.onsapenter = function(oEvent) { + oEvent.stopPropagation(); + }; + + /** + * @see sap.ui.core.Control#getAccessibilityInfo + * @protected + */ + Link.prototype.getAccessibilityInfo = function() { + return { + role: "link", + type: sap.ui.getCore().getLibraryResourceBundle("sap.ui.commons").getText("ACC_CTR_TYPE_LINK"), + description: this.getText() || this.getHref() || "", + focusable: this.getEnabled(), + enabled: this.getEnabled() + }; + }; + + return Link; + +}, /* bExport= */ true); diff --git a/pool/shard001/JavaScript/0006375_initialUserObjects.js b/pool/shard001/JavaScript/0006375_initialUserObjects.js new file mode 100644 index 0000000000000000000000000000000000000000..f97b34a559d6ff4ee16a2c2328d944f2de2159bd --- /dev/null +++ b/pool/shard001/JavaScript/0006375_initialUserObjects.js @@ -0,0 +1,26 @@ +'use strict'; + +var mongoose = require('mongoose'), + User = mongoose.model('User'), + GameObjects = mongoose.model('GameObjects'); + +module.exports = { + createDefaultsForUser: function (user) { + GameObjects.create({ + owner: user, + coordinates: user.coordinates, + minerals: 250, + gas: 0, + updated: (new Date()).getTime(), + tasks: [], + // mineral gas energy supply troops ships lab - only indexes as building levels + buildings: [0, 0, 0, 0, 0, 0, 0], + // transport tier 1 tier 2 tier 3 + ships: [0, 0, 0, 0], + // tier 1 tier 2 tier 3 + troops: [0, 0, 0], + upgrades: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + attacks: [] + }); + } +}; \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006378_linear_regression_example.js b/pool/shard001/JavaScript/0006378_linear_regression_example.js new file mode 100644 index 0000000000000000000000000000000000000000..baeb97e7aeabc0212ec67a66c7dc0e379d8c9641 --- /dev/null +++ b/pool/shard001/JavaScript/0006378_linear_regression_example.js @@ -0,0 +1,71 @@ +/* + * Copyright 2016 IBM Corp. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + Usage: + bin/eclairjs.sh examples/mllib/linear_regression_example.js" + */ + +/* + * Require modules needed within lambda functions. + */ +//var RDD = require('RDD'); +LabeledPoint = 21; +var LinearRegressionWithSGD = require('eclairjs/mllib/regression').LinearRegressionWithSGD; +var myLabeledPoint = require('eclairjs/mllib/regression/LabeledPoint'); +var myDenseVector = require('eclairjs/mllib/linalg/DenseVector'); +var LinearRegressionWithSGD = require('eclairjs/mllib/regression/LinearRegressionWithSGD'); +var Tuple = require('eclairjs/Tuple'); + +function run(sc) { + var filename = ((typeof args !== "undefined") && (args.length > 1)) ? args[1] : "examples/data/lpsa.data"; + var data = sc.textFile(filename).cache(); + var parsedData = data.map(function (s, myLabeledPoint, myDenseVector) { + var parts = s.split(","); + var features = parts[1].split(" "); + return new myLabeledPoint(parts[0], new myDenseVector(features)); + }, [myLabeledPoint, myDenseVector]); + + var numIterations = 3; + var linearRegressionModel = LinearRegressionWithSGD.train(parsedData, numIterations); + + var delta = 17; + var valuesAndPreds = parsedData.mapToPair(function (lp, linearRegressionModel, delta, Tuple) { + var label = lp.getLabel(); + var f = lp.getFeatures(); + var prediction = linearRegressionModel.predict(f) + delta; + return new Tuple(prediction, label); + }, [linearRegressionModel, delta, Tuple]); // end MapToPair + + return valuesAndPreds.take(10); + +} + +/* + check if SparkContext is defined, if it is we are being run from Unit Test + */ + +if (typeof sparkContext === 'undefined') { + var SparkConf = require('eclairjs/SparkConf'); + var SparkContext = require('eclairjs/SparkContext'); + var sparkConf = new SparkConf() + .setAppName("Linear Regression Example"); + var sc = new SparkContext(sparkConf); + var result = run(sc); + print("valuesAndPreds: " + result.toString()); + + sc.stop(); +} diff --git a/pool/shard001/JavaScript/0006379_app.js b/pool/shard001/JavaScript/0006379_app.js new file mode 100644 index 0000000000000000000000000000000000000000..838b0a912ed33620f50c4c672378f282c7e59baa --- /dev/null +++ b/pool/shard001/JavaScript/0006379_app.js @@ -0,0 +1,97 @@ +module.exports = function (db_polls, db_users) { + +var express = require('express') +var app = express() + +//Set up templating View engine +var hbs = require('hbs') +app.set('view engine', 'html'); +app.set('views', __dirname + '/views/'); +app.engine('html', require('hbs').__express); +hbs.registerPartials(__dirname + '/views/' ); + +//Attach body parsing middleware +var bodyParser = require('body-parser') +app.use(bodyParser.json()); +app.use(bodyParser.urlencoded({ extended: true })); + +app.get('/', function (req, res, next){ + db_polls.find({}, function(err, polls){ + res.render('index', {polls, baseUrl:req.baseUrl, user:req.user}); + }) + +}) + +app.get('/new-poll', function(req, res, next){ + res.render('new-poll', {baseUrl:req.baseUrl, user:req.user}) +}) + +app.post('/new-poll', function(req, res, next){ + var newPoll = req.body; + var options = newPoll.options.split(/\s*\n\s*/); + newPoll.options = [] + newPoll.votes = [] + newPoll.voters = {} + for(var i in options){ + if(options[i]){ + //newPoll.options[options[i]] = {option:options[i], votes:0} + newPoll.options.push(options[i]) + newPoll.votes.push(0) + } + } + db_polls.insert(newPoll, function(err, insertedPoll){ + + res.append('Refresh', "0; " + req.baseUrl + "/poll/" + insertedPoll._id); + res.json({newPoll, err, insertedPoll}); + + }) + +}) + +app.get('/poll/:id', function(req, res, next){ + db_polls.find({_id:req.params.id}, function(err, poll){ + if(err){ + return next(err); + } else if (poll.length == 0){ + res.sendStatus(404) + } else { + var ctx = poll[0]; + ctx.user= req.user + ctx.baseUrl = req.baseUrl + res.render('poll', ctx) + } + }) +}); + +app.post('/poll/:id', function(req, res, next){ + if(req.body.option == undefined){ + throw new Error("No option chosen!") + } + db_polls.find({_id:req.params.id}, function(err, poll){ + if(err){ + return next(err); + } else if (poll.length == 0){ + res.sendStatus(404) + } else { + poll = poll[0] + poll.votes[req.body.option]++ + db_polls.update({_id:poll._id}, poll, {}, function(err){ + if(err){ + res.status(500) + res.json(err) + } else { + res.append('Refresh', "0; " + req.originalUrl); + res.status(200) + res.send() + } + }) + } + }) +}) + + + + + +return app; +} diff --git a/pool/shard001/JavaScript/0006380_amd.js b/pool/shard001/JavaScript/0006380_amd.js new file mode 100644 index 0000000000000000000000000000000000000000..ec587b9e0baf59d290a9f34ef5ecb66a6f0388c3 --- /dev/null +++ b/pool/shard001/JavaScript/0006380_amd.js @@ -0,0 +1,81 @@ +var funnel = require('broccoli-funnel'), + findup = require('findup-sync'), + util = require('../util'), + path = require('path'), + fs = require('fs'); + +function findRoot( module, dir ) { + if (~dir.indexOf('dist/cjs')) { + return findRoot(module, path.resolve(dir, '../')); + } + + var pathnames = fs.readdirSync(dir), + basename = path.basename(module, '.js').replace(/js$/, '') + + var folders = [ + 'assets', + 'dist', + 'amd' + ]; + + for (var i = 0; i < folders.length; i++) { + var folder = folders[i]; + if (~pathnames.indexOf(folder)) { + if (util.isDirectory(folder, dir)) { + return findRoot(module, path.join(dir, folder)); + } + } + } + + if (~pathnames.indexOf(basename) && util.isDirectory(basename, dir)) { + return dir; + } + + var includes = pathnames.filter(function( pathname ) { + return ~pathname.indexOf(basename); + }); + + if (includes.length > 0) { + var excludes = pathnames.filter(function( pathname ) { + var extname = path.extname(pathname); + + if (pathname !== basename && util.isDirectory(pathname, dir)) { + return true; + } + + if (/(gzip|md|json)/.test(path.extname(pathname))) { + return false; + } + + if (!~pathname.indexOf(basename)) { + return true; + } + + return false; + }); + + if (excludes.length === 0) { + return dir; + } + } + + return false; +} + +module.exports = function exportAMD( module ) { + var modulePath = require.resolve(module), + moduleDir = path.dirname(modulePath), + baseDir = findRoot(module, moduleDir), + basename = path.basename(module, '.js').replace(/js$/, '') + + if (baseDir) { + return util.resolveTree(function() { + return funnel('./', { + include: [ + basename + '/**/*', + basename + '.*' + ] + }) + }, baseDir); + } +} \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006388_external_links.js b/pool/shard001/JavaScript/0006388_external_links.js new file mode 100644 index 0000000000000000000000000000000000000000..db7215f9eb10639ee8d23768d383ba849790a7da --- /dev/null +++ b/pool/shard001/JavaScript/0006388_external_links.js @@ -0,0 +1,40 @@ +// Convenient way for opening links in external browser, not in the app. +// Useful especially if you have a lot of links to deal with. +// +// Usage: +// +// Every link with class ".js-external-link" will be opened in external browser. +// google +// +// The same behaviour for many links can be achieved by adding +// this class to any parent tag of an anchor tag. +// + +import { shell } from 'electron'; + +const supportExternalLinks = (event) => { + let href; + let isExternal = false; + + const checkDomElement = (element) => { + if (element.nodeName === 'A') { + href = element.getAttribute('href'); + } + if (element.classList.contains('js-external-link')) { + isExternal = true; + } + if (href && isExternal) { + shell.openExternal(href); + event.preventDefault(); + } else if (element.parentElement) { + checkDomElement(element.parentElement); + } + }; + + checkDomElement(event.target); +}; + +document.addEventListener('click', supportExternalLinks, false); diff --git a/pool/shard001/JavaScript/0006395_camvas.js b/pool/shard001/JavaScript/0006395_camvas.js new file mode 100644 index 0000000000000000000000000000000000000000..b85916aeb0f85253ae5b001153a812b96b9eaa66 --- /dev/null +++ b/pool/shard001/JavaScript/0006395_camvas.js @@ -0,0 +1,82 @@ +/* +Copyright (c) 2012 Claudio Brandolino + +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. +*/ + + +// requestAnimationFrame implementation, we just ignore it. +// My policy for experimental software is: if you don't have a +// nightly build, you don't deserve exceptions. +window.URL = window.URL || window.webkitURL + +navigator.getUserMedia = navigator.getUserMedia || + navigator.webkitGetUserMedia || + navigator.mozGetUserMedia || + navigator.msGetUserMedia + +window.requestAnimationFrame = window.requestAnimationFrame || + window.webkitRequestAnimationFrame || + window.mozRequestAnimationFrame || + window.msRequestAnimationFrame || + window.oRequestAnimationFrame + +// The function takes a canvas context and a `drawFunc` function. +// `drawFunc` receives two parameters, the video and the time since +// the last time it was called. +function camvas(ctx, drawFunc) { + var self = this + this.ctx = ctx + this.draw = drawFunc + + // We can't `new Video()` yet, so we'll resort to the vintage + // "hidden div" hack for dynamic loading. + var streamContainer = document.createElement('div') + this.video = document.createElement('video') + + // If we don't do this, the stream will not be played. + // By the way, the play and pause controls work as usual + // for streamed videos. + this.video.setAttribute('autoplay', '1') + + // The video should fill out all of the canvas + this.video.setAttribute('width', this.ctx.canvas.width) + this.video.setAttribute('height', this.ctx.canvas.height) + + this.video.setAttribute('style', 'display:none') + streamContainer.appendChild(this.video) + document.body.appendChild(streamContainer) + + // The callback happens when we are starting to stream the video. + navigator.getUserMedia({video: true}, function(stream) { + // Yay, now our webcam input is treated as a normal video and + // we can start having fun + self.video.src = window.URL.createObjectURL(stream) + // Let's start drawing the canvas! + self.update() + }, function(err){ + throw err + }) + + // As soon as we can draw a new frame on the canvas, we call the `draw` function + // we passed as a parameter. + this.update = function() { + var self = this + var last = Date.now() + var loop = function() { + // For some effects, you might want to know how much time is passed + // since the last frame; that's why we pass along a Delta time `dt` + // variable (expressed in milliseconds) + var dt = Date.now - last + self.draw(self.video, dt) + last = Date.now() + requestAnimationFrame(loop) + } + requestAnimationFrame(loop) + } +} + diff --git a/pool/shard001/JavaScript/0006396_index.js b/pool/shard001/JavaScript/0006396_index.js new file mode 100644 index 0000000000000000000000000000000000000000..cec87b016c5187bbe9847177314ad7767530ba98 --- /dev/null +++ b/pool/shard001/JavaScript/0006396_index.js @@ -0,0 +1,145 @@ +'use strict' + +var Promise = require('bluebird') +var glob = require('glob') + +var internals = { + constants: { + ABIBAO_CONST_TOKEN_AUTH_ME: 'auth_me', + ABIBAO_CONST_TOKEN_FINGERPRINT: 'fingerprint', + ABIBAO_CONST_TOKEN_EMAIL_VERIFICATION: 'email_verification', + ABIBAO_CONST_TOKEN_CAMPAIGN_PUBLISH: 'campaign_publish', + ABIBAO_CONST_TOKEN_ABIBAO_CAMPAIGN_PUBLISH_AUTO: 'abibao_campaign_publish_auto', + ABIBAO_CONST_ENTITY_TYPE_NONE: 'none', + ABIBAO_CONST_ENTITY_TYPE_ABIBAO: 'abibao', + ABIBAO_CONST_ENTITY_TYPE_CHARITY: 'charity', + ABIBAO_CONST_ENTITY_TYPE_COMPANY: 'company', + ABIBAO_CONST_USER_SCOPE_ADMINISTRATOR: 'administrator', + ABIBAO_CONST_USER_SCOPE_INDIVIDUAL: 'individual' + }, + events: { }, + domain: false +} + +var _ = require('lodash') +var Cryptr = require('cryptr') +var cryptr = new Cryptr(global.ABIBAO.config('ABIBAO_API_GATEWAY_CRYPTO_CREDENTIALS')) + +internals.initialize = function () { + global.ABIBAO.debuggers.domain('start initializing') + return new Promise(function (resolve, reject) { + internals.domain.dictionnary = [] + internals.domain.thinky = require('./../connections/thinky') + internals.domain.knex = require('./../connections/knex')() + internals.domain.injector = internals.injector + internals.domain.execute = internals.execute + internals.domain.getIDfromURN = function (urn) { + return cryptr.decrypt(_.last(_.split(urn, ':'))) + } + internals.domain.getURNfromID = function (id, model) { + return 'urn:abibao:database:' + model + ':' + cryptr.encrypt(id) + } + /* internals.domain.databases = { + mvp: require('./models/sequelize/mvp') + } */ + Promise.all([ + // internals.domain.databases.mvp.sequelize.authenticate(), + internals.domain.injector('commands'), + internals.domain.injector('queries'), + internals.domain.injector('models/mysql'), + internals.domain.injector('models/rethinkdb'), + // internals.domain.databases.mvp.sequelize.sync(), + internals.domain.AnswerModel(internals.domain.knex), + internals.domain.UserModel(internals.domain.knex), + internals.domain.VoteSMFModel(internals.domain.knex), + internals.domain.SendgridBounceModel(internals.domain.knex) + ]) + .then(() => { + resolve() + }) + .catch(reject) + }) +} + +module.exports.singleton = function () { + return new Promise(function (resolve, reject) { + if (internals.domain !== false) { resolve() } + internals.domain = { } + internals.initialize() + .then(function () { + global.ABIBAO.services.domain = internals.domain + global.ABIBAO.events.DomainEvent = internals.events + global.ABIBAO.constants.DomainConstant = internals.constants + resolve() + }) + .catch(function (error) { + internals.domain = false + global.ABIBAO.debuggers.error(error) + reject(error) + }) + }) +} + +var async = require('async') +var path = require('path') +var uuid = require('node-uuid') + +internals.injector = function (type) { + var self = internals.domain + return new Promise(function (resolve) { + global.ABIBAO.debuggers.domain('[' + _.upperFirst(_.camelCase(type)) + ']') + var patternPath = path.resolve(__dirname, type) + '/**/*.js' + var patternFiles = glob.sync(patternPath, { + nodir: true, + dot: true, + ignore: ['index.js'] + }) + async.mapSeries(patternFiles, function (file, next) { + var name = path.basename(file, '.js') + global.ABIBAO.debuggers.domain('>>> [' + _.upperFirst(_.camelCase(name)) + '] has just being injected') + switch (type) { + case 'models/rethinkdb': + self[name] = require(file)(self.thinky) + break + default: + self[name] = require(file) + } + next(null, true) + }, function () { + resolve() + }) + }) +} + +internals.execute = function (type, promise, params) { + return new Promise(function (resolve, reject) { + var starttime = new Date() + var data = { + uuid: uuid.v1(), + environnement: global.ABIBAO.config('ABIBAO_API_GATEWAY_ENV'), + type: type, + promise: promise + } + global.ABIBAO.debuggers.domain('[%s] start %s %s %o', data.uuid, type, promise, params) + global.ABIBAO.services.domain[promise](params) + .then(function (result) { + data.exectime = new Date() - starttime + // loggers: info + global.ABIBAO.logger.info(data) + // debuggers + global.ABIBAO.debuggers.domain('[%s] finish %s %s', data.uuid, type, promise) + // return + resolve(result) + }) + .catch(function (error) { + data.exectime = new Date() - starttime + data.error = error + // loggers:: error + global.ABIBAO.logger.error(data) + // debuggers + global.ABIBAO.debuggers.error('[%s] finish %s %s %o', data.uuid, type, promise, error) + // return + reject(error) + }) + }) +} diff --git a/pool/shard001/JavaScript/0006398_setup.js b/pool/shard001/JavaScript/0006398_setup.js new file mode 100644 index 0000000000000000000000000000000000000000..2dd2baf037851a0dafb19419e8dec890fb17dc93 --- /dev/null +++ b/pool/shard001/JavaScript/0006398_setup.js @@ -0,0 +1,124 @@ +var http = require('http'); +var httpProxy = require('http-proxy'); +var debug = require('debug')('zuul:setup'); + +var user_server = require('./user-server'); + +// sets up a test instance +// cb(err, instance) +// instance.shutdown() terminates the instance +function setup_test_instance(opt, cb) { + + var support_server = undefined; + var bouncer = undefined; + var Tunnel; + if (typeof opt.tunnel === 'string') { + Tunnel = require('zuul-' + opt.tunnel); + debug('using zuul-%s to tunnel', opt.tunnel); + } else if (typeof opt.tunnel === 'object' && opt.tunnel.type) { + Tunnel = require('zuul-' + opt.tunnel.type); + debug('using zuul-%s to tunnel', opt.tunnel.type); + } else { + Tunnel = require('zuul-localtunnel'); + debug('using zuul-localhost to tunnel'); + } + + var tunnel = new Tunnel(opt); + + if (opt.server) { + user_server(opt.server, setup); + } + else { + setup(); + } + + function setup(_support_server) { + support_server = _support_server; + var config = opt; + var control_port = opt.control_port; + + var support_port = undefined; + if (support_server) { + support_port = config.support_port = support_server.port; + } + + // TODO start support server + // currently happens within user_server + + var bouncer_port = 0; + if (config.local && parseInt(config.local)) { + bouncer_port = config.local; + } + + if (config.phantom && parseInt(config.phantom)) { + bouncer_port = config.phantom; + } + + var proxy = httpProxy.createProxy(); + proxy.on('proxyReq', on_proxy_req); + + bouncer = http.createServer(); + bouncer.on('request', on_request(proxy.web)); + bouncer.on('upgrade', on_request(proxy.ws)); + + function on_request(bounce) { + return function(req, res) { + var args = [].slice.call(arguments); + if (is_control_req(req)) { + args.push({ target: 'http://localhost:' + control_port }); + bounce.apply(proxy, args); + return; + } + + args.push({ target: 'http://localhost:' + support_port }, on_support_server_proxy_done); + bounce.apply(proxy, args); + }; + } + + function on_proxy_req(proxyReq, req, res, options) { + if (is_control_req(req) || + (req.headers.connection && req.headers.connection.toLowerCase().indexOf('upgrade') === -1)) { + proxyReq.setHeader('connection', 'close'); + } + } + + function on_support_server_proxy_done(err, req, res) { + if (err.code === 'ECONNRESET' && res && res.socket && res.socket.destroyed === true) { + debug('Request to support-server:%s was canceled by the client, ignoring the proxy error'); + } + } + + function is_control_req(req) { + var url = req.url.split('?')[0]; + return !support_port || url.split('/')[1] === '__zuul'; + } + + bouncer.listen(bouncer_port, bouncer_active); + + function bouncer_active() { + var app_port = bouncer.address().port; + debug('bouncer active on port %d', app_port); + + if (!config.tunnel) { + return cb(null, 'http://localhost:' + app_port + '/__zuul'); + } + + tunnel.connect(app_port, cb); + }; + } + + function shutdown() { + bouncer.close(); + tunnel.close(); + + if (support_server) { + support_server.process.kill('SIGKILL'); + } + } + + return { + shutdown: shutdown + }; +} + +module.exports = setup_test_instance; diff --git a/pool/shard001/JavaScript/0006403_amp-story-cta-layer.js b/pool/shard001/JavaScript/0006403_amp-story-cta-layer.js new file mode 100644 index 0000000000000000000000000000000000000000..fcdc9227228dd5048261699fdf1dc4ac1cc1ca1d --- /dev/null +++ b/pool/shard001/JavaScript/0006403_amp-story-cta-layer.js @@ -0,0 +1,86 @@ +/** + * @fileoverview This is a layer that allows a call to action in a story page. + * With this, a user could link to an external site from inside a story using + * the call to action layer, for example. + * + * Example: + * ... + * + * + * Visit my site! + * + * + * ... + */ + +import {AmpStoryBaseLayer} from './amp-story-base-layer'; +import {addAttributesToElement, removeElement} from '#core/dom'; +import {dict} from '#core/types/object'; +import {matches} from '#core/dom/query'; +import {user} from '#utils/log'; + +/** + * @type {string} + * @const + */ +const TAG = 'amp-story-cta-layer'; + +/** + * Call to action button layer template. + * + * No pre-rendering to let more computing-intensive elements (like + * videos) get pre-rendered first. Since this layer will not contain + * computing-intensive resources such as videos, we can just risk rendering + * while the user is looking. + */ +export class AmpStoryCtaLayer extends AmpStoryBaseLayer { + /** @override */ + buildCallback() { + super.buildCallback(); + this.setOrOverwriteAttributes_(); + this.checkAndRemoveLayerIfOnFirstPage_(); + } + + /** + * Overwrite or set target attributes that are cta-layer-specific. + * @private + */ + setOrOverwriteAttributes_() { + const ctaLinks = this.element.querySelectorAll('a'); + for (let i = 0; i < ctaLinks.length; i++) { + addAttributesToElement(ctaLinks[i], dict({'target': '_blank'})); + + if (!ctaLinks[i].getAttribute('role')) { + addAttributesToElement(ctaLinks[i], dict({'role': 'link'})); + } + } + + const ctaButtons = this.element.querySelectorAll('button'); + for (let i = 0; i < ctaButtons.length; i++) { + if (!ctaButtons[i].getAttribute('role')) { + addAttributesToElement(ctaButtons[i], dict({'role': 'button'})); + } + } + } + + /** + * CTA links or buttons are not allowed on the first amp-story page. Remove + * the amp-story-cta-layer if it is found on the first page of the story. + * @private + */ + checkAndRemoveLayerIfOnFirstPage_() { + if ( + matches( + this.element, + 'amp-story-page:first-of-type > amp-story-cta-layer' + ) + ) { + removeElement(this.element); + user().error( + TAG, + 'amp-story-cta-layer is not allowed on the first page' + + ' of an amp-story.' + ); + } + } +} diff --git a/pool/shard001/JavaScript/0006404_cli.js b/pool/shard001/JavaScript/0006404_cli.js new file mode 100644 index 0000000000000000000000000000000000000000..b92e944bdce3faac7ca912c74976d53823914420 --- /dev/null +++ b/pool/shard001/JavaScript/0006404_cli.js @@ -0,0 +1,248 @@ +#!/usr/bin/env node + +const fs = require('fs'); +const path = require('path'); +const chalk = require('chalk'); +const Table = require('cli-table'); +const _async = require('async'); +const updateNotifier = require('update-notifier'); + +const theGit = require('git-state'); +const { Spinner } = require('cli-spinner'); +const argv = require('minimist')(process.argv.slice(2)); + +const pkg = require('./package'); +const C = require('./src/constants'); +const { printHelp } = require('./src/functions'); + +const NOOP = () => {}; + +const showGitOnly = argv.gitonly || argv.g; +const dirs = argv._.length ? argv._ : [process.cwd()]; +const debug = Boolean(argv.debug) ? console.log : NOOP; + +let spinner = null; +let table = null; +let cwd = null; +let fileIndex = 0; +let statuses = []; +let compact = false; + +const linePrinter = console.log; + +updateNotifier({ + pkg: pkg, + updateCheckInterval: C.updateInterval * C.daysMultiplier, +}).notify(); + +process.on('uncaughtException', (err) => { + linePrinter(`Caught exception: ${err}`); + process.exit(); +}); + +if (argv.version || argv.v) { + linePrinter(pkg.version); + process.exit(); +} + +if (argv.help || argv.h) { + printHelp(linePrinter); + process.exit(); +} + +if (argv.compact || argv.c) { + compact = argv.compact || argv.c; +} + +function hasAskedForCompact() { + return compact && compact === 's'; +} + +function hasAskedForVeryCompact() { + return compact && compact === 'so'; +} + +function getTableHeader(type, color) { + if (!color) { + color = 'cyan'; + } + return C.columnsOrder.map((key) => chalk[color](C.headers[key][type])); +} + +function init() { + //either passed from CLI or take the current directory + cwd = dirs[0]; + + //Spinners + spinner = new Spinner('%s'); + spinner.setSpinnerString(18); + spinner.start(); + + //Console Tables + let tableOpts = {}; + tableOpts = { + head: getTableHeader('long'), + }; + + if (compact) { + if (hasAskedForCompact() || hasAskedForVeryCompact()) { + tableOpts.head = getTableHeader('short'); + } + tableOpts.chars = { + mid: '', + 'left-mid': '', + 'mid-mid': '', + 'right-mid': '', + }; + } + return new Table(tableOpts); +} + +function prettyPath(pathString) { + let p = pathString.split(path.sep); + return p[p.length - 1]; +} + +function processDirectory(stat, callback) { + fileIndex++; + let pathString = path.join(cwd, stat.file); + if (stat.stat.isDirectory()) { + debug(fileIndex, stat.file); + theGit.isGit(pathString, function (isGit) { + if (isGit) { + theGit.check(pathString, function (e, gitStatus) { + if (e) return callback(e); + gitStatus.git = true; + debug(stat.file, gitStatus); + insert(pathString, gitStatus); + return callback(null, true); + }); + } else { + const gitStatus = C.emptyGitStatus; + debug(stat.file, gitStatus); + if (!showGitOnly) { + insert(pathString, gitStatus); + } + return callback(null, false); + } + }); + } else { + debug(stat.file, false); + return callback(null, false); + } +} + +function insert(pathString, status) { + let directoryName = prettyPath(pathString); + status.directory = directoryName; + statuses.push(status); + + // TODO: refactor + let methodName = + status.dirty === 0 + ? status.ahead === 0 + ? status.untracked === 0 + ? 'grey' + : 'yellow' + : 'green' + : 'red'; + + if (!((argv.attention || argv.a) && methodName === 'grey')) { + table.push( + C.columnsOrder.map((key) => + key === 'directory' + ? directoryName + : checkAndGetEmptyString(status, key, methodName) + ) + ); + } +} + +function checkAndGetEmptyString(status, key, methodName) { + return chalk[methodName](status[key] || '-'); +} + +function simpleStatus(status) { + //simple comma and newline separated output for machine readability + let str = []; + for (let i = 0; i < C.simple.length; i++) { + str.push(status[C.simple[i]]); + } + console.log(str.join(',')); +} + +function simple() { + for (let i = 0; i < statuses.length; i++) { + simpleStatus(statuses[i]); + } +} + +function finish() { + spinner.stop(); + process.stdout.clearLine(); // clear current text + process.stdout.cursorTo(0); // move cursor to beginning of line + + if (argv.sort) { + table.sort((a, b) => { + if (a[0] < b[0]) { + return -1; + } + if (a[0] > b[0]) { + return 1; + } + return 0; + }); + } + + if (argv.simple || argv.s) { + simple(); + } else { + if (!chalk.supportsColor) { + console.log(chalk.stripColor(table.toString())); + } else { + console.log(table.toString()); + } + } + if (compact) { + let str = []; + Object.keys(C.headers).map(function (key) { + let header = C.headers[key]; + str.push(chalk.cyan(header.short) + ': ' + header.long); + }); + if (!hasAskedForVeryCompact()) { + console.log(str.join(', ') + '\n'); + } + } +} + +const listRepos = () => { + table = init(dirs); + linePrinter(chalk.green(cwd)); + + fs.readdir(cwd, function (err, files) { + if (err) { + throw err; + } + _async.map( + files, + function (file, statCallback) { + fs.stat(path.join(cwd, file), function (err, stat) { + if (err) return statCallback(err); + statCallback(null, { + file: file, + stat: stat, + }); + }); + }, + function (err, statuses) { + if (err) throw new Error(err); + debug(statuses.length); + _async.filter(statuses, processDirectory, function () { + finish(); + }); + } + ); + }); +}; + +listRepos(); diff --git a/pool/shard001/JavaScript/0006405_help.js b/pool/shard001/JavaScript/0006405_help.js new file mode 100644 index 0000000000000000000000000000000000000000..a52d77180a1954ae172a02165c3e0b6148b2e4fd --- /dev/null +++ b/pool/shard001/JavaScript/0006405_help.js @@ -0,0 +1,21 @@ +module.exports = function(controller) { + + + // This before middleware allows the help command to accept sub-thread names as a parameter + // so users can say help to get the default thread, but help will automatically + // jump to that subthread (if it exists) + controller.studio.before('help', function(convo, next) { + + // is there a parameter on the help command? + // if so, change topic. + if (matches = convo.source_message.text.match(/^help (.*)/i)) { + if (convo.hasThread(matches[1])) { + convo.gotoThread(matches[1]); + } + } + + next(); + + }); + +} diff --git a/pool/shard001/JavaScript/0006408_ProgramTransformer.js b/pool/shard001/JavaScript/0006408_ProgramTransformer.js new file mode 100644 index 0000000000000000000000000000000000000000..1ab6688b5f5c05ed7f607055349ce766876e93a8 --- /dev/null +++ b/pool/shard001/JavaScript/0006408_ProgramTransformer.js @@ -0,0 +1,266 @@ +// Copyright 2012 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. + +import ArrayComprehensionTransformer from 'ArrayComprehensionTransformer.js'; +import ArrowFunctionTransformer from 'ArrowFunctionTransformer.js'; +import AtNameMemberTransformer from 'AtNameMemberTransformer.js'; +import BlockBindingTransformer from 'BlockBindingTransformer.js'; +import CascadeExpressionTransformer from 'CascadeExpressionTransformer.js'; +import ClassTransformer from 'ClassTransformer.js'; +import CollectionTransformer from 'CollectionTransformer.js'; +import DefaultParametersTransformer from 'DefaultParametersTransformer.js'; +import DestructuringTransformer from 'DestructuringTransformer.js'; +import ForOfTransformer from 'ForOfTransformer.js'; +import FreeVariableChecker from '../semantics/FreeVariableChecker.js'; +import GeneratorComprehensionTransformer from + 'GeneratorComprehensionTransformer.js'; +import GeneratorTransformPass from 'GeneratorTransformPass.js'; +import IsExpressionTransformer from 'IsExpressionTransformer.js'; +import ModuleTransformer from 'ModuleTransformer.js'; +import ObjectLiteralTransformer from 'ObjectLiteralTransformer.js'; +import ObjectMap from '../util/ObjectMap.js'; +import ParseTreeValidator from '../syntax/ParseTreeValidator.js'; +import PrivateNameSyntaxTransformer from 'PrivateNameSyntaxTransformer.js'; +import PropertyNameShorthandTransformer from + 'PropertyNameShorthandTransformer.js'; +import TemplateLiteralTransformer from 'TemplateLiteralTransformer.js'; +import RestParameterTransformer from 'RestParameterTransformer.js'; +import SpreadTransformer from 'SpreadTransformer.js'; +import TypeTransformer from 'TypeTransformer.js'; +import {options, transformOptions} from '../options.js'; + +/** + * Transforms a Traceur file's ParseTree to a JS ParseTree. + */ +export class ProgramTransformer { + /** + * @param {ErrorReporter} reporter + * @param {Project} project + */ + constructor(reporter, project) { + this.project_ = project; + this.reporter_ = reporter; + this.results_ = new ObjectMap(); + } + + /** + * @return {void} + * @private + */ + transform_() { + this.project_.getSourceFiles().forEach((file) => { + this.transformFile_(file); + }); + } + + /** + * @param {SourceFile} file + * @return {void} + * @private + */ + transformFile_(file) { + var result = this.transform(this.project_.getParseTree(file)); + this.results_.set(file, result); + } + + /** + * @param {ModuleSymbol} module + * @param {SourceFile} file + * @return {void} + * @private + */ + transformFileAsModule_(module, file) { + var result = this.transformTree_(this.project_.getParseTree(file), + module); + this.results_.set(file, result); + } + + /** + * This is the root of the code generation pass. + * Each pass translates one contruct from Traceur to standard JS constructs. + * The order of the passes matters. + * + * @param {Program} tree + * @return {ParseTree} + */ + transform(tree) { + return this.transformTree_(tree); + } + + transformTree_(tree, opt_module) { + var identifierGenerator = this.project_.identifierGenerator; + var runtimeInliner = this.project_.runtimeInliner; + var reporter = this.reporter_; + + function chain(enabled, transformer, ...args) { + if (!enabled) + return; + + if (!reporter.hadError()) { + if (options.validate) { + ParseTreeValidator.validate(tree); + } + + tree = transformer(...args, tree) || tree; + } + } + + // TODO: many of these simple, local transforms could happen in the same + // tree pass + + chain(transformOptions.types, TypeTransformer.transformTree); + + chain(transformOptions.templateLiterals, + TemplateLiteralTransformer.transformTree, + identifierGenerator); + + chain(transformOptions.modules, this.transformModules_.bind(this), tree, + opt_module); + + chain(transformOptions.arrowFunctions, + ArrowFunctionTransformer.transformTree, reporter); + + // ClassTransformer needs to come before ObjectLiteralTransformer. + chain(transformOptions.classes, ClassTransformer.transform, + identifierGenerator, runtimeInliner, reporter); + + chain(transformOptions.propertyNameShorthand, + PropertyNameShorthandTransformer.transformTree); + chain(transformOptions.propertyMethods || + transformOptions.privateNameSyntax && + transformOptions.privateNames, + ObjectLiteralTransformer.transformTree, identifierGenerator); + + chain(transformOptions.isExpression, IsExpressionTransformer.transformTree); + + // Generator/ArrayComprehensionTransformer must come before for-of and + // destructuring. + chain(transformOptions.generatorComprehension, + GeneratorComprehensionTransformer.transformTree, + identifierGenerator); + chain(transformOptions.arrayComprehension, + ArrayComprehensionTransformer.transformTree, + identifierGenerator); + + // for of must come before destructuring and generator, or anything + // that wants to use VariableBinder + chain(transformOptions.forOf, ForOfTransformer.transformTree, + identifierGenerator); + + // rest parameters must come before generator + chain(transformOptions.restParameters, + RestParameterTransformer.transformTree, identifierGenerator); + + // default parameters should come after rest parameter to get the + // expected order in the transformed code. + chain(transformOptions.defaultParameters, + DefaultParametersTransformer.transformTree); + + // destructuring must come after for of and before block binding and + // generator + chain(transformOptions.destructuring, + DestructuringTransformer.transformTree, identifierGenerator); + + // generator must come after for of and rest parameters + chain(transformOptions.generators || transformOptions.deferredFunctions, + GeneratorTransformPass.transformTree, + identifierGenerator, + reporter); + + chain(transformOptions.privateNames && transformOptions.privateNameSyntax, + AtNameMemberTransformer.transformTree, + identifierGenerator); + + chain(transformOptions.privateNames && transformOptions.privateNameSyntax, + PrivateNameSyntaxTransformer.transformTree, + identifierGenerator); + + chain(transformOptions.spread, SpreadTransformer.transformTree, + identifierGenerator, runtimeInliner); + + chain(true, runtimeInliner.transformAny.bind(runtimeInliner)); + + chain(transformOptions.blockBinding, BlockBindingTransformer.transformTree); + + // Cascade must come before CollectionTransformer. + chain(transformOptions.cascadeExpression, + CascadeExpressionTransformer.transformTree, + identifierGenerator, + reporter); + + chain(transformOptions.trapMemberLookup || transformOptions.privateNames, + CollectionTransformer.transformTree, + identifierGenerator); + + // Issue errors for any unbound variables + chain(options.freeVariableChecker, + FreeVariableChecker.checkProgram, reporter); + + return tree; + } + + /** + * Transforms a program tree. If an optional module is passed in the + * program is treated as a module body. + * @param {Program} tree + * @param {ModuleSymbol} module + * @return {Program} + * @private + */ + transformModules_(tree, opt_module) { + if (opt_module) { + return ModuleTransformer.transformAsModule(this.project_, opt_module, + tree); + } else { + return ModuleTransformer.transform(this.project_, tree); + } + } +} + +/** + * @param {ErrorReporter} reporter + * @param {Project} project + * @return {ObjectMap} + */ +ProgramTransformer.transform = function(reporter, project) { + var transformer = new ProgramTransformer(reporter, project); + transformer.transform_(); + return transformer.results_; +}; + +/** + * @param {ErrorReporter} reporter + * @param {Project} project + * @param {SourceFile} sourceFile + * @return {ObjectMap} + */ +ProgramTransformer.transformFile = function(reporter, project, sourceFile) { + var transformer = new ProgramTransformer(reporter, project); + transformer.transformFile_(sourceFile); + return transformer.results_; +}; + +/** + * @param {ErrorReporter} reporter + * @param {Project} project + * @param {ModuleSymbol} + * @param {SourceFile} sourceFile + * @return {ObjectMap} + */ +ProgramTransformer.transformFileAsModule = function(reporter, project, + module, sourceFile) { + var transformer = new ProgramTransformer(reporter, project); + transformer.transformFileAsModule_(module, sourceFile); + return transformer.results_; +}; diff --git a/pool/shard001/JavaScript/0006409_12-parents.js b/pool/shard001/JavaScript/0006409_12-parents.js new file mode 100644 index 0000000000000000000000000000000000000000..d53a1f5599772874b3c73cc356a9bcf69c25f2e4 --- /dev/null +++ b/pool/shard001/JavaScript/0006409_12-parents.js @@ -0,0 +1,59 @@ +// Один-ко-многим: Вывод юзера с детьми + +const mongoose = require('mongoose'); +mongoose.Promise = Promise; + +mongoose.set('debug', true); + +mongoose.connect('mongodb://localhost/test'); + +const userSchema = new mongoose.Schema({ + email: { + type: String, + required: 'Укажите email', // true for default message + unique: true + }, + parent: { + type: mongoose.Schema.Types.ObjectId, + ref: 'User' + } +}, { + toJSON: { + virtuals: true + }, + toObject: { + virtuals: true // for console.log, to output children + } +}); + +userSchema.virtual('children', { + ref: 'User', // The model to use + localField: '_id', // Find people where `localField` + foreignField: 'parent' // is equal to `foreignField` +}); + +const User = mongoose.model('User', userSchema); + +(async () => { + + await User.remove({}); + + let pete = await User.create({email: 'pete@gmail.com'}); + + await User.create({ + email: 'john@gmail.com', + parent: pete + }); + + await User.create({ + email: 'ann@gmail.com', + parent: pete + }); + + pete = await User.findOne({ + email: 'pete@gmail.com' + }).populate('children'); + + console.log(pete); + +})().catch(console.error).then(() => mongoose.disconnect()); diff --git a/pool/shard001/JavaScript/0006410_editor_plugin_src.js b/pool/shard001/JavaScript/0006410_editor_plugin_src.js new file mode 100644 index 0000000000000000000000000000000000000000..aa61a49b3a48120b1d87920480eb65555c9f3648 --- /dev/null +++ b/pool/shard001/JavaScript/0006410_editor_plugin_src.js @@ -0,0 +1,136 @@ +/** + * $Id$ + * + * @author Moxiecode + * @copyright Copyright � 2004-2008, Moxiecode Systems AB, All rights reserved. + */ + +(function() { + tinymce.create('tinymce.plugins.XHTMLXtrasPlugin', { + init : function(ed, url) { + // Register commands + ed.addCommand('mceCite', function() { + ed.windowManager.open({ + file : url + '/cite.htm', + width : 350 + parseInt(ed.getLang('xhtmlxtras.cite_delta_width', 0)), + height : 250 + parseInt(ed.getLang('xhtmlxtras.cite_delta_height', 0)), + inline : 1 + }, { + plugin_url : url + }); + }); + + ed.addCommand('mceAcronym', function() { + ed.windowManager.open({ + file : url + '/acronym.htm', + width : 350 + parseInt(ed.getLang('xhtmlxtras.acronym_delta_width', 0)), + height : 250 + parseInt(ed.getLang('xhtmlxtras.acronym_delta_width', 0)), + inline : 1 + }, { + plugin_url : url + }); + }); + + ed.addCommand('mceAbbr', function() { + ed.windowManager.open({ + file : url + '/abbr.htm', + width : 350 + parseInt(ed.getLang('xhtmlxtras.abbr_delta_width', 0)), + height : 250 + parseInt(ed.getLang('xhtmlxtras.abbr_delta_width', 0)), + inline : 1 + }, { + plugin_url : url + }); + }); + + ed.addCommand('mceDel', function() { + ed.windowManager.open({ + file : url + '/del.htm', + width : 340 + parseInt(ed.getLang('xhtmlxtras.del_delta_width', 0)), + height : 310 + parseInt(ed.getLang('xhtmlxtras.del_delta_width', 0)), + inline : 1 + }, { + plugin_url : url + }); + }); + + ed.addCommand('mceIns', function() { + ed.windowManager.open({ + file : url + '/ins.htm', + width : 340 + parseInt(ed.getLang('xhtmlxtras.ins_delta_width', 0)), + height : 310 + parseInt(ed.getLang('xhtmlxtras.ins_delta_width', 0)), + inline : 1 + }, { + plugin_url : url + }); + }); + + ed.addCommand('mceAttributes', function() { + ed.windowManager.open({ + file : url + '/attributes.htm', + width : 380, + height : 370, + inline : 1 + }, { + plugin_url : url + }); + }); + + // Register buttons + ed.addButton('cite', {title : 'xhtmlxtras.cite_desc', cmd : 'mceCite'}); + ed.addButton('acronym', {title : 'xhtmlxtras.acronym_desc', cmd : 'mceAcronym'}); + ed.addButton('abbr', {title : 'xhtmlxtras.abbr_desc', cmd : 'mceAbbr'}); + ed.addButton('del', {title : 'xhtmlxtras.del_desc', cmd : 'mceDel'}); + ed.addButton('ins', {title : 'xhtmlxtras.ins_desc', cmd : 'mceIns'}); + ed.addButton('attribs', {title : 'xhtmlxtras.attribs_desc', cmd : 'mceAttributes'}); + + if (tinymce.isIE) { + function fix(ed, o) { + if (o.set) { + o.content = o.content.replace(/]+)>/gi, ''); + o.content = o.content.replace(/<\/abbr>/gi, ''); + } + }; + + ed.onBeforeSetContent.add(fix); + ed.onPostProcess.add(fix); + } + + ed.onNodeChange.add(function(ed, cm, n, co) { + n = ed.dom.getParent(n, 'CITE,ACRONYM,ABBR,DEL,INS'); + + cm.setDisabled('cite', co); + cm.setDisabled('acronym', co); + cm.setDisabled('abbr', co); + cm.setDisabled('del', co); + cm.setDisabled('ins', co); + cm.setDisabled('attribs', n && n.nodeName == 'BODY'); + cm.setActive('cite', 0); + cm.setActive('acronym', 0); + cm.setActive('abbr', 0); + cm.setActive('del', 0); + cm.setActive('ins', 0); + + // Activate all + if (n) { + do { + cm.setDisabled(n.nodeName.toLowerCase(), 0); + cm.setActive(n.nodeName.toLowerCase(), 1); + } while (n = n.parentNode); + } + }); + }, + + getInfo : function() { + return { + longname : 'XHTML Xtras Plugin', + author : 'Moxiecode Systems AB', + authorurl : 'http://tinymce.moxiecode.com', + infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/xhtmlxtras', + version : tinymce.majorVersion + "." + tinymce.minorVersion + }; + } + }); + + // Register plugin + tinymce.PluginManager.add('xhtmlxtras', tinymce.plugins.XHTMLXtrasPlugin); +})(); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006411_ui.js b/pool/shard001/JavaScript/0006411_ui.js new file mode 100644 index 0000000000000000000000000000000000000000..9cd5f1343c8208a750a2ffb57ffcdcbc4aaa5f55 --- /dev/null +++ b/pool/shard001/JavaScript/0006411_ui.js @@ -0,0 +1,73 @@ +(function($) { + +/** + * @file ui.js + * + * "Global" UI components: toggle, modal. + */ + +Drupal.edit = Drupal.edit || {}; + + +Drupal.edit.toggle = { + render: function() { + // TODO: fancy, "physical toggle" to switch from view to edit mode and back. + } +}; + + +Drupal.edit.modal = { + create: function(message, actions, $editable) { + // The modal should be the only interaction element now. + $editable + .add(Drupal.edit.toolbar.get($editable)) + .addClass('edit-belowoverlay'); + + $(Drupal.theme('editModal', {})) + .appendTo('body') + .find('.main p').text(message).end() + .find('.actions').append($(actions)) + .delegate('a.discard', 'click.edit', function() { + // Restore to original state. + $editable.html($editable.data('edit-content-original')); + $editable.data('edit-content-changed', false); + + Drupal.edit.modal.remove(); + Drupal.edit.toolbar.get($editable).find('a.close').trigger('click.edit'); + return false; + }) + .delegate('a.save', 'click.edit', function() { + Drupal.edit.modal.remove(); + Drupal.edit.toolbar.get($editable).find('a.save').trigger('click.edit'); + return false; + }); + }, + + get: function() { + return $('#edit-modal'); + }, + + remove: function() { + var $modal = Drupal.edit.modal.get(); + + // Remove after animation. + $modal + .addClass('edit-animate-invisible') + .bind(Drupal.edit.const.transitionEnd, function(e) { + $modal.remove(); + + // The modal's HTML was removed, hence no need to undelegate it. + }); + + // Make the other interaction elements available again. + $('.edit-belowoverlay').removeClass('edit-belowoverlay'); + }, + + // Animate into view. + show: function() { + Drupal.edit.modal.get() + .removeClass('edit-animate-invisible'); + } +}; + +})(jQuery); diff --git a/pool/shard001/JavaScript/0006413_conf.js b/pool/shard001/JavaScript/0006413_conf.js new file mode 100644 index 0000000000000000000000000000000000000000..87f7bd6bb0edba94f92db60724d78a0d481b6762 --- /dev/null +++ b/pool/shard001/JavaScript/0006413_conf.js @@ -0,0 +1,50 @@ +exports.config = { + seleniumAddress: 'http://localhost:4444/wd/hub', + baseUrl: 'https://localhost',//set dynamically in onPrepare + specs: [ + 'install-spec.js', + 'login-spec.js', + '../../temp/kajona/core*/module_*/tests/selenium/*-spec.js', + '../../temp/kajona/files/extract/module_*/tests/selenium/*-spec.js' + ], + capabilities: { + browserName: 'chrome', + chromeOptions: { + args: ['--no-sandbox'] + } + }, + jasmineNodeOpts: { + defaultTimeoutInterval: 480000 // 8 minutes + }, + plugins: [ + { + package: 'protractor-screenshoter-plugin', + screenshotPath: '../build/screenshots', + clearFoldersBeforeTest: true + }], + onPrepare: function () { + + /** base path of the selenium */ + const strBasePath = __dirname + '/../../temp/kajona/core/_buildfiles/jstests/selenium'; + + /** If you are testing against a non-angular site - set ignoreSynchronization setting to true */ + browser.ignoreSynchronization = true; + + + /**add requireHelper to global variable */ + global.requireHelper = function (relativePath) {// "relativePath" - path, relative to "basePath" variable + return require(strBasePath + relativePath); + }; + + /** Set baseUrl dynamically */ + const path = require('path'); + const strPathToProject = path.join(__dirname, "/../../../../");//path to project folder + const strProjectName = path.basename(strPathToProject);//determine project folder name + browser.baseUrl = browser.baseUrl + "/" + strProjectName + "/core/_buildfiles/temp/kajona"; + + // returning the promise makes protractor wait for the reporter config before executing tests + return global.browser.getProcessedConfig().then(function (config) { + //it is ok to be empty + }); + } +}; diff --git a/pool/shard001/JavaScript/0006419_main.js b/pool/shard001/JavaScript/0006419_main.js new file mode 100644 index 0000000000000000000000000000000000000000..b0e0da130eac0635477f1ae06ae865100dcdf0fc --- /dev/null +++ b/pool/shard001/JavaScript/0006419_main.js @@ -0,0 +1,139 @@ +$(function(){ + $(window).scroll(function(){ + if ($(this).scrollTop() > 200) { + $('.navbar-inverse').fadeIn(500); + } else { + $('.navbar-inverse').fadeOut(500); + } + }); + + + $('#video-container').click(function(){ + $('#video-container').html(''); + setAspectRatio(); + }); + + // Auto-resize the video player to proper aspect ratio. + function setAspectRatio() { + $('#video-container iframe').each(function() { + $(this).innerHeight($(this).innerWidth() * 9/16); + }); + } + $(window).resize(setAspectRatio); + + /* ================================ + Social counts + ================================= */ + + var shareUrl = 'https://fight215.org/'; // window.location.href; + // If the share buttons widget is visible, lets load some values + if($('#share-buttons').length > 0) { + function updateCount() { + $.ajax('https://act.eff.org/tools/social_buttons_count?url=' + shareUrl, { + success: function(res, err) { + $.each(res, function(network, value) { + var count = value; + if (count / 10000 > 1) { + count = Math.ceil(count / 1000) + 'k'; + } + $('[data-network="' + network + '"]').attr('count', count).hide().show(); + }); + }, + dataType: 'json', + cache: true + }); + } + updateCount(); + setInterval(updateCount, 60000); + + $( ".facebook-button" ).click(function() { + var url = $(this).attr("href"); + window.open(url, "Share on Facebook", "width=650,height=500"); + return false; + }); + $( ".twitter-button" ).click(function() { + var url = $(this).attr("href"); + window.open(url,"Twitter","width=550,height=420"); + return false; + }); + $( ".google-button" ).click(function() { + var url = $(this).attr("href"); + window.open(url,"Share on Google Plus","width=500,height=436"); + return false; + }); + } + + $('.cta').click(function() { + window.location.href='#call'; + return false; + }); + // $('#tf-phone-number').focus(); + $('#tf-phone-number').mask('(000) 000-0000'); + + function shuffle(array) { + var currentIndex = array.length, temporaryValue, randomIndex; + while (0 !== currentIndex) { + randomIndex = Math.floor(Math.random() * currentIndex); + currentIndex -= 1; + temporaryValue = array[currentIndex]; + array[currentIndex] = array[randomIndex]; + array[randomIndex] = temporaryValue; + } + }; + + var tweets = [ + "Please reject the update to Rule 41 of the Federal Rules of Criminal Procedure.", + "Please reject the update to Rule 41 of the Federal Rules of Criminal Procedure.", + "Please reject the update to Rule 41 of the Federal Rules of Criminal Procedure." + ]; + + var targets = [ + '@ChuckGrassley ', + '@SenateMajLdr ', + '@SenatorReid ', + '@RonWyden ', + ]; + + shuffle(tweets); + for (var i=0; i < tweets.length; i++) { + shuffle(targets); + tweets[i] = 'Dear ' + targets[0] + targets[1] + tweets[i]; + $('#tweets a:eq(' + i.toString() + ')').attr('href', 'https://twitter.com/share?text=' + encodeURIComponent(tweets[i]) + '&url=https%3A%2F%2Ffight215.org'); + $('#tweets p:eq(' + i.toString() + ')').text(tweets[i]); + } + + $('#tweets a').click(function() { + var url = $(this).attr('href'); + window.open(url, 'Twitter', 'width=550,height=420'); + return false; + }); + + $('a[href="#take-action"]').click(function () { + $('html, body').animate({ + scrollTop: $("#take-action").offset().top - 15 + }, 600); + }); + + + + $('a[href="#embed-howto"]').click(function () { + $('html, body').animate({ + scrollTop: $("#embed-howto").offset().top - 15 + }, 600); + }); + + + $('a[href="#background"]').click(function () { + $('html, body').animate({ + scrollTop: $("#background").offset().top - 20 + }, 600); + }); + + // Hide navbar on click. + $('.nav a').on('click', function(){ + if ($('.navbar-toggle').css('display') != 'none') { + $('.navbar-toggle').click(); + } + }); + +}); diff --git a/pool/shard001/JavaScript/0006420_VParallax.spec.js b/pool/shard001/JavaScript/0006420_VParallax.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..f573dfe39fbac0f5b379de9b3fc8502c4254ddb5 --- /dev/null +++ b/pool/shard001/JavaScript/0006420_VParallax.spec.js @@ -0,0 +1,35 @@ +import { test } from '@/test' +import VParallax from '@/components/VParallax' + +test('VParallax.js', ({ mount }) => { + it('should render', async () => { + const wrapper = mount(VParallax, { + attachToDocument: true + }) + + expect(wrapper.html()).toMatchSnapshot() + }) + + it('should use alt tag when supplied', async () => { + const wrapper = mount(VParallax, { + attachToDocument: true, + propsData: { + alt: 'name' + } + }) + + const img = wrapper.find('img')[0] + expect(img.getAttribute('alt')).toBe('name') + expect(wrapper.html()).toMatchSnapshot() + }) + + it('should use empty alt tag when not supplied', async () => { + const wrapper = mount(VParallax, { + attachToDocument: true, + }) + + const img = wrapper.find('img')[0] + expect(img.getAttribute('alt')).toBe('') + expect(wrapper.html()).toMatchSnapshot() + }) +}) diff --git a/pool/shard001/JavaScript/0006424_units.js b/pool/shard001/JavaScript/0006424_units.js new file mode 100644 index 0000000000000000000000000000000000000000..99756b0fa76385fe8f29257a054f351266e9cdb7 --- /dev/null +++ b/pool/shard001/JavaScript/0006424_units.js @@ -0,0 +1,108 @@ +// units + +// load math.js (using node.js) +const math = require('..') + +// units can be created by providing a value and unit name, or by providing +// a string with a valued unit. +console.log('create units') +const a = math.unit(45, 'cm') +const b = math.unit('0.1m') +print(a) // 45 cm +print(b) // 0.1 m +console.log() + +// units can be added, subtracted, and multiplied or divided by numbers and by other units +console.log('perform operations') +print(math.add(a, b)) // 55 cm +print(math.multiply(b, 2)) // 0.2 m +print(math.divide(math.unit('1 m'), math.unit('1 s'))) // 1 m / s +print(math.pow(math.unit('12 in'), 3)) // 1728 in^3 +console.log() + +// units can be converted to a specific type, or to a number +console.log('convert to another type or to a number') +print(b.to('cm')) // 10 cm Alternatively: math.to(b, 'cm') +print(math.to(b, 'inch')) // 3.9370078740157 inch +print(b.toNumber('cm')) // 10 +print(math.number(b, 'cm')) // 10 +console.log() + +// the expression parser supports units too +console.log('parse expressions') +print(math.evaluate('2 inch to cm')) // 5.08 cm +print(math.evaluate('cos(45 deg)')) // 0.70710678118655 +print(math.evaluate('90 km/h to m/s')) // 25 m / s +console.log() + +// convert a unit to a number +// A second parameter with the unit for the exported number must be provided +print(math.evaluate('number(5 cm, mm)')) // number, 50 +console.log() + +// simplify units +console.log('simplify units') +print(math.evaluate('100000 N / m^2')) // 100 kPa +print(math.evaluate('9.81 m/s^2 * 100 kg * 40 m')) // 39.24 kJ +console.log() + +// example engineering calculations +console.log('compute molar volume of ideal gas at 65 Fahrenheit, 14.7 psi in L/mol') +const Rg = math.unit('8.314 N m / (mol K)') +const T = math.unit('65 degF') +const P = math.unit('14.7 psi') +const v = math.divide(math.multiply(Rg, T), P) +console.log('gas constant (Rg) = ', format(Rg)) +console.log('P = ' + format(P)) +console.log('T = ' + format(T)) +console.log('v = Rg * T / P = ' + format(math.to(v, 'L/mol'))) +// 23.910432393453 L / mol +console.log() + +console.log('compute speed of fluid flowing out of hole in a container') +const g = math.unit('9.81 m / s^2') +const h = math.unit('1 m') +const v2 = math.pow(math.multiply(2, math.multiply(g, h)), 0.5) // Can also use math.sqrt +console.log('g = ' + format(g)) +console.log('h = ' + format(h)) +console.log('v = (2 g h) ^ 0.5 = ' + format(v2)) +// 4.42944691807 m / s +console.log() + +console.log('electrical power consumption:') +const expr1 = '460 V * 20 A * 30 days to kWh' +console.log(expr1 + ' = ' + math.evaluate(expr1)) // 6624 kWh +console.log() + +console.log('circuit design:') +const expr2 = '24 V / (6 mA)' +console.log(expr2 + ' = ' + math.evaluate(expr2)) // 4 kohm +console.log() + +console.log('operations on arrays:') +const B = math.evaluate('[1, 0, 0] T') +const v3 = math.evaluate('[0, 1, 0] m/s') +const q = math.evaluate('1 C') +const F = math.multiply(q, math.cross(v3, B)) +console.log('B (magnetic field strength) = ' + format(B)) // [1 T, 0 T, 0 T] +console.log('v (particle velocity) = ' + format(v3)) // [0 m / s, 1 m / s, 0 m / s] +console.log('q (particle charge) = ' + format(q)) // 1 C +console.log('F (force) = q (v cross B) = ' + format(F)) // [0 N, 0 N, -1 N] + +/** + * Helper function to output a value in the console. Value will be formatted. + * @param {*} value + */ +function print (value) { + console.log(format(value)) +} + +/** + * Helper function to format an output a value. + * @param {*} value + * @return {string} Returns the formatted value + */ +function format (value) { + const precision = 14 + return math.format(value, precision) +} diff --git a/pool/shard001/JavaScript/0006425_compare.js b/pool/shard001/JavaScript/0006425_compare.js new file mode 100644 index 0000000000000000000000000000000000000000..215395237a0c22e9cc105b4980b3c86f614e26b9 --- /dev/null +++ b/pool/shard001/JavaScript/0006425_compare.js @@ -0,0 +1,75 @@ +steal('jquery', function($) { + +/** + * @function jQuery.fn.compare + * @parent jQuery.compare + * + * Compare two elements and return a bitmask as a number representing the following conditions: + * + * - `000000` -> __0__: Elements are identical + * - `000001` -> __1__: The nodes are in different documents (or one is outside of a document) + * - `000010` -> __2__: #bar precedes #foo + * - `000100` -> __4__: #foo precedes #bar + * - `001000` -> __8__: #bar contains #foo + * - `010000` -> __16__: #foo contains #bar + * + * You can check for any of these conditions using a bitwise AND: + * + * if( $('#foo').compare($('#bar')) & 2 ) { + * console.log("#bar precedes #foo") + * } + * + * @param {HTMLElement|jQuery} element an element or jQuery collection to compare against. + * @return {Number} A number representing a bitmask deatiling how the elements are positioned from each other. + */ + +// See http://ejohn.org/blog/comparing-document-position/ +$.fn.compare = function(element){ //usually + try{ + // Firefox 3 throws an error with XUL - we can't use compare then + element = element.jquery ? element[0] : element; + }catch(e){ + return null; + } + + // make sure we aren't coming from XUL element + if (window.HTMLElement) { + var s = HTMLElement.prototype.toString.call(element) + if (s == '[xpconnect wrapped native prototype]' || s == '[object XULElement]' || s === '[object Window]') { + return null; + } + } + + if(this[0].compareDocumentPosition){ + // For browsers that support it, use compareDocumentPosition + // https://developer.mozilla.org/en/DOM/Node.compareDocumentPosition + return this[0].compareDocumentPosition(element); + } + + // this[0] contains element + if(this[0] == document && element != document) return 8; + + var number = + // this[0] contains element + (this[0] !== element && this[0].contains(element) && 16) + + // element contains this[0] + (this[0] != element && element.contains(this[0]) && 8), + docEl = document.documentElement; + + // Use the sourceIndex + if(this[0].sourceIndex){ + // this[0] precedes element + number += (this[0].sourceIndex < element.sourceIndex && 4) + // element precedes foo[0] + number += (this[0].sourceIndex > element.sourceIndex && 2) + // The nodes are in different documents + number += (this[0].ownerDocument !== element.ownerDocument || + (this[0] != docEl && this[0].sourceIndex <= 0 ) || + (element != docEl && element.sourceIndex <= 0 )) && 1 + } + + return number; +} + +return $; +}); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006426_results-model-spec.js b/pool/shard001/JavaScript/0006426_results-model-spec.js new file mode 100644 index 0000000000000000000000000000000000000000..a4310fe5f7fb6d5e03ac94057adc26339895b671 --- /dev/null +++ b/pool/shard001/JavaScript/0006426_results-model-spec.js @@ -0,0 +1,140 @@ +(function() { + var $, ResultsModel, WorkspaceView, path, waitsForPromise, _ref; + + path = require('path'); + + _ref = require('atom'), $ = _ref.$, WorkspaceView = _ref.WorkspaceView; + + ResultsModel = require('../lib/project/results-model'); + + waitsForPromise = function(fn) { + return window.waitsForPromise({ + timeout: 30000 + }, fn); + }; + + describe('ResultsModel', function() { + var editSession, resultsModel, searchPromise, _ref1; + _ref1 = [], editSession = _ref1[0], searchPromise = _ref1[1], resultsModel = _ref1[2], searchPromise = _ref1[3]; + beforeEach(function() { + var editor; + atom.workspaceView = new WorkspaceView(); + atom.project.setPath(path.join(__dirname, 'fixtures')); + atom.workspaceView.openSync('sample.js'); + atom.workspaceView.attachToDom(); + editor = atom.workspaceView.getActiveView(); + editSession = editor.editor; + return resultsModel = new ResultsModel(); + }); + describe("searching for a pattern", function() { + beforeEach(function() {}); + it("populates the model with all the results, and updates in response to changes in the buffer", function() { + var resultAddedSpy, resultRemovedSpy; + resultAddedSpy = jasmine.createSpy(); + resultRemovedSpy = jasmine.createSpy(); + runs(function() { + resultsModel.on('result-added', resultAddedSpy); + resultsModel.on('result-removed', resultRemovedSpy); + return searchPromise = resultsModel.search('items', ['*.js'], ''); + }); + waitsForPromise(function() { + return searchPromise; + }); + return runs(function() { + var result; + expect(resultAddedSpy).toHaveBeenCalled(); + expect(resultAddedSpy.callCount).toBe(1); + result = resultsModel.getResult(editSession.getPath()); + expect(result.matches.length).toBe(6); + expect(resultsModel.getPathCount()).toBe(1); + expect(resultsModel.getMatchCount()).toBe(6); + expect(resultsModel.getPaths()).toEqual([editSession.getPath()]); + editSession.setText('there are some items in here'); + editSession.buffer.emit('contents-modified'); + expect(resultAddedSpy.callCount).toBe(2); + result = resultsModel.getResult(editSession.getPath()); + expect(result.matches.length).toBe(1); + expect(resultsModel.getPathCount()).toBe(1); + expect(resultsModel.getMatchCount()).toBe(1); + expect(resultsModel.getPaths()).toEqual([editSession.getPath()]); + expect(result.matches[0].lineText).toBe('there are some items in here'); + editSession.setText('no matches in here'); + editSession.buffer.emit('contents-modified'); + expect(resultAddedSpy.callCount).toBe(2); + expect(resultRemovedSpy.callCount).toBe(1); + result = resultsModel.getResult(editSession.getPath()); + expect(result).not.toBeDefined(); + expect(resultsModel.getPathCount()).toBe(0); + expect(resultsModel.getMatchCount()).toBe(0); + resultsModel.clear(); + spyOn(editSession, 'scan').andCallThrough(); + editSession.setText('no matches in here'); + editSession.buffer.emit('contents-modified'); + expect(editSession.scan).not.toHaveBeenCalled(); + expect(resultsModel.getPathCount()).toBe(0); + return expect(resultsModel.getMatchCount()).toBe(0); + }); + }); + return it("ignores changes in untitled buffers", function() { + var resultAddedSpy, resultRemovedSpy; + resultAddedSpy = jasmine.createSpy(); + resultRemovedSpy = jasmine.createSpy(); + waitsForPromise(function() { + return atom.workspaceView.open(); + }); + runs(function() { + resultsModel.on('result-added', resultAddedSpy); + resultsModel.on('result-removed', resultRemovedSpy); + return searchPromise = resultsModel.search('items', ['*.js'], ''); + }); + waitsForPromise(function() { + return searchPromise; + }); + return runs(function() { + editSession = atom.workspaceView.getActiveView().editor; + editSession.setText('items\nitems'); + spyOn(editSession, 'scan').andCallThrough(); + editSession.buffer.emit('contents-modified'); + return expect(editSession.scan).not.toHaveBeenCalled(); + }); + }); + }); + return describe("cancelling a search", function() { + var cancelledSpy; + cancelledSpy = null; + beforeEach(function() { + cancelledSpy = jasmine.createSpy(); + return resultsModel.on('cancelled-searching', cancelledSpy); + }); + it("populates the model with all the results, and updates in response to changes in the buffer", function() { + runs(function() { + searchPromise = resultsModel.search('items', ['*.js'], ''); + expect(resultsModel.inProgressSearchPromise).toBeTruthy(); + resultsModel.clear(); + return expect(resultsModel.inProgressSearchPromise).toBeFalsy(); + }); + waitsForPromise(function() { + return searchPromise; + }); + return runs(function() { + return expect(cancelledSpy).toHaveBeenCalled(); + }); + }); + return it("populates the model with all the results, and updates in response to changes in the buffer", function() { + runs(function() { + searchPromise = resultsModel.search('items', ['*.js'], ''); + return searchPromise = resultsModel.search('sort', ['*.js'], ''); + }); + waitsForPromise(function() { + return searchPromise; + }); + return runs(function() { + expect(cancelledSpy).toHaveBeenCalled(); + expect(resultsModel.getPathCount()).toBe(1); + return expect(resultsModel.getMatchCount()).toBe(5); + }); + }); + }); + }); + +}).call(this); diff --git a/pool/shard001/JavaScript/0006430_nav-pop.js b/pool/shard001/JavaScript/0006430_nav-pop.js new file mode 100644 index 0000000000000000000000000000000000000000..61f255641d4b00352846a7cd2427fb9ae4a0f8c1 --- /dev/null +++ b/pool/shard001/JavaScript/0006430_nav-pop.js @@ -0,0 +1,70 @@ +(function (factory) { + if (typeof module === "object" && typeof module.exports === "object") { + var v = factory(require, exports); + if (v !== undefined) module.exports = v; + } + else if (typeof define === "function" && define.amd) { + define(["require", "exports", "@angular/core", "../../navigation/nav-controller"], factory); + } +})(function (require, exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var core_1 = require("@angular/core"); + var nav_controller_1 = require("../../navigation/nav-controller"); + /** + * @name NavPop + * @description + * Directive to declaratively pop the current page off from the + * navigation stack. + * + * @usage + * ```html + * + * + * + * + * + * ``` + * + * Similar to {@link /docs/api/components/nav/NavPush/ `NavPush` } + * @demo /docs/demos/src/navigation/ + * @see {@link /docs/components#navigation Navigation Component Docs} + * @see {@link ../NavPush NavPush API Docs} + */ + var NavPop = (function () { + function NavPop(_nav) { + this._nav = _nav; + if (!_nav) { + console.error('navPop must be within a NavController'); + } + } + /** + * @hidden + */ + NavPop.prototype.onClick = function () { + // If no target, or if target is _self, prevent default browser behavior + if (this._nav) { + this._nav.pop().catch(function () { + (void 0) /* console.debug */; + }); + return false; + } + return true; + }; + NavPop.decorators = [ + { type: core_1.Directive, args: [{ + selector: '[navPop]' + },] }, + ]; + /** @nocollapse */ + NavPop.ctorParameters = function () { return [ + { type: nav_controller_1.NavController, decorators: [{ type: core_1.Optional },] }, + ]; }; + NavPop.propDecorators = { + 'onClick': [{ type: core_1.HostListener, args: ['click',] },], + }; + return NavPop; + }()); + exports.NavPop = NavPop; +}); +//# sourceMappingURL=nav-pop.js.map \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006431_inlineeditor.js b/pool/shard001/JavaScript/0006431_inlineeditor.js new file mode 100644 index 0000000000000000000000000000000000000000..cba9b96f2c18bb51818f8d85e3e4420e79eaa4c3 --- /dev/null +++ b/pool/shard001/JavaScript/0006431_inlineeditor.js @@ -0,0 +1,87 @@ +Fraym.InlineEditor = { + defaultSaveUrl: '', + instances: [], + + saveField: function(element, dataAttr, data, callback) { + var url = $(element).parents('[data-inline-editor-save]').data('inline-editor-save') || Fraym.InlineEditor.defaultSaveUrl; + var field = $(element).data(dataAttr); + var $block = $(element).parents('[data-id]:first'); + var blockId = $block.data('id'); + + var formData = new FormData(); + formData.append(field, data); + formData.append('blockId', blockId); + + $.ajax({ + url: url, + dataType: 'json', + data: formData, + processData: false, + contentType: false, + type: 'post', + success:function (json, textStatus, jqXHR) { + $block.addClass('changeset'); + if(callback) { + callback(json, textStatus, jqXHR); + } + } + }); + }, + + init: function() { + + $('[data-inline-editor-field]').attr('contenteditable', 'true'); + + for(var key in Fraym.InlineEditor.instances) + { + CKEDITOR.instances[Fraym.InlineEditor.instances[key]].destroy(); + } + + Fraym.InlineEditor.instances = []; + + $('[data-inline-editor-image]').each(function(){ + var $inlineEditorElement = this; + var $selectImageLink = $(''); + $selectImageLink.data('filefilter', $($inlineEditorElement).data('filefilter')); + $selectImageLink.data('singlefileselect', $($inlineEditorElement).data('singlefileselect')); + $selectImageLink.change(function(e, data){ + Fraym.InlineEditor.saveField($inlineEditorElement, 'inline-editor-image', data, function(json) { + Fraym.Block.replaceBlock(json.blockId, json.data); + }); + }); + $(this).append($selectImageLink); + }); + + Fraym.FileManager.initFilePathInput(); + + $('[data-inline-editor-field]').each(function(){ + + var removePlugins = 'toolbar'; + var removeButtons = 'Image,Flash,Table,HorizontalRule,SpecialChar,Iframe,find,selection,spellchecker,Find,Replace,SelectAll,Scayt,NewPage,Templates,ShowBlocks'; + + if($(this).data('inline-editor-rte') === true) { + removePlugins = ''; + } + + var instance = CKEDITOR.inline(this, { + removePlugins: removePlugins, + removeButtons: removeButtons, + basicEntities: false, + autoParagraph: false, + on: { + blur: function( event ) { + var data = event.editor.getData(); + data = Fraym.Block.replaceRteLink(data); + Fraym.InlineEditor.saveField(this.element.$, 'inline-editor-field', data); + } + } + }); + + Fraym.InlineEditor.instances.push(instance.name); + + $(this).click(function(){ + $(this).focus(); + }); + }); + } +}; \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006432_queue-attr-recs.js b/pool/shard001/JavaScript/0006432_queue-attr-recs.js new file mode 100644 index 0000000000000000000000000000000000000000..d6636e0ffe4e8680a8f04e9412095a65a35aae64 --- /dev/null +++ b/pool/shard001/JavaScript/0006432_queue-attr-recs.js @@ -0,0 +1,82 @@ +'use strict'; + +var constants = require('../constants'); + +var QueueAttrRecs = function (sql) { + this._sql = sql; +}; + +QueueAttrRecs.NAME = 'queue_attrs'; +QueueAttrRecs.ID_LAST_RESERVED = constants.ID_LAST_RESERVED; + +QueueAttrRecs.prototype.createTable = function () { + + var self = this; + + var schema = { + id: { + type: 'primary' + }, + col_name: { + type: 'varchar', + length: 100, + null: false + }, + doc_uuid: { + type: 'varbinary', + length: 38 + }, // 38 = 36 + prefix, can be null if modifying role + attr_name: { + type: 'varchar', + length: 100 + }, + attr_val: { + type: 'text' + }, + user_uuid: { + type: 'varbinary', + length: 36 + }, // userUUID of author + super_uuid: { + type: 'varbinary', + length: 36 + }, // userUUID of super user + created_at: { + type: 'datetime', + default: 'currenttimestamp', + null: false + }, + recorded_at: { + type: 'datetime', + default: 'currenttimestamp', + null: false + }, + updated_at: { + type: 'datetime', + default: 'currenttimestamp', + null: false + }, + seq: { + type: 'smallint' + }, // for back-to-back changes w/ same updatedAt + quorum: { + type: 'boolean' + } // true if quorum of servers have attr recorded + }; + + return self._sql.createTable(QueueAttrRecs.NAME, schema, null, QueueAttrRecs.ID_LAST_RESERVED); + +}; + +QueueAttrRecs.prototype.truncateTable = function () { + return this._sql.truncateTable(QueueAttrRecs.NAME, 'id', QueueAttrRecs.ID_LAST_RESERVED); +}; + +// TODO: make caller limit by pages +QueueAttrRecs.prototype.get = function () { + return this._sql.find(null, QueueAttrRecs.NAME).then(function (results) { + return results.rows ? results.rows : null; + }); +}; + +module.exports = QueueAttrRecs; diff --git a/pool/shard001/JavaScript/0006433_transformer.js b/pool/shard001/JavaScript/0006433_transformer.js new file mode 100644 index 0000000000000000000000000000000000000000..ece49b91222fb48e7e9ab1d228a0b936d62102f7 --- /dev/null +++ b/pool/shard001/JavaScript/0006433_transformer.js @@ -0,0 +1,69 @@ +var _ = require('./lib/test'), + Transformer = _.tagged('Transformer', ['x']), + TransformerT = _.transformer(_.tagged('TransformerT', ['run'])); + +Transformer.of = function(x) { + return Transformer(x); +}; + +Transformer.empty = function() { + return Transformer(''); +}; + +Transformer.prototype.chain = function(f) { + return f(this.x); +}; + +Transformer.prototype.equal = function(b) { + return _.equal(this.x, b.x); +}; + +Transformer.prototype.map = function(f) { + return this.chain(function(a) { + return Transformer.of(f(a)); + }); +}; + +exports.transformer = { + 'when testing Transformer of should return correct value': _.check( + function(a) { + var actual = TransformerT(Transformer).of(a); + return _.expect(actual.run.x).toBe(a); + }, + [_.AnyVal] + ), + 'when testing Transformer empty should return correct value': function(test) { + var actual = TransformerT(Transformer).empty(); + test.ok(actual.run.x === ''); + test.done(); + }, + 'when testing Transformer lift should return correct value': _.check( + function(a) { + var actual = TransformerT(Transformer).lift(Transformer(a)); + return _.expect(actual.run.x).toBe(a); + }, + [_.AnyVal] + ), + 'when testing Transformer chain should return correct value': _.check( + function(a, b) { + var trans = TransformerT(Transformer), + actual = trans.of(a).chain(function() { + return trans.of(b); + }); + + return _.expect(actual.run.x).toBe(b); + }, + [_.AnyVal, _.AnyVal] + ), + 'when testing Transformer map should return correct value': _.check( + function(a, b) { + var trans = TransformerT(Transformer), + actual = trans.of(a).map(function() { + return b; + }); + + return _.expect(actual.run.x).toBe(b); + }, + [_.AnyVal, _.AnyVal] + ) +}; \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006435_SocketError.js b/pool/shard001/JavaScript/0006435_SocketError.js new file mode 100644 index 0000000000000000000000000000000000000000..34493e4b0fbc73889e95fc0c86fe56e5783ee5c4 --- /dev/null +++ b/pool/shard001/JavaScript/0006435_SocketError.js @@ -0,0 +1,142 @@ +var expect = require('unexpected'); +var HttpError = require('httperrors'); +var http = require('http'); +var socketCodesMap = require('../lib/socketCodesMap'); +var SocketError = require('../lib/SocketError'); +// Alias to avoid jshint complaints due to capitalized function used without new: +var socketErrorConstructorInLowerCase = SocketError; + +describe('SocketError', function() { + it('will create a properly subclassed instance', function(done) { + // capture a genuine ECONNREFUSED error + http.get('http://localhost:59891/').on('error', function(err) { + var socketError = SocketError(err); + var httpError = new HttpError[504](); + + expect(socketError, 'to equal', new SocketError[err.code](err)); + + // has the original error propeties + expect(socketError, 'to have properties', Object.keys(err)); + + // has the httpError properties + expect(socketError, 'to have properties', Object.keys(httpError)); + + // has named errorCode property + expect(socketError[err.code], 'to be true'); + + expect(socketError, 'to be a', SocketError.SocketError); + + done(); + }); + }); + + it('will return unknown error if it was not mapped', function() { + var err = new Error(); + var socketError = SocketError(err); + + expect(socketError, 'to equal', new SocketError.NotSocketError()); + + expect(socketError.code, 'to equal', 'NotSocketError'); + + // has named errorCode property + expect(socketError.NotSocketError, 'to be true'); + }); + + it('will not alter the original error', function() { + var err = new Error(); + err.code = 'ECONNREFUSED'; + var socketError = SocketError(err); + + // assert socketError was altered + expect(socketError, 'to equal', new SocketError[err.code](err)); + + // assert orignal err was untouched + expect(err, 'not to have properties', ['statusCode']); + }); + + // check the various error codes will be transformed correctly + Object.keys(socketCodesMap).forEach(function(errorCode) { + var statusCode = socketCodesMap[errorCode]; + + describe(errorCode, function() { + it('is correctly instantiated', function() { + var err = new Error(); + err.code = errorCode; + var socketError = SocketError(err); + + expect(socketError, 'to equal', new SocketError[errorCode](err)); + + // has named errorCode property + expect(socketError[errorCode], 'to be true'); + }); + + it('returns a ' + statusCode, function() { + var socketError = SocketError( + (function() { + var err = new Error(); + err.code = errorCode; + return err; + })() + ); + + expect(socketError.statusCode, 'to equal', statusCode); + }); + + it('lets the `code` from the original instance take precedence over the one built into the class', function() { + var err = new Error(); + err.code = 'SOMETHINGELSE'; + var socketError = SocketError(err); + + expect(socketError.code, 'to equal', 'SOMETHINGELSE'); + }); + + describe('when instantiated via the constructor', function() { + it('has a `code` property', function() { + expect(new SocketError[errorCode]().code, 'to equal', errorCode); + }); + }); + }); + }); + + it('has the SocketError superclass constructor as the main export', function() { + expect(new SocketError.ECONNREFUSED(), 'to be a', SocketError); + }); + + it('should create an instance via SocketError(errorCode)', function() { + expect( + socketErrorConstructorInLowerCase('ECONNREFUSED'), + 'to be a', + SocketError.ECONNREFUSED + ); + }); + + describe('#supports', function() { + it('should return true for a mapped socket error code', function() { + expect(SocketError.supports('ECONNREFUSED'), 'to be true'); + }); + + it('should return false for an unmapped socket error code', function() { + expect(SocketError.supports('FOOBAR'), 'to be false'); + }); + + it('should return true for a unmapped socket error instance', function() { + var fakeSocketError = new Error('ECONNREFUSED'); + fakeSocketError.code = 'ECONNREFUSED'; + expect(SocketError.supports(fakeSocketError), 'to be true'); + }); + + it('should return false for a unmapped socket error instance', function() { + var fakeSocketError = new Error('FOOBAR'); + fakeSocketError.code = 'FOOBAR'; + expect(SocketError.supports(fakeSocketError), 'to be false'); + }); + }); + + it('should produce instances that have a falsy http property, despite being inherited from HttpError', function() { + expect(new SocketError.ECONNREFUSED().http, 'to be falsy'); + }); + + it('should produce instances that have a falsy HttpError property, despite being inherited from HttpError', function() { + expect(new SocketError.ECONNREFUSED().HttpError, 'to be falsy'); + }); +}); diff --git a/pool/shard001/JavaScript/0006442_version_module.js b/pool/shard001/JavaScript/0006442_version_module.js new file mode 100644 index 0000000000000000000000000000000000000000..fbdf0ead9655886155b00dc559521d79525a47a0 --- /dev/null +++ b/pool/shard001/JavaScript/0006442_version_module.js @@ -0,0 +1,29 @@ +var MapModule = require("./map_module"); + +function VersionModule(emscriptenApi) { + + var _emscriptenApi = emscriptenApi; + var _ready = false; + + this.getVersion = function() { + if (!_ready) { + return null; + } + return _emscriptenApi.versionApi.getPlatformVersion(); + }; + + this.getVersionHash = function() { + if (!_ready) { + return null; + } + return _emscriptenApi.versionApi.getPlatformVersionHash(); + }; + + this.onInitialized = function() { + _ready = true; + }; + +} +VersionModule.prototype = MapModule; + +module.exports = VersionModule; diff --git a/pool/shard001/JavaScript/0006443_checkbox.js b/pool/shard001/JavaScript/0006443_checkbox.js new file mode 100644 index 0000000000000000000000000000000000000000..3931e0164c904efc39cb464a369844814439db7e --- /dev/null +++ b/pool/shard001/JavaScript/0006443_checkbox.js @@ -0,0 +1,142 @@ +/*! + * Angular Material Design + * https://github.com/angular/material + * @license MIT + * v0.8.1-master-4d722ec + */ +goog.provide('ng.material.components.checkbox'); +goog.require('ng.material.core'); +(function() { +'use strict'; + +/** + * @ngdoc module + * @name material.components.checkbox + * @description Checkbox module! + */ +angular.module('material.components.checkbox', [ + 'material.core' +]) + .directive('mdCheckbox', MdCheckboxDirective); + +/** + * @ngdoc directive + * @name mdCheckbox + * @module material.components.checkbox + * @restrict E + * + * @description + * The checkbox directive is used like the normal [angular checkbox](https://docs.angularjs.org/api/ng/input/input%5Bcheckbox%5D). + * + * As per the [material design spec](http://www.google.com/design/spec/style/color.html#color-ui-color-application) + * the checkbox is in the accent color by default. The primary color palette may be used with + * the `md-primary` class. + * + * @param {string} ng-model Assignable angular expression to data-bind to. + * @param {string=} name Property name of the form under which the control is published. + * @param {expression=} ng-true-value The value to which the expression should be set when selected. + * @param {expression=} ng-false-value The value to which the expression should be set when not selected. + * @param {string=} ng-change Angular expression to be executed when input changes due to user interaction with the input element. + * @param {boolean=} md-no-ink Use of attribute indicates use of ripple ink effects + * @param {string=} aria-label Adds label to checkbox for accessibility. + * Defaults to checkbox's text. If no default text is found, a warning will be logged. + * + * @usage + * + * + * Finished ? + * + * + * + * No Ink Effects + * + * + * + * Disabled + * + * + * + * + */ +function MdCheckboxDirective(inputDirective, $mdInkRipple, $mdAria, $mdConstant, $mdTheming, $mdUtil) { + inputDirective = inputDirective[0]; + var CHECKED_CSS = 'md-checked'; + + return { + restrict: 'E', + transclude: true, + require: '?ngModel', + template: + '
      ' + + '
      ' + + '
      ' + + '
      ', + compile: compile + }; + + // ********************************************************** + // Private Methods + // ********************************************************** + + function compile (tElement, tAttrs) { + + tAttrs.type = 'checkbox'; + tAttrs.tabIndex = 0; + tElement.attr('role', tAttrs.type); + + return function postLink(scope, element, attr, ngModelCtrl) { + ngModelCtrl = ngModelCtrl || $mdUtil.fakeNgModel(); + var checked = false; + $mdTheming(element); + + if (attr.ngChecked) { + scope.$watch( + scope.$eval.bind(scope, attr.ngChecked), + ngModelCtrl.$setViewValue.bind(ngModelCtrl) + ); + } + + $mdAria.expectWithText(element, 'aria-label'); + + // Reuse the original input[type=checkbox] directive from Angular core. + // This is a bit hacky as we need our own event listener and own render + // function. + inputDirective.link.pre(scope, { + on: angular.noop, + 0: {} + }, attr, [ngModelCtrl]); + + element.on('click', listener) + .on('keypress', keypressHandler); + ngModelCtrl.$render = render; + + function keypressHandler(ev) { + if(ev.which === $mdConstant.KEY_CODE.SPACE) { + ev.preventDefault(); + listener(ev); + } + } + function listener(ev) { + if (element[0].hasAttribute('disabled')) return; + + scope.$apply(function() { + checked = !checked; + ngModelCtrl.$setViewValue(checked, ev && ev.type); + ngModelCtrl.$render(); + }); + } + + function render() { + checked = ngModelCtrl.$viewValue; + if(checked) { + element.addClass(CHECKED_CSS); + } else { + element.removeClass(CHECKED_CSS); + } + } + }; + } +} +MdCheckboxDirective.$inject = ["inputDirective", "$mdInkRipple", "$mdAria", "$mdConstant", "$mdTheming", "$mdUtil"]; + +})(); diff --git a/pool/shard001/JavaScript/0006446_api.js b/pool/shard001/JavaScript/0006446_api.js new file mode 100644 index 0000000000000000000000000000000000000000..00118fe828e0108034f96ec9b8d352b58dd353f4 --- /dev/null +++ b/pool/shard001/JavaScript/0006446_api.js @@ -0,0 +1,258 @@ +var api = { + + /** + * Handle to the jsonrpc server. + */ + _server: new $.JsonRpcClient({ ajaxUrl: "http://" + window.location.hostname + ":28574/" }), + + /** + * Internal function for passing calls to the jsonrpc server. + * + * @param {string} method Method to call. + * @param {array} args Arguments to pass. + * @param {apiCallback} callback function(err, result) (optional) + */ + _call: function(method, args, callback) { + return this._server.call( + method, args, + function(result) { if (callback) return callback(null, result); }, + function(error) { + + console.error('Error from jsonrpc: ' + error.message, + 'Method: ' + method, + 'Args: ', args, + error); + if (callback) return callback(error); + } + ); + }, + + /** + * Echo function. Just echoes back whatever is sent in the text parameter. + * Use this to test if the server is responding. + * + * @param {*} text The thing you want echoed back. + * @param {apiCallback} cb function(err, result); 'result' will have the same type as 'text' + */ + echo: function(text, cb) { + return this._call('echo', [text], cb); + }, + + /** + * Get the addon version running on the server. This will be something like + * "1.2.3", whatever is set in the addon.xml + * + * @param {Function} cb function(err, version); where 'version' will be the version string + */ + get_version: function(cb) { + return this._call('get_version', [], cb); + }, + + /** + * Return a list of all shows (both in the xbmc library, and in the database) + * Only the properties specified in the properties argument will be populated. + * + * @param {array} properties Array of required property names. If null the default is used. See + * the python tvtumbler.tv.TvShow for a list of all available properties. + * (but be aware that some can be quite slow to retrieve) + * @param {apiCallback} cb function(err, shows); where shows is an array of object, each a 'show'. + */ + get_all_shows: function(properties, cb) { + if (properties === null) { + properties=['tvshowid', 'name', 'tvdb_id', 'followed', 'wanted_quality', 'fanart', + 'thumbnail', 'poster', 'banner']; + } + return this._call('get_all_shows', [properties], cb); + }, + + /** + * Return an array of objects with the properties of the shows with the tvdb_ids given. + * + * @param {array} tvdb_ids An array of tvdb_ids. Either ints or strings. + * @param {array} properties Array of required property names. If null the default is used. See + * the python tvtumbler.tv.TvShow for a list of all available properties. + * (but be aware that some can be quite slow to retrieve) + * @param {apiCallback} cb function(err, shows); where shows is an array of object, each a 'show'. + */ + get_shows: function(tvdb_ids, properties, cb) { + if (properties === null) { + properties=['tvshowid', 'name', 'tvdb_id', 'followed', 'wanted_quality', 'fanart', + 'thumbnail', 'poster', 'banner']; + } + return this._call('get_shows', [tvdb_ids, properties], cb); + }, + + /** + * Flag a show as followed/ignored + * + * @param {int|string} tvdb_id tvdb_id of show to set. + * @param {boolean} followed true => followed, false => ignored. + * @param {apiCallback} cb function(err, wasFollowed); optional callback. wasFollowed is the prev state + */ + set_show_followed: function(tvdb_id, followed, cb) { + return this._call('set_show_followed', [tvdb_id, followed], cb); + }, + + /** + * Get the current wanted_quality for a show + * + * @param {int|string} tvdb_id + * @param {apiCallback} cb function(err, wanted_quality); where wanted_quality is an int (one of the + * python tvtumbler.quality values. + */ + get_show_wanted_quality: function(tvdb_id, cb) { + return this._call('get_show_wanted_quality', [tvdb_id], cb); + }, + + /** + * Set the wanted_quality for a show + * + * @param {int|string} tvdb_id + * @param {int} wanted_quality The wanted_quality. One of the python tvtumbler.quality values + * @param {apiCallback} cb function(err, prev_quality); optional callback where prev_quality is + * the previous setting. + */ + set_show_wanted_quality: function(tvdb_id, wanted_quality, cb) { + return this._call('set_show_wanted_quality', [tvdb_id, wanted_quality], cb); + }, + + /** + * Get an array of running downloads from the server. + * + * @param {array} properties The properties to get for each download. See the python + * tvtumbler.comms.server for a list of available properties. + * If null, defaults are used. + * @param {string} sort_by CURRENTLY_IGNORED. + * @param {apiCallback} cb function(err, downloads); where downloads is an array of objects. + */ + get_running_downloads: function(properties, sort_by, cb) { + if (properties === null) { + properties=['rowid', 'key', 'name', 'status', 'status_text', 'total_size', + 'downloaded_size', 'download_speed', 'start_time', 'source', + 'downloader']; + } + if (sort_by === null) { + sort_by='start_time'; + } + return this._call('get_running_downloads', [properties, sort_by], cb); + }, + + /** + * Get an array of previous downloads. + * + * @param {array} properties An array of strings, the properties of wanted. See the python code + * tvtumbler.log.get_non_running_downloads() for a list of available + * properties. Leave set to null for defaults. + * @param {int} limit Limit the length of returned results. If null, defaults to 30. + * @param {apiCallback} cb function(err, downloads); where downloads is an array of objects. + */ + get_non_running_downloads: function(properties, limit, cb) { + if (properties === null) { + properties=['rowid', 'key', 'name', 'final_status', 'total_size', + 'start_time', 'finish_time', 'source', 'quality']; + } + if (limit === null) { + limit = 30; + } + return this._call('get_non_running_downloads', [properties, limit], cb); + }, + + /** + * Does a GetSeries.php search on thetvdb. + * Returns an array objects, one for each found show (may be empty), with the following properties: + * 'seriesid' - the tvdb_id + * 'language' + * 'seriesname' + * 'overview' + * 'firstaired' + * 'network' + * 'imdb_id' + * 'zap2it_id' + * 'aliasnames' - a list, if present. + * + * @param {string} searchstring + * @param {apiCallback} cb function(err, foundShows) where foundShows is the array. + */ + search_series_by_name: function(searchstring, cb) { + return this._call('search_series_by_name', [searchstring], cb); + }, + + /** + * Add a show. + * + * @param {int|string} tvdb_id tvdb_id to add. + * @param {boolean} followed true or false. (care: if false it will be deleted automatically later) + * @param {int} wanted_quality One of the python tvtumbler.quality values. Default is 3 (SDTV | SDDVD). + * @param {apiCallback} cb Always returns true, unless the error is set. + */ + add_show: function(tvdb_id, followed, wanted_quality, cb) { + if (followed === null) { + followed = true; + } + if (wanted_quality === null) { + wanted_quality = quality.SD_COMP; + } + return this._call('add_show', [tvdb_id, followed, wanted_quality], cb); + }, + + /** + * Get episodes that air on a particular date. + * + * @param {string} firstaired This is an iso date format (yyyy-mm-dd) string. + * @param {array} properties An array of strings. The properties wanted. See the python code + * tvtumbler.comms.server.Service for a list of possible values. Use null + * for the defaults. + * @param {apiCallback} cb The callback receives an array of objects, if there's no error. + */ + get_episodes_on_date: function(firstaired, properties, cb) { + if (properties === null) { + properties=['episodeid', 'tvdb_season', 'tvdb_episode', 'title', + 'art', 'show_fanart', 'show_thumbnail', + 'show_tvdb_id', 'show_name', 'have_state' + ]; + } + return this._call('get_episodes_on_date', [firstaired, properties], cb); + }, + + /** + * Get an array of seasons for this show. + * + * @param {int|string} tvdb_id tvdb_id + * @param {apiCallback} cb function(err, seasons) where seasons is the array. + */ + get_seasons: function(tvdb_id, cb) { + return this._call('get_seasons', [tvdb_id], cb); + }, + + /** + * Get episodes in a season. + * + * @param {int} tvdb_id Show to search. + * @param {int} tvdb_season Season to search. Use zero (0) for specials. + * @param {array} properties An array of strings. The properties wanted. See the python code + * tvtumbler.comms.server.Service for a list of possible values. Use null + * for the defaults. + * @param {apiCallback} cb The callback receives an array of objects. + */ + get_episodes_in_season: function(tvdb_id, tvdb_season, properties, cb) { + if (properties === null) { + properties = ['episodeid', 'tvdb_season', 'tvdb_episode', 'title', 'have_state']; + } + return this._call('get_episodes_in_season', [tvdb_id, tvdb_season, properties], cb); + }, + + /** + * Refresh the episode list for a series. Always returns True. + */ + refresh_episodes: function(tvdb_id, cb) { + return this._call('refresh_episodes', [tvdb_id], cb); + } +} + +/** + * This callback type is called `apiCallback` and is displayed as a global symbol. + * + * @callback apiCallback + * @param {*} err This will be set if an error occurred. null otherwise. + * @param {*} result This is the 'return' value from jsonrpc. + */ diff --git a/pool/shard001/JavaScript/0006447_externalEvents.spec.js b/pool/shard001/JavaScript/0006447_externalEvents.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..d4e55226ba5d302a863ae7c2e4040f16ebf7ec35 --- /dev/null +++ b/pool/shard001/JavaScript/0006447_externalEvents.spec.js @@ -0,0 +1,41 @@ +import * as externalEvents from './externalEvents' + +describe('app-extensions', () => { + describe('externalEvents', () => { + describe('invokeExternalEvent', () => { + test('should invoke event handler', () => { + const handler = sinon.spy() + const events = {success: handler} + externalEvents.invokeExternalEvent(events, 'success') + expect(handler).to.have.property('callCount', 1) + }) + + test('should pass arguments to event handler', () => { + const handler = sinon.spy() + const events = {success: handler} + externalEvents.invokeExternalEvent(events, 'success', 'arg1', 'arg2', 'arg3') + expect(handler).to.have.been.calledWith('arg1', 'arg2', 'arg3') + }) + + test('should ignore unknown events', done => { + externalEvents.invokeExternalEvent('unknown') + done() + }) + }) + + describe('addToStore', () => { + test('should start sagas', () => { + const sagaRunSpy = sinon.spy() + const store = { + sagaMiddleware: { + run: sagaRunSpy + } + } + + externalEvents.addToStore(store, {}) + + expect(sagaRunSpy).to.be.calledOnce + }) + }) + }) +}) diff --git a/pool/shard001/JavaScript/0006448_object.js b/pool/shard001/JavaScript/0006448_object.js new file mode 100644 index 0000000000000000000000000000000000000000..6638def53685caae539041bab3ba82446c6c1931 --- /dev/null +++ b/pool/shard001/JavaScript/0006448_object.js @@ -0,0 +1,78 @@ +import Promise from './promise'; +import Ember from 'ember'; + +export default Promise.extend({ + _validators : null, + + _observers : null, + + typeCheck : null, + + validators: Ember.computed(function() { + var ret = {}; + var self = this; + this.constructor.eachComputedProperty(function(name, meta) { + if (meta.type==='validation') { + ret[name]=self.get(name); + } + }); + return ret; + }).readOnly(), + + init: function() { + this._super(); + this._validators={}; + this.get('validators'); + }, + + _validate: function(context) { + var promises=Ember.A(); + Ember.assert('The object validator can\'t validate enumerables',!Ember.Enumerable.detect(context.value)); + + // Check the stack for circular checks + if(!context.stack.contains(context.value)) { + context.stack.push(context.value); + var validators=this.get('validators'); + for(var propertyName in validators) { + var nestedContext=context.nest(propertyName); + if(nestedContext) { + promises.pushObject(validators[propertyName]._validate(nestedContext)); + } + } + promises.pushObject(this._super(context)); + } + + var validator=this; + return Ember.RSVP.all(promises,validator.constructor.toString()+" All validations for "+context.path).then(function(values) { + return context.result; + },function(e) { + return e; + },validator.constructor.toString()+" Validations resolved"); + }, + + _validateProperty:function(propertyName,context) { + return this.get('validators.'+propertyName).invoke('_validate',context); + }, + + + _observe : function(observer) { +// console.log('Validator _observer'); +// Ember.debug(this); + this._super(observer); + var validators=this.get('validators'); + for(var propertyName in validators) { + observer._observe(propertyName,validators[propertyName]); + } + }, + + call : function(context,value,result) { + if(value){ + if(!(value instanceof Ember.Object)) { + result.addError(context,'notObject'); + } else if(this.get('typeCheck') && !(value instanceof this.get('typeCheck'))) { + result.addError(context,'invalidType'); + } + } + }, + +}); diff --git a/pool/shard001/JavaScript/0006450_mod_form.js b/pool/shard001/JavaScript/0006450_mod_form.js new file mode 100644 index 0000000000000000000000000000000000000000..ef2e819fda23b6cc898e3a95b2f60c1d2f4c88a4 --- /dev/null +++ b/pool/shard001/JavaScript/0006450_mod_form.js @@ -0,0 +1,174 @@ +M.mod_multimedia = M.mod_multimedia || {}; + +/** +* When pick one multimedia,update the content field. +* Use base64_encode +* +*/ +M.mod_multimedia.init_filepicker = function(Y,elementname){ + Y.use('event,node',function(){ + Y.one('#id_'+elementname).on('change',function(e){ + //var client_id = Y.one(e.target).ancestor('.ffilepicker') + //.one('.filepicker-filelist').get('id').replace('file_info_',''); + //var client = M.core_filepicker.instances[client_id]; + var url = Y.one(e.target).ancestor('.ffilepicker').one('.filepicker-filename>a').get('href'); + var result = url.match(new RegExp("(.+)\#(.+)", "i")); + var content = M.mod_multimedia.Base64.encode(''+result[2]+''); + Y.one(e.target).ancestor('form').one('input[name=content]').set('value',content); + }) + }); +}; + +/** +* When load the form page, update the file picker with the content. +* Use base64_decode. +* +*/ +M.mod_multimedia.restore_filepicker = function(Y,elementname){ + Y.use('event,node',function(){ + var content = Y.one('input[name=content]').get('value'); + if(!content)return; + try{ + content = M.mod_multimedia.Base64.decode(content); + var html = content + '
      '; + Y.one('#id_'+elementname).ancestor('.ffilepicker').one('.filepicker-filename').setContent(html); + }catch(e){ + } + }); +}; + +//copy from http://yui.yahooapis.com/combo?gallery-2013.02.27-21-03/build/gallery-base64/gallery-base64.js +//This isn't in the moodle yui +(function(Y) { + + /* + * Copyright (c) 2009 Nicholas C. Zakas. All rights reserved. + * http://www.nczonline.net/ + */ + + /** + * Base64 encoder/decoder + * @module gallery-base64 + */ + + //base 64 digits + var digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + + /** + * Base64 encoder/decoder + * @class Base64 + * @static + */ + Y.Base64 = { + + /** + * Base64-decodes a string of text. + * @param {String} text The text to decode. + * @return {String} The base64-decoded string. + */ + decode: function(text){ + + //ignore white space + text = text.replace(/\s/g,""); + + //first check for any unexpected input + if(!(/^[a-z0-9\+\/\s]+\={0,2}$/i.test(text)) || text.length % 4 > 0){ + throw new Error("Not a base64-encoded string."); + } + + //local variables + var cur, prev, digitNum, + i=0, + result = []; + + //remove any equals signs + text = text.replace(/\=/g, ""); + + //loop over each character + while(i < text.length){ + + cur = digits.indexOf(text.charAt(i)); + digitNum = i % 4; + + switch(digitNum){ + + //case 0: first digit - do nothing, not enough info to work with + + case 1: //second digit + result.push(String.fromCharCode(prev << 2 | cur >> 4)); + break; + + case 2: //third digit + result.push(String.fromCharCode((prev & 0x0f) << 4 | cur >> 2)); + break; + + case 3: //fourth digit + result.push(String.fromCharCode((prev & 3) << 6 | cur)); + break; + } + + prev = cur; + i++; + } + + //return a string + return result.join(""); + + }, + + + /** + * Base64-encodes a string of text. + * @param {String} text The text to encode. + * @return {String} The base64-encoded string. + */ + encode: function(text){ + + if (/([^\u0000-\u00ff])/.test(text)){ + throw new Error("Can't base64 encode non-ASCII characters."); + } + + var i = 0, + cur, prev, byteNum, + result=[]; + + while(i < text.length){ + + cur = text.charCodeAt(i); + byteNum = i % 3; + + switch(byteNum){ + case 0: //first byte + result.push(digits.charAt(cur >> 2)); + break; + + case 1: //second byte + result.push(digits.charAt((prev & 3) << 4 | (cur >> 4))); + break; + + case 2: //third byte + result.push(digits.charAt((prev & 0x0f) << 2 | (cur >> 6))); + result.push(digits.charAt(cur & 0x3f)); + break; + } + + prev = cur; + i++; + } + + if (byteNum == 0){ + result.push(digits.charAt((prev & 3) << 4)); + result.push("=="); + } else if (byteNum == 1){ + result.push(digits.charAt((prev & 0x0f) << 2)); + result.push("="); + } + + return result.join(""); + + } + + }; + + +})(M.mod_multimedia); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006451_task0002_5.js b/pool/shard001/JavaScript/0006451_task0002_5.js new file mode 100644 index 0000000000000000000000000000000000000000..87dc41d5eda89b2c08a00d1cd04f44dc77ec69a5 --- /dev/null +++ b/pool/shard001/JavaScript/0006451_task0002_5.js @@ -0,0 +1,99 @@ +(function (){ + var draggingObj = null; + var dragObjId; + var diffX = 0, diffY = 0; + var left = ["bar1", "bar2", "bar3", "bar4", "bar5", "void", "void", "void"]; + var right = ["bar6", "bar7", "bar8", "void", "void", "void", "void", "void"]; + + function down(e) { + e = e ? e : window.event; + var target = e.srcElement ? e.srcElement : e.target; + dragObjId = target.id; + if (target.className.indexOf('bar') != -1) { + draggingObj = target; + diffX = e.clientX - target.offsetLeft; + diffY = e.clientY - target.offsetTop; + } + } + + function move(e) { + e = e ? e : window.event; + if (draggingObj) { + var cur = document.getElementById(dragObjId); + cur.style.top = (e.clientY - diffY).toString() + 'px'; + cur.style.left = (e.clientX - diffX).toString() + 'px'; + } + } + + function up(e){ + console.log(draggingObj.offsetLeft); + draggingObj = e.target; + if(draggingObj.offsetLeft < 200 && draggingObj.offsetLeft > 50 && right.indexOf(draggingObj.id) != -1){ + if(draggingObj.offsetTop < 50 && left[0] == "space"){ + left[0] = draggingObj.id; + draggingObj.style = ""; + } + for(var i = 1; i < 8;i++){ + if(draggingObj.offsetTop > 100 * i - 50 && draggingObj.offsetTop < 100 * i + 50 && left[i] == "space"){ + left[i] = draggingObj.id; + draggingObj.style = ""; + } + } + $("#box-left").innerHTML = $("#box-left").innerHTML + draggingObj.outerHTML; + right[right.indexOf(draggingObj.id)] = "space"; + try{ + draggingObj.remove(); + }catch(exception){ + removeElement(draggingObj); + } + } + + else if(draggingObj.offsetLeft > 350 && draggingObj.offsetLeft < 500 && left.indexOf(draggingObj.id) != -1){ + console.log("fuck"); + if(draggingObj.offsetTop < 50 && right[0] == "space"){ + right[0] = draggingObj.id; + draggingObj.style = ""; + } + for(var i = 1; i < 8; i++){ + if(draggingObj.offsetTop > 100 * i - 50 && draggingObj.offsetTop < 100 * i + 50 && right[i] == "space"){ + right[i] = draggingObj.id; + draggingObj.style = ""; + } + } + $("#box-right").innerHTML = $("#box-right").innerHTML + draggingObj.outerHTML; + left[left.indexOf(draggingObj.id)] = "space"; + try{ + draggingObj.remove(); + }catch(exception){ + removeElement(draggingObj); + } + } + + else { + draggingObj.style = ""; + } + draggingObj = null; + diffX = 0; + diffY = 0; + console.log(left); + console.log(right); + } + + function removeElement(ele){ + var parentElement = ele.parentNode; + if (parentElement){ + parentElement.removeChild(ele); + } + } + + var drag = { + down : down, + up : up, + move : move + } + window.drag = drag; +})() + +addEvent(document, 'mousedown', drag.down); +addEvent(document, 'mouseup', drag.up); +addEvent(document, 'mousemove', drag.move); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006452_sidebar.js b/pool/shard001/JavaScript/0006452_sidebar.js new file mode 100644 index 0000000000000000000000000000000000000000..057f741f16671430238edf7cfea5687cdaf39eb5 --- /dev/null +++ b/pool/shard001/JavaScript/0006452_sidebar.js @@ -0,0 +1,213 @@ +/* + * sidebar.js + * ~~~~~~~~~~ + * + * This script makes the Sphinx sidebar collapsible and moveable. + * + * .sphinxsidebar contains .sphinxsidebarwrapper. The script adds + * in .sphixsidebar, after .sphinxsidebarwrapper, the #sidebarbutton + * used to collapse, expand and move the sidebar. + * + * The script saves per-browser/per-session cookies used to remember + * the collapsed state and position of the sidebar among the pages. + * Once the browser is closed the cookies are deleted and the position + * reset to the default set in the style sheed. + * + * Modifications and improvements made 2010 by Christoph Zwerschke. + * + * :copyright: Copyright 2007-2010 by the Sphinx team, see AUTHORS. + * :license: BSD, see LICENSE for details. + * + */ + +$(function() { + var body = $('div.document'); + var body_width = body.width(); + var footer = $('div.footer'); + var sidebar = $('div.sphinxsidebar'); + var sidebarwrapper = $('div.sphinxsidebarwrapper'); + var sidebarbutton = $('
      '); + var sbw_width = sidebar.width(); + var sbb_width = 9; + var dark_color = $('div.related').css('background-color'); + var light_color = sidebarwrapper.css('color'); + var opacity_factor = $.browser.msie ? 1 : 0.75; + var collapsed = sidebarwrapper.is(':not(:visible)'); + var rightside = sidebar.css('right') == '0px'; + var dragging = null; + + function set_sidebar() { + var width = collapsed ? 0 : sbw_width; + if (rightside) { + sidebar.css({ + 'width': width, + 'left': 'auto', + 'right': 0 + }); + sidebarbutton.css({ + 'right': collapsed ? 0 : width, + 'left': 'auto' + }); + body.add(footer).css({ + 'margin-right': width + sbb_width, + 'margin-left': 0 + }); + } else { + sidebar.css({ + 'width': width, + 'right': 'auto', + 'left': '0' + }); + sidebarbutton.css({ + 'left': collapsed ? 0 : width, + 'right': 'auto' + }); + body.add(footer).css({ + 'margin-left': width + sbb_width, + 'margin-right': 0 + }); + } + sidebarbutton.find('div').text(rightside == collapsed ? '«' : '»'); + } + + function toggle_sidebar() { + collapsed ? expand_sidebar() : collapse_sidebar(); + } + + function collapse_sidebar() { + collapsed = true; + sidebarwrapper.hide(); + set_sidebar(); + sidebarbutton.attr('title', _('Expand sidebar')); + document.cookie = 'sidebar_collapsed=1'; + } + + function expand_sidebar() { + collapsed = false; + sidebarwrapper.show(); + set_sidebar(); + sidebarbutton.attr('title', _('Collapse sidebar')); + document.cookie = 'sidebar_collapsed=0'; + } + + function add_sidebar_button() { + sidebar.css('width', (collapsed ? 0 : sbw_width) + sbb_width); + sidebarbutton.attr('title', _('Collapse sidebar')); + sidebarbutton.css({ + 'color': light_color, + 'font-size': 14, + 'text-align': 'center', + 'border-left': '1px solid ' + dark_color, + 'border-right': '1px solid ' + dark_color, + 'padding': '1px 0', + 'margin': '0', + 'width': sbb_width - 2, + 'cursor': 'pointer', + 'position': 'fixed', + 'left': collapsed ? 0 : sbw_width, + 'top': sidebar.css('top'), + 'bottom': 0 + }); + sidebarbutton.find('div').css({ + 'position': 'relative', + 'top': '50%', + 'margin-top': -8 + }); + set_sidebar(); + sidebarbutton.hover( + function() { + sidebarbutton.css('background-color', dark_color); + }, + function() { + sidebarbutton.css('background-color', light_color); + } + ); + sidebarbutton.mousedown( + function(e) { + if (dragging != null || e.which != 1) return; + dragging = { + 'dragged': false, + 'pageX': e.pageX + }; + sidebarbutton.css('cursor', 'move'); + } + ); + sidebar.add(body).mouseup( + function(e) { + if (dragging == null) + return; + e.preventDefault(); + if (dragging.dragged) { + var left = sidebar.offset().left; + if (rightside) + left = body_width - left; + if (left < 0 && !collapsed) + collapse_sidebar(); + else if (left < body_width / 2 && + left < sbw_width + 2 * sbw_width && collapsed) + expand_sidebar(); + else { + if (left > body_width / 2) + rightside = !rightside; + set_sidebar(); + } + if (opacity_factor != 1) + sidebar.css('opacity', dragging.opacity); + document.cookie = 'sidebar_rightside=' + (rightside ? '1' : '0'); + } else + toggle_sidebar(); + sidebarbutton.css('cursor', 'pointer'); + dragging = null; + e.stopPropagation(); + } + ); + sidebar.add(body).mousemove( + function(e) { + if (dragging == null) + return; + e.preventDefault(); + var pageX = e.pageX; + side = 'left'; + sidebarbutton.css('left', pageX); + if (rightside) + pageX += sbb_width; + else + pageX -= sbw_width; + sidebar.css('left', pageX); + if (!dragging.dragged) { + dragging.dragged = true; + if (collapsed) { + sidebar.css('width', sbw_width); + sidebarwrapper.show(); + } + if (opacity_factor != 1) { + dragging.opacity = sidebar.css('opacity'); + sidebar.css('opacity', opacity_factor * dragging.opacity); + } + } + e.stopPropagation(); + } + ); + sidebar.append(sidebarbutton); + light_color = sidebarbutton.css('background-color'); + } + + function set_position_from_cookie() { + if (!document.cookie) + return; + var items = document.cookie.split(';'); + for (var k = 0; k < items.length; k++) { + var key_val = items[k].split('='); + var key = $.trim(key_val[0]); + var val = $.trim(key_val[1]); + if (key == 'sidebar_collapsed') + collapsed = val == '1'; + else if (key == 'sidebar_rightside') + rightside = val == '1'; + } + } + + set_position_from_cookie(); + if (sidebar.length) + add_sidebar_button(); +}); diff --git a/pool/shard001/JavaScript/0006456_fetch.js b/pool/shard001/JavaScript/0006456_fetch.js new file mode 100644 index 0000000000000000000000000000000000000000..166c3553948721ea24a44d6c450421229fb21145 --- /dev/null +++ b/pool/shard001/JavaScript/0006456_fetch.js @@ -0,0 +1,105 @@ +import {parse as urlParse} from 'url'; +import * as session from './session'; +import {version} from '../../package.json'; +import {isLocalhost} from './util'; + +let commandListeners = []; + +export function onCommand(callback) { + console.log(`-- Added DB Listener -- `); + commandListeners.push(callback); +} + +export function offCommand(callback) { + console.log(`-- Removed DB Listener -- `); + commandListeners = commandListeners.filter(l => l !== callback); +} + +export function post(path, obj) { + return _fetch('POST', path, obj); +} + +export function put(path, obj, sessionId = null) { + return _fetch('PUT', path, obj, sessionId); +} + +export function patch(path, obj) { + return _fetch('PATCH', path, obj); +} + +export function get(path, sessionId = null) { + return _fetch('GET', path, null, sessionId); +} + +export function del(path, sessionId = null) { + return _fetch('DELETE', path, null, sessionId); +} + +export function to(path) { + window.location = _getUrl(path); +} + +async function _fetch(method, path, json, sessionId = null) { + const config = { + method: method, + headers: new Headers() + }; + + // Set some client information + config.headers.set('X-Insomnia-Client', getClientString()); + + if (json) { + config.body = JSON.stringify(json, null, 2); + config.headers.set('Content-Type', 'application/json'); + } + + sessionId = sessionId || session.getCurrentSessionId(); + if (sessionId) { + config.headers.set('X-Session-Id', sessionId); + } + + const response = await fetch(_getUrl(path), config); + + const uri = response.headers.get('x-insomnia-command'); + uri && _notifyCommandListeners(uri); + + if (!response.ok) { + const err = new Error(`Response ${response.status} for ${path}`); + err.message = await response.text(); + err.statusCode = response.status; + throw err; + } + + if (response.headers.get('content-type') === 'application/json') { + return response.json(); + } else { + return response.text(); + } +} + +export function _getUrl(path) { + if (window.location.hostname === 'staging.insomnia.rest') { + return `https://api.staging.insomnia.rest${path}`; + } else if (isLocalhost()) { + return `http://localhost:8000${path}`; + } else { + return `https://api.insomnia.rest${path}`; + } +} + +function _notifyCommandListeners(uri) { + const parsed = urlParse(uri, true); + + const command = `${parsed.hostname}${parsed.pathname}`; + const args = JSON.parse(JSON.stringify(parsed.query)); + + commandListeners.map(fn => fn(command, args)); +} + +function getClientString() { + return `${isDev() ? 'development' : 'production'}::browser::${version}`; +} + +function isDev() { + return process.env.NODE_ENV !== 'production'; +} diff --git a/pool/shard001/JavaScript/0006457_zoom_controls.js b/pool/shard001/JavaScript/0006457_zoom_controls.js new file mode 100644 index 0000000000000000000000000000000000000000..0683b15356490f1a81309f22b1c2a48ba537febd --- /dev/null +++ b/pool/shard001/JavaScript/0006457_zoom_controls.js @@ -0,0 +1,358 @@ +/** + * @license + * Copyright 2015 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. + */ + +/** + * @fileoverview Object representing a zoom icons. + * @author carloslfu@gmail.com (Carlos Galarza) + */ +'use strict'; + +goog.provide('Blockly.ZoomControls'); + +goog.require('Blockly.Css'); +goog.require('Blockly.Scrollbar'); +goog.require('Blockly.Touch'); +goog.require('Blockly.utils.dom'); + + +/** + * Class for a zoom controls. + * @param {!Blockly.WorkspaceSvg} workspace The workspace to sit in. + * @constructor + */ +Blockly.ZoomControls = function(workspace) { + /** + * @type {!Blockly.WorkspaceSvg} + * @private + */ + this.workspace_ = workspace; +}; + +/** + * Width of the zoom controls. + * @type {number} + * @private + */ +Blockly.ZoomControls.prototype.WIDTH_ = 32; + +/** + * Height of the zoom controls. + * @type {number} + * @private + */ +Blockly.ZoomControls.prototype.HEIGHT_ = 110; + +/** + * Distance between zoom controls and bottom edge of workspace. + * @type {number} + * @private + */ +Blockly.ZoomControls.prototype.MARGIN_BOTTOM_ = 20; + +/** + * Distance between zoom controls and right edge of workspace. + * @type {number} + * @private + */ +Blockly.ZoomControls.prototype.MARGIN_SIDE_ = 20; + +/** + * The SVG group containing the zoom controls. + * @type {SVGElement} + * @private + */ +Blockly.ZoomControls.prototype.svgGroup_ = null; + +/** + * Left coordinate of the zoom controls. + * @type {number} + * @private + */ +Blockly.ZoomControls.prototype.left_ = 0; + +/** + * Top coordinate of the zoom controls. + * @type {number} + * @private + */ +Blockly.ZoomControls.prototype.top_ = 0; + +/** + * Create the zoom controls. + * @return {!SVGElement} The zoom controls SVG group. + */ +Blockly.ZoomControls.prototype.createDom = function() { + this.svgGroup_ = + Blockly.utils.dom.createSvgElement('g', {}, null); + + // Each filter/pattern needs a unique ID for the case of multiple Blockly + // instances on a page. Browser behaviour becomes undefined otherwise. + // https://neil.fraser.name/news/2015/11/01/ + var rnd = String(Math.random()).substring(2); + this.createZoomOutSvg_(rnd); + this.createZoomInSvg_(rnd); + if (this.workspace_.isMovable()) { + // If we zoom to the center and the workspace isn't movable we could + // loose blocks at the edges of the workspace. + this.createZoomResetSvg_(rnd); + } + return this.svgGroup_; +}; + +/** + * Initialize the zoom controls. + * @param {number} verticalSpacing Vertical distances from workspace edge to the + * same edge of the controls. + * @return {number} Vertical distance from workspace edge to the opposite + * edge of the controls. + */ +Blockly.ZoomControls.prototype.init = function(verticalSpacing) { + this.verticalSpacing_ = this.MARGIN_BOTTOM_ + verticalSpacing; + return this.verticalSpacing_ + this.HEIGHT_; +}; + +/** + * Dispose of this zoom controls. + * Unlink from all DOM elements to prevent memory leaks. + */ +Blockly.ZoomControls.prototype.dispose = function() { + if (this.svgGroup_) { + Blockly.utils.dom.removeNode(this.svgGroup_); + } +}; + +/** + * Position the zoom controls. + * It is positioned in the opposite corner to the corner the + * categories/toolbox starts at. + */ +Blockly.ZoomControls.prototype.position = function() { + // Not yet initialized. + if (!this.verticalSpacing_) { + return; + } + var metrics = this.workspace_.getMetrics(); + if (!metrics) { + // There are no metrics available (workspace is probably not visible). + return; + } + if (metrics.toolboxPosition == Blockly.TOOLBOX_AT_LEFT || + (this.workspace_.horizontalLayout && !this.workspace_.RTL)) { + // Toolbox starts in the left corner. + this.left_ = metrics.viewWidth + metrics.absoluteLeft - + this.WIDTH_ - this.MARGIN_SIDE_ - Blockly.Scrollbar.scrollbarThickness; + } else { + // Toolbox starts in the right corner. + this.left_ = this.MARGIN_SIDE_ + Blockly.Scrollbar.scrollbarThickness; + } + + if (metrics.toolboxPosition == Blockly.TOOLBOX_AT_BOTTOM) { + this.top_ = this.verticalSpacing_; + this.zoomInGroup_.setAttribute('transform', 'translate(0, 34)'); + if (this.zoomResetGroup_) { + this.zoomResetGroup_.setAttribute('transform', 'translate(0, 77)'); + } + } else { + this.top_ = metrics.viewHeight + metrics.absoluteTop - + this.HEIGHT_ - this.verticalSpacing_; + this.zoomInGroup_.setAttribute('transform', 'translate(0, 43)'); + this.zoomOutGroup_.setAttribute('transform', 'translate(0, 77)'); + } + + this.svgGroup_.setAttribute('transform', + 'translate(' + this.left_ + ',' + this.top_ + ')'); +}; + +/** + * Create the zoom in icon and its event handler. + * @param {string} rnd The random string to use as a suffix in the clip path's + * ID. These IDs must be unique in case there are multiple Blockly + * instances on the same page. + * @private + */ +Blockly.ZoomControls.prototype.createZoomOutSvg_ = function(rnd) { + /* This markup will be generated and added to the .svgGroup_: + + + + + */ + var ws = this.workspace_; + this.zoomOutGroup_ = Blockly.utils.dom.createSvgElement('g', + {'class': 'blocklyZoom'}, this.svgGroup_); + var clip = Blockly.utils.dom.createSvgElement('clipPath', + { + 'id': 'blocklyZoomoutClipPath' + rnd + }, + this.zoomOutGroup_); + Blockly.utils.dom.createSvgElement('rect', + { + 'width': 32, + 'height': 32, + }, + clip); + var zoomoutSvg = Blockly.utils.dom.createSvgElement('image', + { + 'width': Blockly.SPRITE.width, + 'height': Blockly.SPRITE.height, + 'x': -64, + 'y': -92, + 'clip-path': 'url(#blocklyZoomoutClipPath' + rnd + ')' + }, + this.zoomOutGroup_); + zoomoutSvg.setAttributeNS(Blockly.utils.dom.XLINK_NS, 'xlink:href', + ws.options.pathToMedia + Blockly.SPRITE.url); + + // Attach listener. + Blockly.bindEventWithChecks_(zoomoutSvg, 'mousedown', null, function(e) { + ws.markFocused(); + ws.zoomCenter(-1); + Blockly.Touch.clearTouchIdentifier(); // Don't block future drags. + e.stopPropagation(); // Don't start a workspace scroll. + e.preventDefault(); // Stop double-clicking from selecting text. + }); +}; + +/** + * Create the zoom out icon and its event handler. + * @param {string} rnd The random string to use as a suffix in the clip path's + * ID. These IDs must be unique in case there are multiple Blockly + * instances on the same page. + * @private + */ +Blockly.ZoomControls.prototype.createZoomInSvg_ = function(rnd) { + /* This markup will be generated and added to the .svgGroup_: + + + + + + + */ + var ws = this.workspace_; + this.zoomInGroup_ = Blockly.utils.dom.createSvgElement('g', + {'class': 'blocklyZoom'}, this.svgGroup_); + var clip = Blockly.utils.dom.createSvgElement('clipPath', + { + 'id': 'blocklyZoominClipPath' + rnd + }, + this.zoomInGroup_); + Blockly.utils.dom.createSvgElement('rect', + { + 'width': 32, + 'height': 32, + }, + clip); + var zoominSvg = Blockly.utils.dom.createSvgElement('image', + { + 'width': Blockly.SPRITE.width, + 'height': Blockly.SPRITE.height, + 'x': -32, + 'y': -92, + 'clip-path': 'url(#blocklyZoominClipPath' + rnd + ')' + }, + this.zoomInGroup_); + zoominSvg.setAttributeNS(Blockly.utils.dom.XLINK_NS, 'xlink:href', + ws.options.pathToMedia + Blockly.SPRITE.url); + + // Attach listener. + Blockly.bindEventWithChecks_(zoominSvg, 'mousedown', null, function(e) { + ws.markFocused(); + ws.zoomCenter(1); + Blockly.Touch.clearTouchIdentifier(); // Don't block future drags. + e.stopPropagation(); // Don't start a workspace scroll. + e.preventDefault(); // Stop double-clicking from selecting text. + }); +}; + +/** + * Create the zoom reset icon and its event handler. + * @param {string} rnd The random string to use as a suffix in the clip path's + * ID. These IDs must be unique in case there are multiple Blockly + * instances on the same page. + * @private + */ +Blockly.ZoomControls.prototype.createZoomResetSvg_ = function(rnd) { + /* This markup will be generated and added to the .svgGroup_: + + + + + + + */ + var ws = this.workspace_; + this.zoomResetGroup_ = Blockly.utils.dom.createSvgElement('g', + {'class': 'blocklyZoom'}, this.svgGroup_); + var clip = Blockly.utils.dom.createSvgElement('clipPath', + { + 'id': 'blocklyZoomresetClipPath' + rnd + }, + this.zoomResetGroup_); + Blockly.utils.dom.createSvgElement('rect', + { + 'width': 32, + 'height': 32 + }, + clip); + var zoomresetSvg = Blockly.utils.dom.createSvgElement('image', + { + 'width': Blockly.SPRITE.width, + 'height': Blockly.SPRITE.height, + 'y': -92, + 'clip-path': 'url(#blocklyZoomresetClipPath' + rnd + ')' + }, + this.zoomResetGroup_); + zoomresetSvg.setAttributeNS(Blockly.utils.dom.XLINK_NS, 'xlink:href', + ws.options.pathToMedia + Blockly.SPRITE.url); + + // Attach event listeners. + Blockly.bindEventWithChecks_(zoomresetSvg, 'mousedown', null, function(e) { + ws.markFocused(); + ws.setScale(ws.options.zoomOptions.startScale); + ws.beginCanvasTransition(); + ws.scrollCenter(); + setTimeout(ws.endCanvasTransition.bind(ws), 500); + Blockly.Touch.clearTouchIdentifier(); // Don't block future drags. + e.stopPropagation(); // Don't start a workspace scroll. + e.preventDefault(); // Stop double-clicking from selecting text. + }); +}; + +/** + * CSS for zoom controls. See css.js for use. + */ +Blockly.Css.register([ + /* eslint-disable indent */ + '.blocklyZoom>image, .blocklyZoom>svg>image {', + 'opacity: .4;', + '}', + + '.blocklyZoom>image:hover, .blocklyZoom>svg>image:hover {', + 'opacity: .6;', + '}', + + '.blocklyZoom>image:active, .blocklyZoom>svg>image:active {', + 'opacity: .8;', + '}' + /* eslint-enable indent */ +]); diff --git a/pool/shard001/JavaScript/0006458_openurl.js b/pool/shard001/JavaScript/0006458_openurl.js new file mode 100644 index 0000000000000000000000000000000000000000..2c42de5bfcfdb54219dff755603d04e88990d47a --- /dev/null +++ b/pool/shard001/JavaScript/0006458_openurl.js @@ -0,0 +1,64 @@ +/** + * # openurl + * Copyright(c) 2015 Stefano Balietti + * MIT Licensed + * + * Open a phantomjs instance to the specified url + * + * This file is executed via `#ServerChannel.connectPhantom()`. + * + * http://www.nodegame.org + */ + +"use strict"; + +var webpage = require('webpage'); +var system = require('system'); + +var url, page; + +if (system.args.length < 2) { + console.log('Need URL!'); + phantom.exit(); +} +url = system.args[1]; + +page = webpage.create(); + +page.viewportSize = { + width: 1366, + height: 768 +}; + + +page.onConsoleMessage = function(msg) { + if (msg === 'PHANTOMJS EXITING') phantom.exit(); + console.log(msg); +}; + +page.open(url, function() { + setTimeout(function() { + page.evaluate(function() { + + // PhantomJS does not have the .click() method. + if (!HTMLElement.prototype.click) { + HTMLElement.prototype.click = function() { + var ev = document.createEvent('MouseEvent'); + ev.initMouseEvent( + 'click', + /*bubble*/true, /*cancelable*/true, + window, null, + 0, 0, 0, 0, /*coordinates*/ + false, false, false, false, /*modifier keys*/ + 0/*button=left*/, null + ); + this.dispatchEvent(ev); + }; + } + + node.events.ee.ng.on('GAME_OVER', function() { + console.log('PHANTOMJS EXITING'); + }); + }); + }, 1000); +}); diff --git a/pool/shard001/JavaScript/0006462_StatisticalView.js b/pool/shard001/JavaScript/0006462_StatisticalView.js new file mode 100644 index 0000000000000000000000000000000000000000..588222858bef954954b78f4ad8a72d78408ab5a2 --- /dev/null +++ b/pool/shard001/JavaScript/0006462_StatisticalView.js @@ -0,0 +1,147 @@ +'use strict'; + +App.View.Tool.Statistical = Backbone.View.extend({ + _template: _.template( $('#tool-statistical_template').html() ), + _template_field_options: _.template( $('#tool-statistical_field_options').html() ), + + initialize: function(options) { + this._outputType = false; + this._title = 'Statistical report'; + App.View.Tool.Overlay.prototype.initialize.apply(this,[options]); + this.model.unset('overlay'); + this.reportView = options.reportView; + this._parentView = options.parentView; + }, + + events: { + 'change [name="input"]' : '_updateField', + 'change [name="field"]' : '_fieldChange', + 'click a.add': '_addField', + 'click a.remove': '_removeField', + 'click a.run': '_runTool', + 'click a.cancel': '_cancelTool', + 'keyup [name]' : '_checkFields', + 'change select' : '_checkFields', + 'click input[type="checkbox"]' : '_checkFields', + 'click .button.notfilled.cancel' : '_closeTool', + }, + + onClose: function(){ + this.stopListening(); + }, + + _updateField:function(e){ + var _this = this; + var $select = this.$('select[name="field"]'); + $select.find('option:not(.choose)').remove() + this.$('.wraper_field.extra').remove(); + this.$('.wraper_field .options').children().remove(); + + this._geoVizModel.getSublayersFieldsByType($(e.currentTarget).val(), 'number', function(fields,errors){ + _this.currentFields = []; + _.each(fields, function(f) { + if(f!='cartodb_id' && f!='the_geom' && f!='the_geom_webmercator'){ + _this.currentFields.push(f); + $select.append(''); + } + }); + }); + }, + + _addField:function(e){ + e.preventDefault(); + var options = ''; + _.each(this.currentFields, function(f) { + options += '' + }); + this.$('.field_list').append('
      ' + +'
      ' + +' ' + +' ' + +'
      ' + +'
      ' + +'
      '); + this._checkFields(); + }, + + _removeField:function(e){ + e.preventDefault(); + $(e.currentTarget).closest('.wraper_field').remove(); + this._checkFields(); + }, + + _fieldChange:function(e){ + var options = $(e.currentTarget).closest('.wraper_field').find('.options'); + if(options.children().length == 0) + options.html(this._template_field_options()); + + this.$('.add').removeClass('hide'); + }, + + _runTool: function(cb){ + if(!this.$('.run').hasClass('disabled')){ + var reportModel = new App.Model.Report(); + reportModel.set('name', this.$('#output-name').val()); + reportModel.set('layer', this.$('[name="input"] option:selected').text()); + reportModel.set('layer_sql', this._geoVizModel.findSublayer(this.$('[name="input"]').val()).options.sql); + reportModel.set('fields',[]); + _.each(this.$('.field_list .wraper_field'),function(f) { + var json = {'name':$(f).find('[name="field"]').val(), 'operations':[]}; + _.each($(f).find('input:checked'),function(i) { + json.operations.push($(i).val()); + }); + reportModel.get('fields').push(json) + }); + + this.reportView.reportCollection.add(reportModel); + this._geoVizModel.set('reports',this.reportView.reportCollection.toJSON()); + this._geoVizModel.save(); + } + }, + + _checkFields:function(){ + var enable = true; + if(this.$('#output-name').val() == '') + enable = false; + + if(this.$('select[name=input]') == 'Choose field...') + enable = false; + + var fields = this.$('.wraper_field'); + _.each(fields,function(f) { + if($(f).find('select[name=field]').val() == 'Choose field...') + enable = false; + if($(f).find('.options').length == 0 || $(f).find('.options input[type=checkbox]:checked').length == 0) + enable = false; + }); + + if(enable) + this.$('.run').removeClass('disabled'); + else + this.$('.run').addClass('disabled'); + + }, + + _closeTool:function(e){ + e.preventDefault(); + this._parentView._closeTool(); + }, + + render: function(){ + + this.$el.html(this._template({title: this._title})); + + var inputLayers = this._geoVizModel.getSublayers({only_ready: true}); + var $select = this.$('select[name="input"]'); + for (var i in inputLayers){ + if(!inputLayers[i].geoLayer) + $select.append(''); + } + + return this; + } + +}); diff --git a/pool/shard001/JavaScript/0006463_user-status.directive.js b/pool/shard001/JavaScript/0006463_user-status.directive.js new file mode 100644 index 0000000000000000000000000000000000000000..1e69b93b3592a90ca7e55eae812345e2eebdc6da --- /dev/null +++ b/pool/shard001/JavaScript/0006463_user-status.directive.js @@ -0,0 +1,35 @@ +/*global angular*/ +(function() { + 'use strict'; + + /*global angular*/ + angular.module('MealCalories').directive('mcUserStatus', mcUserStatus); + + /** + * @ngInject + */ + function mcUserStatus(mcLogin) { + function linkFn(scope) { + var onUpdate; + scope.user = null; + + mcLogin.initPromise.then(update); + onUpdate = mcLogin.onUpdate(update); + scope.$on('$destory', destroy); + + function update() { + scope.user = mcLogin.user(); + } + function destroy() { + onUpdate(); + } + } + + return { + restrict: 'E', + replace: true, + link:linkFn, + templateUrl: 'html/user-status.html' + }; + } +}()); diff --git a/pool/shard001/JavaScript/0006466_index.js b/pool/shard001/JavaScript/0006466_index.js new file mode 100644 index 0000000000000000000000000000000000000000..ac1cc647ea06063549da35f72e6d807ed2748984 --- /dev/null +++ b/pool/shard001/JavaScript/0006466_index.js @@ -0,0 +1,88 @@ +var postcss = require('postcss'); + +module.exports = postcss.plugin('postcss-nested', function (opts) { + var bubble = ['document', 'media', 'supports']; + var name = 'nest'; + + if (opts && opts.bubble) bubble = bubble.concat(opts.bubble); + if (opts && opts.prefix) name = '-' + opts.prefix + '-' + name; + + return function (css) { + css.walk(function (target) { + var rule = target.parent; + var root = rule && rule.parent; + + var isAtRule = target.type === 'atrule'; + var isRule = target.type === 'rule'; + + if (root && rule.type === 'rule') { + var newrule = postcss.rule({ + source: target.source + }); + + if (isRule && target.selectors.every(function (selector) { + return selector.lastIndexOf('&') === 0; + })) { + target.remove(); + + newrule.selector = target.selector; + + newrule.append(target.nodes); + + transpileSelectors(rule, newrule); + + root.insertAfter(rule.insertAfterNode || rule, newrule); + + rule.insertAfterNode = newrule; + } else if (isAtRule && target.name === name && ~target.params.indexOf('&')) { + target.remove(); + + newrule.selector = target.params; + + newrule.append(target.nodes); + + transpileSelectors(rule, newrule); + + root.insertAfter(rule.insertAfterNode || rule, newrule); + + rule.insertAfterNode = newrule; + } else if (isAtRule && ~bubble.indexOf(target.name)) { + var selector = rule.selector; + + if (root.type === 'atrule' && root.name === target.name && root.parent) { + target.params = root.params + ' and ' + target.params; + + rule = root; + root = root.parent; + } + + target.remove(); + + newrule.selector = selector; + + newrule.append(target.nodes); + + target.removeAll(); + + target.append(newrule); + + root.insertAfter(rule.insertAfterNode || rule, target); + + rule.insertAfterNode = target; + } + } + }); + }; +}); + +function transpileSelectors(fromRule, toRule) { + var selectors = []; + + fromRule.selectors.forEach(function (fromSelector) { + toRule.selectors.forEach(function (toSelector) { + selectors.push(toSelector.replace(/&/g, fromSelector)); + }); + }); + + toRule.selectors = selectors; +} diff --git a/pool/shard001/JavaScript/0006467_test-monit.js b/pool/shard001/JavaScript/0006467_test-monit.js new file mode 100644 index 0000000000000000000000000000000000000000..85f8ea935b2f59e406446b53dfe2bb040fd65f26 --- /dev/null +++ b/pool/shard001/JavaScript/0006467_test-monit.js @@ -0,0 +1,40 @@ +// Generated by CoffeeScript 1.8.0 +(function() { + var async, cookie, m, monit, noteStore, url; + + monit = require('../server/monitor'); + + cookie = process.env.ZhiHu; + + noteStore = require('../server/noteStore'); + + async = require('async'); + + url = 'http://www.zhihu.com/collection/29469118'; + + m = new monit(url, noteStore, cookie); + + async.series([ + function(cb) { + console.log("here"); + return m.getLogPage(function(err) { + if (err) { + return console.log(err); + } + return cb(); + }); + }, function(cb) { + var $; + $ = m.$; + return m.checkFav($, function(err) { + if (err) { + return console.log(err); + } + return cb(); + }); + } + ]); + +}).call(this); + +//# sourceMappingURL=test-monit.js.map diff --git a/pool/shard001/JavaScript/0006472_task_card_mini_menu.js b/pool/shard001/JavaScript/0006472_task_card_mini_menu.js new file mode 100644 index 0000000000000000000000000000000000000000..932c28fd8f7b69ec5b225e1a6f68df8b533b8f8f --- /dev/null +++ b/pool/shard001/JavaScript/0006472_task_card_mini_menu.js @@ -0,0 +1,67 @@ +'use strict'; +const _ = require('lodash'); +const ko = require('knockout'); +const EventEmitter2 = require('eventemitter2'); +const TaskCardMiniMenuView = require('./task_card_mini_menu_view'); + +class TaskCardMiniMenu extends EventEmitter2 { + constructor ({eventEmitterOptions = {}} = {}) { + super(eventEmitterOptions); + } + + onClickTaskDetail (task) { + this.emit('clickTaskDetail', {task}); + } + + onClickTaskNextStage (task) { + this.emit('clickTaskNextStage', {task}); + } + + onClickTaskArchive (task) { + this.emit('clickTaskArchive', {task}); + } + + onClickTaskAssign (task) { + this.emit('clickTaskAssign', {task}); + } + + onClickTaskPrevStage (task) { + this.emit('clickTaskPrevStage', {task}); + } + + onLoad (viewModel) { + this.emit('load', {viewModel}); + } + + register () { + const taskCardMiniMenu = this; + + ko.components.register('task-card-mini-menu', { + viewModel: function (params) { + this.task = params.task; + this.element = params.element; + + this.enabledNextStageItem = ko.pureComputed(() => !_.includes(['ready', 'archive'], this.task.stage().name())); + this.enabledPrevStageItem = ko.pureComputed(() => !_.includes(['memo', 'done'], this.task.stage().name())); + + this.onClickTaskDetail = taskCardMiniMenu.onClickTaskDetail.bind(taskCardMiniMenu, this.task); + this.onClickTaskNextStage = taskCardMiniMenu.onClickTaskNextStage.bind(taskCardMiniMenu, this.task); + this.onClickTaskArchive = taskCardMiniMenu.onClickTaskArchive.bind(taskCardMiniMenu, this.task); + this.onClickTaskAssign = taskCardMiniMenu.onClickTaskAssign.bind(taskCardMiniMenu, this.task); + this.onClickTaskPrevStage = taskCardMiniMenu.onClickTaskPrevStage.bind(taskCardMiniMenu, this.task); + + this.initRendered = ko.observable(false); + this.initRender = () => { this.initRendered(true); }; + + this.view = new TaskCardMiniMenuView(this.element); + + taskCardMiniMenu.onLoad(this); + }, + template: require('html-loader!./task_card_mini_menu.html') + }); + } +} + +TaskCardMiniMenu.TaskCardMiniMenuView = TaskCardMiniMenuView; + +module.exports = TaskCardMiniMenu; diff --git a/pool/shard001/JavaScript/0006476_index.js b/pool/shard001/JavaScript/0006476_index.js new file mode 100644 index 0000000000000000000000000000000000000000..516b7da1ba96e5a96f9d6d3b3b4da4e6da273ba3 --- /dev/null +++ b/pool/shard001/JavaScript/0006476_index.js @@ -0,0 +1,135 @@ +'use strict'; +var MqttClient = require('../client'), + url = require('url'), + xtend = require('xtend'), + protocols = {}, + protocolList = []; + +if ('browser' !== process.title) { + protocols.mqtt = require('./tcp'); + protocols.tcp = require('./tcp'); + protocols.ssl = require('./tls'); + protocols.tls = require('./tls'); + protocols.mqtts = require('./tls'); +} + +protocols.ws = require('./ws'); +protocols.wss = require('./ws'); + +protocolList = [ + 'mqtt', + 'mqtts', + 'ws', + 'wss' +]; + + +/** + * Parse the auth attribute and merge username and password in the options object. + * + * @param {Object} [opts] option object + */ +function parseAuthOptions (opts) { + var matches; + if (opts.auth) { + matches = opts.auth.match(/^(.+):(.+)$/); + if (matches) { + opts.username = matches[1]; + opts.password = matches[2]; + } else { + opts.username = opts.auth; + } + } +} + +/** + * connect - connect to an MQTT broker. + * + * @param {String} [brokerUrl] - url of the broker, optional + * @param {Object} opts - see MqttClient#constructor + */ +function connect (brokerUrl, opts) { + + if (('object' === typeof brokerUrl) && !opts) { + opts = brokerUrl; + brokerUrl = null; + } + + opts = opts || {}; + + if (brokerUrl) { + opts = xtend(url.parse(brokerUrl, true), opts); + opts.protocol = opts.protocol.replace(/\:$/, ''); + } + + // merge in the auth options if supplied + parseAuthOptions(opts); + + // support clientId passed in the query string of the url + if (opts.query && 'string' === typeof opts.query.clientId) { + opts.clientId = opts.query.clientId; + } + + if (opts.cert && opts.key) { + if (opts.protocol) { + if (-1 === ['mqtts', 'wss'].indexOf(opts.protocol)) { + /* + * jshint and eslint + * complains that break from default cannot be reached after throw + * it is a foced exit from a control structure + * maybe add a check after switch to see if it went through default + * and then throw the error + */ + /*jshint -W027*/ + /*eslint no-unreachable:1*/ + switch (opts.protocol) { + case 'mqtt': + opts.protocol = 'mqtts'; + break; + case 'ws': + opts.protocol = 'wss'; + break; + default: + throw new Error('Unknown protocol for secure conenction: "' + opts.protocol + '"!'); + break; + } + /*eslint no-unreachable:0*/ + /*jshint +W027*/ + } + } else { + // don't know what protocol he want to use, mqtts or wss + throw new Error('Missing secure protocol key'); + } + } + + if (!protocols[opts.protocol]) { + opts.protocol = protocolList.filter(function (key) { + return 'function' === typeof protocols[key]; + })[0]; + } + + if (false === opts.clean && !opts.clientId) { + throw new Error('Missing clientId for unclean clients'); + } + + + function wrapper (client) { + if (opts.servers) { + if (!client._reconnectCount || client._reconnectCount === opts.servers.length) { + client._reconnectCount = 0; + } + + opts.host = opts.servers[client._reconnectCount].host; + opts.port = opts.servers[client._reconnectCount].port; + + client._reconnectCount++; + } + + return protocols[opts.protocol](client, opts); + } + + return new MqttClient(wrapper, opts); +} + +module.exports = connect; +module.exports.connect = connect; diff --git a/pool/shard001/JavaScript/0006479_header-tabela-mutante.directive.js b/pool/shard001/JavaScript/0006479_header-tabela-mutante.directive.js new file mode 100644 index 0000000000000000000000000000000000000000..21d3944aea9da1a071205b410f92580d3b1e0627 --- /dev/null +++ b/pool/shard001/JavaScript/0006479_header-tabela-mutante.directive.js @@ -0,0 +1,86 @@ +//Modulo admin +(function() { + + 'use strict'; + + angular.module('front-alego') + + .directive('frontAlegoHeaderTabelaMutante', ['$window',function($window){ + return { + restrict: 'E', + transclude: true, + replace: true, + scope: { + titulo: "@", + subtitulo: "@", + linkNewTitulo: "@", + linkNewState: "@", + linkShowTitulo: "@", + linkShowState: "@", + linkEditTitulo: "@", + linkEditState: "@", + exibirBotaoVoltar: "@", + busca: "=", + termo: "=" + }, + controller: ['$scope','$rootScope',function($scope, $rootScope) { + $scope.mudarPreferencia = mudarPreferencia; + $scope.deveExibirControlesTabela = deveExibirControlesTabela; + $scope.voltar = voltar; + + $scope.modo = $window.localStorage.getItem('preferencia_visualizacao_conteudo'); + + if(!$scope.modo) { + $scope.modo = "tabela"; + } + + function deveExibirControlesTabela() { + return $scope.busca !== undefined; + } + + function mudarPreferencia(tipoVisualizacao) { + $scope.modo = tipoVisualizacao; + $window.localStorage.setItem('preferencia_visualizacao_conteudo', tipoVisualizacao); + $rootScope.$broadcast("atualizar-tabela-mutante"); + } + + function voltar() { + $window.history.back(); + } + + }], + templateUrl: "front-alego/header-tabela-mutante.html" + }; + }]) + + + .directive('frontAlegoTabelaMutante', ['$window',function($window){ + return { + link: function(scope, element) { + atualizarTabelaMutante(); + + scope.$on("atualizar-tabela-mutante", atualizarTabelaMutante); + + function atualizarTabelaMutante( ) { + var tipoAtual = "tab"; + var tipoAntigo = "tab--card"; + + + var preferencia = $window.localStorage.getItem('preferencia_visualizacao_conteudo'); + + if(preferencia == "card") { + tipoAtual = "tab--card"; + tipoAntigo = "tab"; + } + element.addClass(tipoAtual); + element.removeClass(tipoAntigo); + + } + + } + }; + }]); + + + +})(); diff --git a/pool/shard001/JavaScript/0006481_angular.switchery.js b/pool/shard001/JavaScript/0006481_angular.switchery.js new file mode 100644 index 0000000000000000000000000000000000000000..f9441ec1ace58f7be70e215a31e0dda37f3328c2 --- /dev/null +++ b/pool/shard001/JavaScript/0006481_angular.switchery.js @@ -0,0 +1,65 @@ +(function (window, document) { + angular.module('angular.switchery', []).directive('inputSwitchery', function ($timeout) { + return { + restrict: 'A', + require: '?ngModel', + link: function ($scope, $element, $attrs, $ngModel) { + $ngModel = $ngModel || { + "$setViewValue": angular.noop + } + $ngModel.$render = function () { + if ($ngModel.$viewValue === false || $ngModel.$viewValue === 0) { + $($element).find(".switchery").remove(); + $($element).html(""); + $timeout(function () { + Switchery($($element).find('input')[0], { + color: '#ED5565' + }); + }); + + if ($ngModel.$viewValue === false) { + $ngModel.$setViewValue(false); + } + if ($ngModel.$viewValue === 0) { + $ngModel.$setViewValue(0); + } + } else { + $($element).find(".switchery").remove(); + $($element).html(""); + $timeout(function () { + Switchery($($element).find('input')[0], { + color: '#ED5565' + }); + }); + if ($ngModel.$viewValue === true) { + $ngModel.$setViewValue(true); + } + if ($ngModel.$viewValue === 1) { + $ngModel.$setViewValue(1); + } + } + } + + $($element).append(""); + + $timeout(function () { + $($element).bind("click", function () { + + if ($ngModel.$viewValue === true) { + $ngModel.$setViewValue(false); + } else if ($ngModel.$viewValue === false) { + $ngModel.$setViewValue(true); + } + + if ($ngModel.$viewValue === 1) { + $ngModel.$setViewValue(0); + }else if ($ngModel.$viewValue === 0) { + $ngModel.$setViewValue(1); + } + + }); + }); + } + }; + }); +})(window, document); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006486_mainView.controllerSpec.js b/pool/shard001/JavaScript/0006486_mainView.controllerSpec.js new file mode 100644 index 0000000000000000000000000000000000000000..ec4598484f5407a426ed3c9db5bf6f1f55202110 --- /dev/null +++ b/pool/shard001/JavaScript/0006486_mainView.controllerSpec.js @@ -0,0 +1,126 @@ +describe('mainViewController', function() { + 'use strict'; + var offerSourceService; + beforeEach(function() { + module('mainViewController', function($provide) { + $provide.provider('offerSourceService', { + $get: function() { + return { + subscribeToChanges: jasmine.createSpy('subscribeToChanges'), + getCurrent: jasmine.createSpy('getCurrent'), + update: jasmine.createSpy('update'), + }; + } + }); + }); + inject(function(_offerSourceService_){ + offerSourceService = _offerSourceService_; + }); + }); + + describe('MainViewCtrl', function() { + var $scope, vm; + + describe('bootstrapping', function() { + describe('with offer source current value set for a region', function() { + beforeEach(inject(function($rootScope, $controller, favorites, $httpBackend) { + offerSourceService.getCurrent.and.returnValue({ + region: 'a-region' + }); + + $scope = $rootScope.$new(); + $controller('MainViewCtrl as vm', { + $scope: $scope + }); + vm = $scope.vm; + })); + + it('should set the offerSource state to that region', inject(function($httpBackend) { + expect(vm.state.sourceSelectionPopup).toBeFalsy(); + expect(vm.offerSource.region).toBe('a-region'); + })); + }); + + describe('with offer source current value set for location', function() { + beforeEach(inject(function($rootScope, $controller) { + offerSourceService.getCurrent.and.returnValue({ + location: true + }); + + $scope = $rootScope.$new(); + $controller('MainViewCtrl as vm', { + $scope: $scope + }); + vm = $scope.vm; + })); + + it('should open the source selection popup with locator enabled', function() { + expect(vm.state.sourceSelectionPopup).toBe('active'); + expect(vm.offerSource.location).toBe(true); + }); + }); + + describe('with no current offer source value set', function() { + beforeEach(inject(function($rootScope, $controller) { + $scope = $rootScope.$new(); + $controller('MainViewCtrl as vm', { + $scope: $scope + }); + vm = $scope.vm; + })); + + context('with Tallinn available as one of the sources', function() { + beforeEach(inject(function($httpBackend) { + $httpBackend.expectGET('api/v1/regions').respond([ + { + name: 'Tartu' + }, { + name: 'Tallinn' + } + ]); + $httpBackend.flush(); + })); + + it('should select Tallinn region', function() { + expect(vm.state.sourceSelectionPopup).not.toBe('active'); + expect(vm.state.isLocationSelectionEnabled).toBeFalsy(); + expect(offerSourceService.update).toHaveBeenCalledWith({ + region: 'Tallinn', + }); + }); + }); + + context('without Tallinn available as one of the sources', function() { + beforeEach(inject(function($httpBackend) { + $httpBackend.expectGET('api/v1/regions').respond([ + { + name: 'Tartu' + }, { + name: 'NotTallinn' + } + ]); + $httpBackend.flush(); + })); + + it('should open the source selection popup', function() { + expect(vm.state.sourceSelectionPopup).toBe('active'); + expect(vm.state.isLocationSelectionEnabled).toBeFalsy(); + }); + }); + + it('should keep offer source up to date', function() { + updateOfferSource({ + test: true, + }); + + expect(vm.offerSource.test).toBe(true); + }); + }); + }); + + function updateOfferSource(offerSource) { + var callback = offerSourceService.subscribeToChanges.calls.mostRecent().args[1]; + callback(offerSource); + } + }); +}); diff --git a/pool/shard001/JavaScript/0006487_config.js b/pool/shard001/JavaScript/0006487_config.js new file mode 100644 index 0000000000000000000000000000000000000000..458840e8d2a4935b6a360b245e70ca3210738a08 --- /dev/null +++ b/pool/shard001/JavaScript/0006487_config.js @@ -0,0 +1,79 @@ +'use strict'; + +/** + * Responsible for loading / finding Mocha's "rc" files. + * This doesn't have anything to do with `mocha.opts`. + * + * @private + * @module + */ + +const fs = require('fs'); +const findUp = require('findup-sync'); +const path = require('path'); +const debug = require('debug')('mocha:cli:config'); + +/** + * These are the valid config files, in order of precedence; + * e.g., if `.mocharc.js` is present, then `.mocharc.yaml` and the rest + * will be ignored. + * The user should still be able to explicitly specify a file. + * @private + */ +exports.CONFIG_FILES = [ + '.mocharc.js', + '.mocharc.yaml', + '.mocharc.yml', + '.mocharc.json' +]; + +/** + * Parsers for various config filetypes. Each accepts a filepath and + * returns an object (but could throw) + */ +const parsers = (exports.parsers = { + yaml: filepath => + require('js-yaml').safeLoad(fs.readFileSync(filepath, 'utf8')), + js: filepath => require(filepath), + json: filepath => + JSON.parse( + require('strip-json-comments')(fs.readFileSync(filepath, 'utf8')) + ) +}); + +/** + * Loads and parses, based on file extension, a config file. + * "JSON" files may have comments. + * @param {string} filepath - Config file path to load + * @returns {Object} Parsed config object + * @private + */ +exports.loadConfig = filepath => { + let config = {}; + const ext = path.extname(filepath); + try { + if (/\.ya?ml/.test(ext)) { + config = parsers.yaml(filepath); + } else if (ext === '.js') { + config = parsers.js(filepath); + } else { + config = parsers.json(filepath); + } + } catch (err) { + throw new Error(`failed to parse ${filepath}: ${err}`); + } + return config; +}; + +/** + * Find ("find up") config file starting at `cwd` + * @param {string} [cwd] - Current working directory + * @returns {string|null} Filepath to config, if found + */ +exports.findConfig = (cwd = process.cwd()) => { + const filepath = findUp(exports.CONFIG_FILES, {cwd}); + if (filepath) { + debug(`found config at ${filepath}`); + } + return filepath; +}; diff --git a/pool/shard001/JavaScript/0006491_imagesloaded.js b/pool/shard001/JavaScript/0006491_imagesloaded.js new file mode 100644 index 0000000000000000000000000000000000000000..df196f0988a86b59a74e2aec716cfa52b1364fd7 --- /dev/null +++ b/pool/shard001/JavaScript/0006491_imagesloaded.js @@ -0,0 +1,136 @@ +(function(){ + +// module factory: start + +var moduleFactory = function($) { +// module body: start + +var module = this; +var jQuery = $; +var exports = function() { + +/*! + * jQuery imagesLoaded plugin v2.0.1 + * http://github.com/desandro/imagesloaded + * + * MIT License. by Paul Irish et al. + */ + +/*jshint curly: true, eqeqeq: true, noempty: true, strict: true, undef: true, browser: true */ +/*global jQuery: false */ + +;(function($, undefined) { +'use strict'; + +// blank image data-uri bypasses webkit log warning (thx doug jones) +var BLANK = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw=='; + +$.fn.imagesLoaded = function( callback ) { + var $this = this, + deferred = $.isFunction($.Deferred) ? $.Deferred() : 0, + hasNotify = $.isFunction(deferred.notify), + $images = $this.find('img').add( $this.filter('img') ), + loaded = [], + proper = [], + broken = []; + + function doneLoading() { + var $proper = $(proper), + $broken = $(broken); + + if ( deferred ) { + if ( broken.length ) { + deferred.reject( $images, $proper, $broken ); + } else { + deferred.resolve( $images ); + } + } + + if ( $.isFunction( callback ) ) { + callback.call( $this, $images, $proper, $broken ); + } + } + + function imgLoaded( img, isBroken ) { + // don't proceed if BLANK image, or image is already loaded + if ( img.src === BLANK || $.inArray( img, loaded ) !== -1 ) { + return; + } + + // store element in loaded images array + loaded.push( img ); + + // keep track of broken and properly loaded images + if ( isBroken ) { + broken.push( img ); + } else { + proper.push( img ); + } + + // cache image and its state for future calls + $.data( img, 'imagesLoaded', { isBroken: isBroken, src: img.src } ); + + // trigger deferred progress method if present + if ( hasNotify ) { + deferred.notifyWith( $(img), [ isBroken, $images, $(proper), $(broken) ] ); + } + + // call doneLoading and clean listeners if all images are loaded + if ( $images.length === loaded.length ){ + setTimeout( doneLoading ); + $images.unbind( '.imagesLoaded' ); + } + } + + // if no images, trigger immediately + if ( !$images.length ) { + doneLoading(); + } else { + $images.bind( 'load.imagesLoaded error.imagesLoaded', function( event ){ + // trigger imgLoaded + imgLoaded( event.target, event.type === 'error' ); + }).each( function( i, el ) { + var src = el.src; + + // find out if this image has been already checked for status + // if it was, and src has not changed, call imgLoaded on it + var cached = $.data( el, 'imagesLoaded' ); + if ( cached && cached.src === src ) { + imgLoaded( el, cached.isBroken ); + return; + } + + // if complete is true and browser supports natural sizes, try + // to check for image status manually + if ( el.complete && el.naturalWidth !== undefined ) { + imgLoaded( el, el.naturalWidth === 0 || el.naturalHeight === 0 ); + return; + } + + // cached images don't fire load sometimes, so we reset src, but only when + // dealing with IE, or image is complete (loaded) and failed manual check + // webkit hack from http://groups.google.com/group/jquery-dev/browse_thread/thread/eee6ab7b2da50e1f + if ( el.readyState || el.complete ) { + el.src = BLANK; + el.src = src; + } + }); + } + + return deferred ? deferred.promise( $this ) : $this; +}; + +})(jQuery); +}; + +exports(); +module.resolveWith(exports); + +// module body: end + +}; +// module factory: end + +FD50.module("imagesloaded", moduleFactory); + +}()); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006496_give.js b/pool/shard001/JavaScript/0006496_give.js new file mode 100644 index 0000000000000000000000000000000000000000..29e4c35685ff22ccefbc5c0fba3ffb5654fc25ea --- /dev/null +++ b/pool/shard001/JavaScript/0006496_give.js @@ -0,0 +1,43 @@ +const { Command } = require('discord-akairo') +const Items = require('../../structures/items/') +const Inventory = require('../../structures/items/InventoryHandler') + +class GiveCommand extends Command { + constructor () { + super('give', { + aliases: ['give'], + ownerOnly: true, + channelRestriction: 'guild', + description: 'Give someone some items.', + split: 'sticky', + args: [ + { + id: 'user', + type (word, msg) { + if (word === 'me') return msg.author + return this.client.util.resolveUser( + word, + msg.guild.members.map(m => m.user) + ) + } + }, + { + id: 'items', + match: 'rest', + type: Items.resolveCollection + } + ] + }) + } + + async exec (msg, args) { + const { user, items } = args + if (!items.every(i => i)) return msg.util.error("couldn't resolve items.") + + const inventory = await Inventory.fetch(user.id) + inventory.add(items) + return msg.util.success(`gave ${user}: ${items}`) + } +} + +module.exports = GiveCommand diff --git a/pool/shard001/JavaScript/0006497_ftp_datastream.js b/pool/shard001/JavaScript/0006497_ftp_datastream.js new file mode 100644 index 0000000000000000000000000000000000000000..f5be74cd82165aa98b30c68f356314769d3cb8ea --- /dev/null +++ b/pool/shard001/JavaScript/0006497_ftp_datastream.js @@ -0,0 +1,149 @@ +if (!us) var us = {}; +if (!us.engy) us.engy = {}; +if (!us.engy.rehostImage) us.engy.rehostImage = {}; + +us.engy.rehostImage.ftpDatastream = function(host, port, sourceFile) { + this.host = host; + this.port = port; + this.sourceFile = sourceFile; + + this.transportService = Cc["@mozilla.org/network/socket-transport-service;1"].getService(Ci.nsISocketTransportService); + this.eventTarget = Cc["@mozilla.org/thread-manager;1"].getService().currentThread; + this.dataListener = new us.engy.rehostImage.dataListener(); + this.progressEventSink = new us.engy.rehostImage.progressEventSink(); +} + +us.engy.rehostImage.ftpDatastream.prototype = { + dataTransport: null, + dataInstream: null, + dataOutstream: null, + uploadInputStream: null, + + tempFile: null, + + listData: "", + finished: false, + connection: null, + + connectWrite: function() { + var fileSize2 = this.sourceFile.fileSize; + + var fileInputStream = Cc["@mozilla.org/network/file-input-stream;1"].createInstance(Ci.nsIFileInputStream); + fileInputStream.init(this.sourceFile, -1, 0, 0); + + this.uploadInputStream = fileInputStream; + + this.continueConnectWrite(fileSize2); + }, + + continueConnectWrite: function(fileSize) { + this.dataTransport = this.transportService.createTransport(null, 0, this.host, this.port, null); + + this.dataOutstream = this.dataTransport.openOutputStream(0, 0, -1); + + var binaryOutstream = Cc["@mozilla.org/binaryoutputstream;1"].createInstance(Ci.nsIBinaryOutputStream); + binaryOutstream.setOutputStream(this.dataOutstream); + + this.dataInstream = Cc["@mozilla.org/binaryinputstream;1"].createInstance(Ci.nsIBinaryInputStream); + this.dataInstream.setInputStream(this.uploadInputStream); + + this.progressEventSink.parent = this; + this.progressEventSink.dataInstream = this.dataInstream; + this.progressEventSink.dataOutstream = binaryOutstream; + this.progressEventSink.bytesTotal = fileSize; + + this.dataTransport.setEventSink(this.progressEventSink, this.eventTarget); + + var dataBuffer = this.dataInstream.readBytes(this.dataInstream.available() < 4096 ? this.dataInstream.available() : 4096); + this.progressEventSink.dataOutstream.writeBytes(dataBuffer, dataBuffer.length); + }, + + connectRead: function() { + this.dataTransport = this.transportService.createTransport(null, 0, this.host, this.port, null); + + var dataStream = this.dataTransport.openInputStream(0, 0, 0); + this.dataInstream = Cc["@mozilla.org/binaryinputstream;1"].createInstance(Ci.nsIBinaryInputStream); + this.dataInstream.setInputStream(dataStream); + + this.dataListener.parent = this; + this.dataListener.dataInstream = this.dataInstream; + + var pump = Cc["@mozilla.org/network/input-stream-pump;1"].createInstance(Ci.nsIInputStreamPump); + pump.init(dataStream, -1, -1, 0, 0, false); + pump.asyncRead(this.dataListener, null); + }, + + kill: function() { + if (this.dataInstream) { + this.dataInstream.close(); + } + + if (this.dataOutstream) { + this.dataOutstream.flush(); + this.dataOutstream.close(); + } + + if (this.uploadInputStream) { + this.uploadInputStream.close(); + } + + if (this.dataTransport) { + this.dataTransport.close("Finished"); + } + + this.dataListener.parent = null; + this.progressEventSink.parent = null; + this.finished = true; + + if (this.connection != null) { + this.connection.onDataStreamFinish(); + } + + this.connection = null; + } +} + +us.engy.rehostImage.dataListener = function () { } + +us.engy.rehostImage.dataListener.prototype = { + parent: null, + dataInstream: null, + data: "", + + onStartRequest: function(request, context) { + }, + + onStopRequest: function(request, context, status) { + if (this.parent) { + this.parent.listData = this.data; + this.parent.kill(); + } + }, + + onDataAvailable: function(request, context, inputStream, offset, count) { + this.data += this.dataInstream.readBytes(count); + } +} + +us.engy.rehostImage.progressEventSink = function() { } + +us.engy.rehostImage.progressEventSink.prototype = { + parent: null, + + dataInstream: null, + dataOutstream: null, + + bytesTotal: 0, + + onTransportStatus: function(transport, status, progress, progressMax) { + if (progress == this.bytesTotal) { // finished writing + this.parent.kill(); + return; + } + + us.engy.rehostImage.main.reportProgress((progress * 100) / this.bytesTotal); + + var dataBuffer = this.dataInstream.readBytes(this.dataInstream.available() < 4096 ? this.dataInstream.available() : 4096); + this.dataOutstream.writeBytes(dataBuffer, dataBuffer.length); + } +} \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006499_apply-rules.js b/pool/shard001/JavaScript/0006499_apply-rules.js new file mode 100644 index 0000000000000000000000000000000000000000..cb69b422bff7d2a369d8ef138d947f2a2741c282 --- /dev/null +++ b/pool/shard001/JavaScript/0006499_apply-rules.js @@ -0,0 +1,40 @@ +/* + * @license + * Copyright 2018 Brigham Young University + * + * 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. + */ + +"use strict"; + +module.exports = function findRedirect(rules, pathParts) { + const prefixMatch = findRedirectPrefix(rules.prefixes, pathParts); + return prefixMatch; +}; + +function findRedirectPrefix(prefixRules, pathParts) { + let current = prefixRules; + let match = null; + for (const part of pathParts) { + if (part in current) { + current = current[part]; + if ('|target|' in current) { + match = current['|target|']; + } + } else { + break; + } + } + return match; +} + diff --git a/pool/shard001/JavaScript/0006502_FloatButton.js b/pool/shard001/JavaScript/0006502_FloatButton.js new file mode 100644 index 0000000000000000000000000000000000000000..567a64302241726685c65c42ca59db422e35e38a --- /dev/null +++ b/pool/shard001/JavaScript/0006502_FloatButton.js @@ -0,0 +1,33 @@ +'use strict'; + +var React = require('react-native'); + +var { + StyleSheet, + View, + Image, + TouchableOpacity +} = React; + +var FloatButton = React.createClass({ + render: function(){ + return ( + + + + ); + } +}); + +var styles = StyleSheet.create({ + floatBtn: { + width: 70, + height: 70, + position: 'absolute', + bottom: 25, + right: 0, + backgroundColor: 'transparent' + } +}); + +module.exports = FloatButton; diff --git a/pool/shard001/JavaScript/0006503_tweens.js b/pool/shard001/JavaScript/0006503_tweens.js new file mode 100644 index 0000000000000000000000000000000000000000..dcdb991e294ba608ac553ee44e6dcc4044edc6ee --- /dev/null +++ b/pool/shard001/JavaScript/0006503_tweens.js @@ -0,0 +1,269 @@ +/** +@name glow.tweens +@namespace +@description Functions for modifying animations +@see What are tweens? + +*/ +(window.gloader || glow).module({ + name: "glow.tweens", + library: ["glow", "@VERSION@"], + depends: [], + builder: function(glow) { + + /* + PrivateMethod: _reverse + Takes a tween function and returns a function which does the reverse + */ + function _reverse(tween) { + return function(t) { + return 1 - tween(1 - t); + } + } + + glow.tweens = { + /** + @name glow.tweens.linear + @function + @description Returns linear tween. + + Will transition values from start to finish with no + acceleration or deceleration. + + @returns {Function} + */ + linear: function() { + return function(t) { return t; }; + }, + /** + @name glow.tweens.easeIn + @function + @description Creates a tween which starts off slowly and accelerates. + + @param {Number} [strength=2] How strong the easing is. + + A higher number means the animation starts off slower and + ends quicker. + + @returns {Function} + */ + easeIn: function(strength) { + strength = strength || 2; + return function(t) { + return Math.pow(1, strength - 1) * Math.pow(t, strength); + } + }, + /** + @name glow.tweens.easeOut + @function + @description Creates a tween which starts off fast and decelerates. + + @param {Number} [strength=2] How strong the easing is. + + A higher number means the animation starts off faster and + ends slower + + @returns {Function} + */ + easeOut: function(strength) { + return _reverse(this.easeIn(strength)); + }, + /** + @name glow.tweens.easeBoth + @function + @description Creates a tween which starts off slowly, accelerates then decelerates after the half way point. + + This produces a smooth and natural looking transition. + + @param {Number} [strength=2] How strong the easing is. + + A higher number produces a greater difference between + start / end speed and the mid speed. + + @returns {Function} + */ + easeBoth: function(strength) { + return this.combine(this.easeIn(strength), this.easeOut(strength)); + }, + /** + @name glow.tweens.overshootIn + @function + @description Returns the reverse of {@link glow.tweens.overshootOut overshootOut} + + @param {Number} [amount=1.70158] How much to overshoot. + + The default is 1.70158 which results in a 10% overshoot. + + @returns {Function} + */ + overshootIn: function(amount) { + return _reverse(this.overshootOut(amount)); + }, + /** + @name glow.tweens.overshootOut + @function + @description Creates a tween which overshoots its end point then returns to its end point. + + @param {Number} [amount=1.70158] How much to overshoot. + + The default is 1.70158 which results in a 10% overshoot. + + @returns {Function} + */ + overshootOut: function(amount) { + amount = amount || 1.70158; + return function(t) { + if (t == 0 || t == 1) { return t; } + return ((t -= 1)* t * ((amount + 1) * t + amount) + 1); + } + }, + /** + @name glow.tweens.overshootBoth + @function + @description Returns a combination of {@link glow.tweens.overshootIn overshootIn} and {@link glow.tweens.overshootOut overshootOut} + + @param {Number} [amount=1.70158] How much to overshoot. + + The default is 1.70158 which results in a 10% overshoot. + + @returns {Function} + */ + overshootBoth: function(amount) { + return this.combine(this.overshootIn(amount), this.overshootOut(amount)); + }, + /** + @name glow.tweens.bounceIn + @function + @description Returns the reverse of {@link glow.tweens.bounceOut bounceOut} + + @returns {Function} + */ + bounceIn: function() { + return _reverse(this.bounceOut()); + }, + /** + @name glow.tweens.bounceOut + @function + @description Returns a tween which bounces against the final value 3 times before stopping + + @returns {Function} + */ + bounceOut: function() { + return function(t) { + if (t < (1 / 2.75)) { + return 7.5625 * t * t; + } else if (t < (2 / 2.75)) { + return (7.5625 * (t -= (1.5 / 2.75)) * t + .75); + } else if (t < (2.5 / 2.75)) { + return (7.5625 * (t -= (2.25 / 2.75)) * t + .9375); + } else { + return (7.5625 * (t -= (2.625 / 2.75)) * t + .984375); + } + }; + }, + /** + @name glow.tweens.bounceBoth + @function + @description Returns a combination of {@link glow.tweens.bounceIn bounceIn} and {@link glow.tweens.bounceOut bounceOut} + + @returns {Function} + */ + bounceBoth: function() { + return this.combine(this.bounceIn(), this.bounceOut()); + }, + /** + @name glow.tweens.elasticIn + @function + @description Returns the reverse of {@link glow.tweens.elasticOut elasticOut} + + @param {Number} [amplitude=1] How strong the elasticity is. + + @param {Number} [period=0.3] The frequency period. + + @returns {Function} + */ + elasticIn: function(a, p) { + return _reverse(this.elasticOut(a, p)); + }, + /** + @name glow.tweens.elasticOut + @function + @description Creates a tween which has an elastic movement. + + You can tweak the tween using the parameters but you'll + probably find the defaults sufficient. + + @param {Number} [amplitude=1] How strong the elasticity is. + + @param {Number} [period=0.3] The frequency period. + + @returns {Function} + */ + elasticOut: function(a, p) { + return function (t) { + if (t == 0 || t == 1) { + return t; + } + if (!p) { + p = 0.3; + } + if (!a || a < 1) { + a = 1; + var s = p / 4; + } else { + var s = p / (2 * Math.PI) * Math.asin(1 / a); + } + return a * Math.pow(2, -10 * t) * Math.sin( (t-s) * (2 * Math.PI) / p) + 1; + } + }, + /** + @name glow.tweens.elasticBoth + @function + @description Returns a combination of {@link glow.tweens.elasticIn elasticIn} and {@link glow.tweens.elasticOut elasticOut} + + @param {Number} [amplitude=1] How strong the elasticity is. + + @param {Number} [period=0.3] The frequency period. + + @returns {Function} + */ + elasticBoth: function(a, p) { + p = p || 0.45; + return this.combine(this.elasticIn(a, p), this.elasticOut(a, p)); + }, + /** + @name glow.tweens.combine + @function + @description Create a tween from two tweens. + + This can be useful to make custom tweens which, for example, + start with an easeIn and end with an overshootOut. To keep + the motion natural, you should configure your tweens so the + first ends and the same velocity that the second starts. + + @param {Function} tweenIn Tween to use for the first half + + @param {Function} tweenOut Tween to use for the second half + + @example + // 4.5 has been chosen for the easeIn strength so it + // ends at the same velocity as overshootOut starts. + var myTween = glow.tweens.combine( + glow.tweens.easeIn(4.5), + glow.tweens.overshootOut() + ); + + @returns {Function} + */ + combine: function(tweenIn, tweenOut) { + return function (t) { + if (t < 0.5) { + return tweenIn(t * 2) / 2; + } else { + return tweenOut((t - 0.5) * 2) / 2 + 0.5; + } + } + } + }; + } +}); diff --git a/pool/shard001/JavaScript/0006506_note.js b/pool/shard001/JavaScript/0006506_note.js new file mode 100644 index 0000000000000000000000000000000000000000..4d197039175827097595822b4140131196eb9d2c --- /dev/null +++ b/pool/shard001/JavaScript/0006506_note.js @@ -0,0 +1,176 @@ +$(function() { + + var currentEditingNoteId, + sending = false; + + $('#note-create').focus(function() { + var $editor = $(this); + $(this).summernote({lang: 'ko-KR', + focus: true, + oninit: function() { + if($(window).height() > 400) + $('#note-create-cancel-btn').show(); + $('#btn-create-btn').prop('disabled', false); + $editor.find('.note-editable').css('max-height', $(window).height()-100); + } + }); + }); + + $('.note-create-form').submit(function() { + + if(sending) return false; + + var $form = $(this), + $textarea = $form.find('textarea[name="note.text"]'), + code = $('#note-create').code(); + + $textarea.val(code); + + if(code == '' || code == '


      ') { + alert('내용을 입력해 주세요.'); + $('#note-create').summernote({focus:true}); + return false; + } + + sending = true; + + return true; + }); + + $('#note-create-cancel-btn').click(function() { + var code = $('#note-create').code(); + if(code == '' || code == '


      ' + || confirm('작성중 이던 내용을 취소하시겠습니까?')) { + closeNoteCreate(); + } + }); + + var closeNoteCreate = function(id) { + $('#note-create-cancel-btn').hide(); + $('#btn-create-btn').prop('disabled', true); + $('#note-create').destroy().val(''); + }; + + var closeNoteEdit = function(id) { + $('#note-edit-'+id).destroy().detach(); + $('#note-text-'+id).show(); + $('#content-function-cog-'+id) + .find('.buttons').hide() + .end().find('.dropdown').show(); + }; + + var closeCurrentNoteEdit = function() { + if(confirm('수정중 이던 내용을 취소하시겠습니까?')) { + closeNoteEdit(currentEditingNoteId); + currentEditingNoteId = null; + } + }; + + $('.note-edit-cancel-btn').click(closeCurrentNoteEdit); + + $('.note-edit-btn').click(function() { + + if(sending) return false; + + var id = $(this).data('id'); + + if(currentEditingNoteId) + closeCurrentNoteEdit(); + + currentEditingNoteId = id; + + $('#content-function-cog-'+id) + .find('.dropdown .fa').addClass('fa-spin'); + + sending = true; + + $.ajax({ + url:contextPath+'/content/edit/'+id+'.json', + dataType: 'json', + type: 'get', + success: function(result) { + $('#note-text-' + id).hide(); + $('#content-function-cog-' + id) + .find('.buttons').show() + .end().find('.dropdown').hide() + .find('.fa').removeClass('fa-spin'); + + $('') + .val(result.text) + .insertAfter('#note-text-' + id) + .summernote({lang: 'ko-KR', + focus: true, + oninit: function () { + if ($(window).height() > 400) + $('.note-editable').css('max-height', $(window).height() - 100); + } + } + ); + }, + complete: function() { + sending = false; + } + }); + }); + + $('.note-update-form').submit(function() { + + if(sending) return false; + + var id = $(this).data('id'), + $form = $(this); + + $form.find('textarea[name="text"]').val($('#note-edit-'+id).code()); + + sending = true; + + $.ajax({ + url: $form.attr('action') + '.json', + dataType: 'json', + type: $form.attr('method'), + data: $form.serialize(), + success : function(result) { + $('#note-text-'+id).html(result.text) + .find('code').each(function(i ,el) { + Prism.highlightElement(el); + }); + closeNoteEdit(id); + currentEditingNoteId = null; + }, + complete: function() { + sending = false; + } + }); + + return false; + }); + + $('.note-delete-btn').click(function() { + + if(sending) return false; + + if(confirm('정말로 삭제 하시겠습니까?')) { + + var id = $(this).data('id'), + $form = $('#note-delete-form-'+id); + + sending = true; + + $.ajax({ + url: $form.attr('action') + '.json', + dataType: 'json', + type: $form.attr('method'), + data: $form.serialize(), + success : function(result) { + $('#note-'+id).detach(); + $('#note-count').text(function(i, count) { + return parseInt(count, 10)-1; + }); + }, + complete: function() { + sending = false; + } + }); + } + }); +}); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006507_game.js b/pool/shard001/JavaScript/0006507_game.js new file mode 100644 index 0000000000000000000000000000000000000000..9e07e719d6699160e669384db5876fea30cacb1c --- /dev/null +++ b/pool/shard001/JavaScript/0006507_game.js @@ -0,0 +1,24 @@ +// window/global scope +var rush = rush || {}; + + +window.onload = function() { + // entry point + rush.game = new rush.Game(); + + // listen to the a-href buttons + var startButton = document.getElementById('start-btn'); + startButton.onclick = function() { + var menuScene = document.getElementById('menu'); + menuScene.classList.add('hidden'); + rush.game.initGame(); + } + + var restartButton = document.getElementById('restart-btn'); + restartButton.onclick = function() { + var gameoverScene = document.getElementById('gameover'); + gameoverScene.classList.add('hidden'); + rush.game.initGame(); + } + +}; \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006509_read-and-write.js b/pool/shard001/JavaScript/0006509_read-and-write.js new file mode 100644 index 0000000000000000000000000000000000000000..bcae4ccc7ae19642aeeec6ac0e5666dfc14a4d0f --- /dev/null +++ b/pool/shard001/JavaScript/0006509_read-and-write.js @@ -0,0 +1,155 @@ +// These samples are intended for Web so this import would normally be +// done in HTML however using modules here is more convenient for +// ensuring sample correctness offline. +import firebase from "firebase/app"; +import "firebase/database"; + +// [START rtdb_write_new_user] +function writeUserData(userId, name, email, imageUrl) { + firebase.database().ref('users/' + userId).set({ + username: name, + email: email, + profile_picture : imageUrl + }); +} +// [END rtdb_write_new_user] + +function writeUserDataWithCompletion(userId, name, email, imageUrl) { + // [START rtdb_write_new_user_completion] + firebase.database().ref('users/' + userId).set({ + username: name, + email: email, + profile_picture : imageUrl + }, (error) => { + if (error) { + // The write failed... + } else { + // Data saved successfully! + } + }); + // [END rtdb_write_new_user_completion] +} + +function socialListenStarCount() { + const postElement = document.querySelector('#post'); + const postId = "1234"; + function updateStarCount(a, b) { + // ... + } + + // [START rtdb_social_listen_star_count] + var starCountRef = firebase.database().ref('posts/' + postId + '/starCount'); + starCountRef.on('value', (snapshot) => { + const data = snapshot.val(); + updateStarCount(postElement, data); + }); + // [END rtdb_social_listen_star_count] +} + +function socialSingleValueRead() { + // [START rtdb_social_single_value_read] + var userId = firebase.auth().currentUser.uid; + return firebase.database().ref('/users/' + userId).once('value').then((snapshot) => { + var username = (snapshot.val() && snapshot.val().username) || 'Anonymous'; + // ... + }); + // [END rtdb_social_single_value_read] +} + +// [START rtdb_social_write_fan_out] +function writeNewPost(uid, username, picture, title, body) { + // A post entry. + var postData = { + author: username, + uid: uid, + body: body, + title: title, + starCount: 0, + authorPic: picture + }; + + // Get a key for a new Post. + var newPostKey = firebase.database().ref().child('posts').push().key; + + // Write the new post's data simultaneously in the posts list and the user's post list. + var updates = {}; + updates['/posts/' + newPostKey] = postData; + updates['/user-posts/' + uid + '/' + newPostKey] = postData; + + return firebase.database().ref().update(updates); +} +// [END rtdb_social_write_fan_out] + +function socialCompletionCallback() { + const userId = "123"; + const email = "test@example.com"; + const imageUrl = "https://example.com/image.png"; + + // [START rtdb_social_completion_callback] + firebase.database().ref('users/' + userId).set({ + username: name, + email: email, + profile_picture : imageUrl + }, (error) => { + if (error) { + // The write failed... + } else { + // Data saved successfully! + } + }); + // [END rtdb_social_completion_callback] +} + +/** + * @param {firebase.database.Reference} postRef + * @param {string} uid + */ +// [START rtdb_social_star_transaction] +function toggleStar(postRef, uid) { + postRef.transaction((post) => { + if (post) { + if (post.stars && post.stars[uid]) { + post.starCount--; + post.stars[uid] = null; + } else { + post.starCount++; + if (!post.stars) { + post.stars = {}; + } + post.stars[uid] = true; + } + } + return post; + }); +} +// [END rtdb_social_star_transaction] + +/** + * @param {string} uid + * @param {string} key + */ +// [START rtdb_social_star_increment] +function addStar(uid, key) { + const updates = {}; + updates[`posts/${key}/stars/${uid}`] = true; + updates[`posts/${key}/starCount`] = firebase.database.ServerValue.increment(1); + updates[`user-posts/${key}/stars/${uid}`] = true; + updates[`user-posts/${key}/starCount`] = firebase.database.ServerValue.increment(1); + firebase.database().ref().update(updates); +} +// [END rtdb_social_star_increment] + +function readOnceWithGet(userId) { + // [START rtdb_read_once_get] + const dbRef = firebase.database().ref(); + dbRef.child("users").child(userId).get().then((snapshot) => { + if (snapshot.exists()) { + console.log(snapshot.val()); + } else { + console.log("No data available"); + } + }).catch((error) => { + console.error(error); + }); + // [END rtdb_read_once_get] +} diff --git a/pool/shard001/JavaScript/0006510_react_jqxtogglebutton.esm.js b/pool/shard001/JavaScript/0006510_react_jqxtogglebutton.esm.js new file mode 100644 index 0000000000000000000000000000000000000000..5541b38a65c1e3df8846262a74d89d9d4ef000fb --- /dev/null +++ b/pool/shard001/JavaScript/0006510_react_jqxtogglebutton.esm.js @@ -0,0 +1,134 @@ +import * as jqxcore from '../../jqwidgets/jqxcore'; +import * as jqxbuttons from '../../jqwidgets/jqxbuttons'; +import { createElement, PureComponent } from 'react'; + +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. 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 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* global Reflect, Promise */ + +var extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); +}; + +function __extends(d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +} + +var JqxToggleButton = /** @class */ (function (_super) { + __extends(JqxToggleButton, _super); + function JqxToggleButton(props) { + var _this = _super.call(this, props) || this; + /* tslint:disable:variable-name */ + _this._jqx = JQXLite; + _this._id = 'JqxToggleButton' + _this._jqx.generateID(); + _this._componentSelector = '#' + _this._id; + _this.state = { lastProps: props }; + return _this; + } + JqxToggleButton.getDerivedStateFromProps = function (props, state) { + if (!Object.is) { + Object.is = function (x, y) { + if (x === y) { + return x !== 0 || 1 / x === 1 / y; + } + else { + return x !== x && y !== y; + } + }; + } + var areEqual = Object.is(props, state.lastProps); + if (!areEqual) { + var newState = { lastProps: props }; + return newState; + } + return null; + }; + JqxToggleButton.prototype.componentDidMount = function () { + var widgetOptions = this._manageProps(); + this._jqx(this._componentSelector).jqxToggleButton(widgetOptions); + this._wireEvents(); + }; + JqxToggleButton.prototype.componentDidUpdate = function () { + var widgetOptions = this._manageProps(); + this.setOptions(widgetOptions); + this._wireEvents(); + }; + JqxToggleButton.prototype.render = function () { + return (createElement("div", { id: this._id, className: this.props.className, style: this.props.style }, this.props.children)); + }; + JqxToggleButton.prototype.setOptions = function (options) { + this._jqx(this._componentSelector).jqxToggleButton(options); + }; + JqxToggleButton.prototype.getOptions = function (option) { + return this._jqx(this._componentSelector).jqxToggleButton(option); + }; + JqxToggleButton.prototype.check = function () { + this._jqx(this._componentSelector).jqxToggleButton('check'); + }; + JqxToggleButton.prototype.destroy = function () { + this._jqx(this._componentSelector).jqxToggleButton('destroy'); + }; + JqxToggleButton.prototype.focus = function () { + this._jqx(this._componentSelector).jqxToggleButton('focus'); + }; + JqxToggleButton.prototype.renderWidget = function () { + this._jqx(this._componentSelector).jqxToggleButton('render'); + }; + JqxToggleButton.prototype.toggle = function () { + this._jqx(this._componentSelector).jqxToggleButton('toggle'); + }; + JqxToggleButton.prototype.unCheck = function () { + this._jqx(this._componentSelector).jqxToggleButton('unCheck'); + }; + JqxToggleButton.prototype.val = function (value) { + if (value) { + this._jqx(this._componentSelector).jqxToggleButton('val', value); + } + else { + return this._jqx(this._componentSelector).jqxToggleButton('val'); + } + }; + JqxToggleButton.prototype._manageProps = function () { + var widgetProps = ['disabled', 'height', 'imgSrc', 'imgWidth', 'imgHeight', 'imgPosition', 'roundedCorners', 'rtl', 'textPosition', 'textImageRelation', 'theme', 'template', 'toggled', 'width', 'value']; + var options = {}; + for (var prop in this.props) { + if (widgetProps.indexOf(prop) !== -1) { + options[prop] = this.props[prop]; + } + } + return options; + }; + JqxToggleButton.prototype._wireEvents = function () { + for (var prop in this.props) { + if (prop.indexOf('on') === 0) { + var originalEventName = prop.slice(2); + originalEventName = originalEventName.charAt(0).toLowerCase() + originalEventName.slice(1); + this._jqx(this._componentSelector).off(originalEventName); + this._jqx(this._componentSelector).on(originalEventName, this.props[prop]); + } + } + }; + return JqxToggleButton; +}(PureComponent)); +var jqx = window.jqx; +var JQXLite = window.JQXLite; + +export default JqxToggleButton; +export { jqx, JQXLite }; diff --git a/pool/shard001/JavaScript/0006511_ee-download.js b/pool/shard001/JavaScript/0006511_ee-download.js new file mode 100644 index 0000000000000000000000000000000000000000..3a4c92c56d2377161c519ed80acb86c19590b840 --- /dev/null +++ b/pool/shard001/JavaScript/0006511_ee-download.js @@ -0,0 +1,262 @@ +'use strict'; +/*jshint browser: true*/ + +/*global require: false*/ +var utils = require('./utils'); + +var months = [ + 'January', + 'February', + 'March', + 'April', + 'May', + 'June', + 'July', + 'August', + 'September', + 'October', + 'November', + 'December' +]; + +var attr = utils.attr; +var query = utils.query; +var mkEl = utils.mkEl; +var keys = utils.keys; +var tmpl = utils.tmpl; + +function mkListItems(target, texts, clickCb, that) { + var items = []; + that = that || {}; + + texts.forEach(function (text, i) { + var el = mkEl('li'); + el.innerHTML = '' + text + ''; + + el.addEventListener('click', function (evt) { + evt.preventDefault(); + items.forEach(function (e) { + var cl = e.classList; + if (e === el) { + if (!cl.contains('active')) { + cl.add('active'); + } + } + else { + cl.remove('active'); + } + }); + + clickCb.call(that, i, el); + }); + + target.appendChild(el); + + items.push(el); + }); + + return items; +} + +function camDownloadsWidget(info, holder) { + var majorList = query('ul.major', holder); + var patchList = query('ul.patch', holder); + var serverList = query('ul.server', holder); + var infoDiv = query('.selected-server', holder); + var standaloneDiv = query('.standalone', infoDiv); + + var releaseTitle = query('.info h3', holder); + var notesA = query('a.notes', holder); + var dateSpan = query('span.date', holder); + var zipA = query('a.zip', holder); + var targzA = query('a.tar-gz', holder); + var warA = query('a.war', holder); + + var runDetails = query('a.details.run', holder); + var fullDetails = query('a.details.full', holder); + + var branches = keys(info.branches).sort(function (a, b) { + var foo = parseInt(a.split(".")[1], 10); + var bar = parseInt(b.split(".")[1], 10); + return (foo > bar ? -1 : (foo < bar ? 1 : 0)); + }); + + + function getReleaseInfo(branch, version) { + return info.branches[branch].find(function (release) { + return release.number === version; + }); + } + + function getBranchVersions(branch) { + return info.branches[branch].map(function (release) { + return release.number; + }).filter(function (item) { return !!item; }); + } + + function getServers(release) { + var servers = keys(info.servers); + if (release.excludeServers) { + servers = servers.filter(function (name) { + return release.excludeServers.indexOf(name) < 0; + }); + } + return servers; + } + + + var dlBasePath = 'https://downloads.camunda.cloud/enterprise-release/camunda-bpm/'; + function mkServerClickHandler(servers, version, branch) { + return function (s) { + var selectedServer = servers[s]; + var release = getReleaseInfo(branch, version); + var excludesWar = release.excludeFormats && release.excludeFormats.indexOf('war') > -1; + infoDiv.classList.add('accessible'); + + runDetails.style.display = 'none'; + fullDetails.style.display = 'inline'; + + var dl = tmpl('{server}/{branch}/{version}/camunda-bpm-ee-{serverAlias}-{version}-ee', { + version: version, + branch: (version.indexOf('alpha') > -1) ? 'nightly' : branch, + server: selectedServer, + serverAlias: (selectedServer === 'wildfly8')? 'wildfly' : selectedServer + }); + + releaseTitle.innerHTML = version + '-ee for ' + info.servers[selectedServer]; + + var parts = release.date.split('.').map(function (part) { + return parseInt(part, 10); + }); + dateSpan.innerHTML = parts[2] + ' ' + months[parts[1] - 1] + ' ' + parts[0]; + + attr(notesA, 'href', release.note); + + attr(warA, 'href', dlBasePath + tmpl('{server}/{branch}/{version}/camunda-webapp-ee-{server}-standalone-{version}-ee', { + version: version, + branch: (version.indexOf('alpha') > -1) ? 'nightly' : branch, + server: selectedServer.match(/wildfly*/) ? 'jboss' : selectedServer + }) + '.war'); + + attr(targzA, 'href', dlBasePath + dl + '.tar.gz'); + + attr(zipA, 'href', dlBasePath + dl + '.zip'); + + if (selectedServer.startsWith('ibm-was') || selectedServer === 'oracle-wls') { + dl = tmpl('{vendor}-{server}/{branch}/{version}/camunda-ee-{vendor}-{server}-{version}-ee', { + version: version, + branch: (version.indexOf('alpha') > -1) ? 'nightly' : branch, + vendor: selectedServer.split('-')[0], + server: selectedServer.split('-')[1] + }); + + attr(targzA, 'href', dlBasePath + dl + '.tar.gz'); + + attr(zipA, 'href', dlBasePath + dl + '.zip'); + + attr(warA, 'href', dlBasePath + tmpl('{vendor}-{server}/{branch}/{version}/camunda-webapp-ee-{server}-standalone-{version}-ee', { + version: version, + branch: (version.indexOf('alpha') > -1) ? 'nightly' : branch, + vendor: selectedServer.split('-')[0], + server: selectedServer.split('-')[1] + }) + '.war'); + } + + if(selectedServer.startsWith('run')) { + + runDetails.style.display = 'inline'; + fullDetails.style.display = 'none'; + + var dl = tmpl('{server}/{branch}/{version}/camunda-bpm-{server}-ee-{version}-ee', { + version: version, + branch: (version.indexOf('alpha') > -1) ? 'nightly' : branch, + server: selectedServer + }); + + + attr(targzA, 'href', dlBasePath + dl + '.tar.gz'); + + attr(zipA, 'href', dlBasePath + dl + '.zip'); + + excludesWar = true; + } + + + if (excludesWar) { + standaloneDiv.style.display = 'none'; + } + else { + standaloneDiv.style.display = 'block'; + } + }; + } + + function mkVersionClickHandler(branchName) { + var patchReleases = getBranchVersions(branchName); + + return function selectVersion(r) { + serverList.innerHTML = ''; + + infoDiv.classList.remove('accessible'); + + var selectedVersion = patchReleases[r]; + + var releaseInfo = getReleaseInfo(branchName, selectedVersion); + + var releaseServers = getServers(releaseInfo); + + return mkListItems(serverList, releaseServers.map(function (name) { + return info.servers[name]; + }), mkServerClickHandler(releaseServers, selectedVersion, branchName)); + }; + } + + + function selectBranch(b) { + patchList.innerHTML = ''; + + serverList.innerHTML = ''; + + infoDiv.classList.remove('accessible'); + + var branchName = branches[b]; + + var patchReleases = getBranchVersions(branchName); + + return mkListItems(patchList, patchReleases, mkVersionClickHandler(branchName)); + } + + + var branchEls = mkListItems(majorList, branches, selectBranch); + + if (info.selected) { + var b = branches.indexOf(info.selected.branch); + + var versionEls = selectBranch(b); + + branchEls[b].classList.add('active'); + + + var patchReleases = getBranchVersions(branches[b]); + + var v = patchReleases.indexOf(info.selected.version); + + var serverEls = mkVersionClickHandler(branches[b])(v); + + versionEls[v].classList.add('active'); + + + var servers = getServers(patchReleases[v]); + + var s = servers.indexOf(info.selected.server); + + serverEls[s].classList.add('active'); + + mkServerClickHandler(servers, info.selected.version, info.selected.branch)(s); + } +} + +var camDownloadsEl = query('.cam-downloads'); +if (window.camDownloads && camDownloadsEl) { + camDownloadsWidget(window.camDownloads, camDownloadsEl); +} diff --git a/pool/shard001/JavaScript/0006514_gulpfile.js b/pool/shard001/JavaScript/0006514_gulpfile.js new file mode 100644 index 0000000000000000000000000000000000000000..a581d19760c28aa82c0d5e1d2d1a39f0db36379b --- /dev/null +++ b/pool/shard001/JavaScript/0006514_gulpfile.js @@ -0,0 +1,85 @@ +var config = require("./config.js"); +var pathManager = require("./server/pathManager.js"); +var gulp = require("gulp"); +var del = require("del"); +var jshint = require("gulp-jshint"); +var shell = require("gulp-shell"); +var preprocess = require("gulp-preprocess"); +var nodemon = require("gulp-nodemon"); +var mocha = require("gulp-mocha"); + +gulp.task("clean", function (cb) { + del([pathManager.APP_BUILD], cb); +}); + +gulp.task("copy", ["clean"], function () { + gulp.src([pathManager.APP_ASSETS + "/**/*.*"]).pipe(gulp.dest(pathManager.APP_BUILD + "/assets")); + gulp.src([pathManager.APP_CSS + "/**/*.*"]).pipe(gulp.dest(pathManager.APP_BUILD + "/css")); + + if (config.env != "production") { + gulp.src([pathManager.APP_LIB + "/**/*.*"]).pipe(gulp.dest(pathManager.APP_BUILD + "/lib")); + gulp.src([pathManager.APP_SCRIPTS + "/**/*.js"]).pipe(gulp.dest(pathManager.APP_BUILD + "/scripts")); + } else { + gulp.src([pathManager.APP_LIB + "/requirejs/require.js"]).pipe(gulp.dest(pathManager.APP_BUILD + "/lib/requirejs")); + } +}); + +gulp.task("scripts", ["clean"], shell.task(config.requirejsCommand + " -o app/scripts/build.js")); + +gulp.task("html", ["clean"], function () { + gulp.src(pathManager.APP + "/index.html") + .pipe(preprocess({ context: { NODE_ENV: config.env } })) + .pipe(gulp.dest(pathManager.APP_BUILD)); +}); + +gulp.task("server", function () { + nodemon({ + script: pathManager.BASE + "/server.js", + watch: [ + pathManager.BASE + "/*.js", + pathManager.SERVER + "/*.js" + ], + ignore: [ + pathManager.APP + "/**/*.*", + pathManager.TEST + "/**/*.js" + ] + }); +}); + +gulp.task("watch", function () { + gulp.watch([ + pathManager.TEST + "/app/**/*.js", + pathManager.APP + "/**/*.*", + "!" + pathManager.APP_BUILD + "/**/*.*" + ], ["copy", "html", "lint", "test"]); + + gulp.watch([ + pathManager.BASE + "/*.js", + pathManager.SERVER + "/*.js", + pathManager.TEST + "/server/**/*.js" + ], ["server", "lint", "test"]); +}); + +gulp.task("lint", function () { + return gulp.src([ + pathManager.BASE + "/*.js", + pathManager.SERVER + "/*.js", + pathManager.APP_SCRIPTS + "/**/*.js", + "!" + pathManager.APP_SCRIPTS + "/build.js", + "!" + pathManager.APP_BUILD + "/main-built.js", + ]) + .pipe(jshint()) + .pipe(jshint.reporter("default")); +}); + +gulp.task("test", function () { + gulp.src(pathManager.TEST + "/**/*.js") + .pipe(mocha()) + .on("error", function(err){ + console.log(err.toString()); + }); +}); + +gulp.task("development", ["watch", "copy", "html", "lint", "server"]); +gulp.task("production", ["copy", "scripts", "html"]); +gulp.task("default", [config.env]); diff --git a/pool/shard001/JavaScript/0006515_objectMap.js b/pool/shard001/JavaScript/0006515_objectMap.js new file mode 100644 index 0000000000000000000000000000000000000000..19bbe7f3da9de00cbf56f1ad1bacc7fa76d8ddfc --- /dev/null +++ b/pool/shard001/JavaScript/0006515_objectMap.js @@ -0,0 +1,159 @@ +var policycompass = policycompass || {'version':0.1, 'controller':{}, 'viz': {} ,'extras': {} }; + +policycompass.viz.map = function(options) +{ + + // Object + + var self = {}; + + // Get options data + + for (key in options){ + self[key] = options[key]; + } + + self.parentSelect = "#"+self.idName; + + + self.init = function(){ + + + + self.width = 1200, + self.height = 700, + self.selectedProperty = "population" + self.baseColors = d3.scale.category20(); + self.svg = d3.select(self.parentSelect) + .append("svg") + .attr("width", self.width) + .attr("height", self.height) + .on("mousemove", mousemove) + .call(d3.behavior.zoom().on("zoom", self.redraw)) + .append("g"); + + self.subunits = topojson.feature(self.es, self.es.objects.subunits), + + self.projection = d3.geo.albers() + .center([0, 40.23]) + .rotate([3.43, 0]) + .parallels([40, 60]) + .scale(4000) + .translate([self.width / 2, self.height / 2]); + + self.path = d3.geo.path() + .projection(self.projection); + + + queue()//.defer(d3.json, "es.json") + .defer(d3.tsv, "ine.tsv") + .await(self.ready); + + } + + self.redraw = function() { + self.svg.attr("transform", "translate(" + d3.event.translate + ")" + + " scale(" + d3.event.scale + ")"); + }; + + self.ready = function(error, ine) { + //console.log("READY"); + var provincesData = {}; + ine.forEach(function (d, i) { + if (i == 0) { self.fillSelector(Object.keys(d)); } + Object.keys(d).forEach(function (k) { + var v = parseFloat(d[k]); + if (!isNaN(v)) { + d[k] = v; + } + }); + provincesData[d.provincia] = d; + }); + } + self.fillSelector = function(keys) { + keys = keys.filter(function (e) { return e !== "provincia"; }) + d3.select("#selector") + .selectAll("option") + .data(keys) + .enter() + .append("option") + .attr("value", function (d) { return d; }) + .text(function (d) { return d; }); + d3.select("#selector").on("change", function () { + var sel = document.getElementById("selector"); + selectedProperty = sel.options[sel.selectedIndex].value; + updateColors(); + }); + }; + self.updateColors = function() { + var tempColor = baseColors(selectedProperty), + tempScale = d3.scale.linear() + .domain([d3.min(ine, function (d) { return d[selectedProperty]; }), + d3.max(ine, function (d) { return d[selectedProperty]; })]) + .range([d3.rgb(tempColor).brighter(3), + d3.rgb(tempColor).darker(3)]) + .clamp(true); + svg.selectAll(".subunit.ESP") + .transition() + .duration(1000) + .style("fill", function (d) { + if ("properties" in d) { + if ("name" in d.properties) { + if (d.properties.name in provincesData) { + if (provincesData[d.properties.name][selectedProperty] !== "-") { + return tempScale(provincesData[d.properties.name][selectedProperty]); + } + } + } + } + return "#ddc"; + }); + }; + + function mouseout() { + tooltip.style("opacity",0.0); + } + + self.render = function(){ + self.svg.selectAll(".subunit") + .data(topojson.feature(self.es, self.es.objects.subunits).features) + .enter() + .append("path") + .attr("class", function (d) { return "subunit " + d.id.slice(0, 3); }) + .on("mouseover", function (d) { + + //console.log(d.properties.name); + //posMouse = d3.mouse(this); + //posX = posMouse[0]; + //posY = posMouse[1]; + + tooltip.style("opacity",1.0).html("key="+d.properties.name); + + }) + .on("mouseout", mouseout) + .on("click",function(d,i){ console.log(d);}) + .attr("d", self.path); + self.svg.append("path") + .datum(topojson.mesh(self.es, self.es.objects.subunits, function (a, b) { return a !== b && a.id.slice(0, 3) === "ESP"; })) + .attr("d", self.path) + .attr("class", "subunit-boundary"); + self.svg.append("path") + .datum(topojson.mesh(self.es, self.es.objects.subunits, function (a, b) { return a === b && a.id.slice(0, 3) !== "ESP"; })) + .attr("d", self.path) + .attr("class", "subunit-boundary OTHER"); + self.svg.selectAll(".subunit-label") + .data(topojson.feature(self.es, self.es.objects.subunits).features) + .enter() + .append("text") + .attr("class", function (d) { return "subunit-label " + d.id.slice(0, 3); }) + .attr("transform", function (d) { return "translate(" + self.path.centroid(d) + ")"; }) + .attr("dy", ".35em") + .text(function (d) { + return d.id.slice(0, 3) === "ESP" ? d.properties.name : ""; + }); + }; + + self.init(); + return self; + +} diff --git a/pool/shard001/JavaScript/0006516_Tileset.js b/pool/shard001/JavaScript/0006516_Tileset.js new file mode 100644 index 0000000000000000000000000000000000000000..7169df22fec559cf9cd64df33f26b771a1f9047e --- /dev/null +++ b/pool/shard001/JavaScript/0006516_Tileset.js @@ -0,0 +1,26 @@ +function Tileset(url, taille) { + this.taille = taille; + // Chargement de l'image dans l'attribut image + this.image = new Image(); + this.image.referenceDuTileset = this; + this.image.onload = function() { + if(!this.complete) + throw new Error("Erreur de chargement du tileset nommé \"" + url + "\"."); + + // Largeur du tileset en tiles + this.referenceDuTileset.largeur = this.width / taille; + } + this.image.src = "tilesets/" + url + ".png"; +} + +// Méthode de dessin du tile numéro "numero" dans le contexte 2D "context" aux coordonnées x et y +Tileset.prototype.dessinerTile = function(numero, context, xDestination, yDestination) { + var xSourceEnTiles = numero % this.largeur; + if(xSourceEnTiles == 0) xSourceEnTiles = this.largeur; + var ySourceEnTiles = Math.ceil(numero / this.largeur); + + var xSource = (xSourceEnTiles - 1) * this.taille; + var ySource = (ySourceEnTiles - 1) * this.taille; + + context.drawImage(this.image, xSource, ySource, this.taille, this.taille, xDestination, yDestination, this.taille, this.taille); +} diff --git a/pool/shard001/JavaScript/0006517_common.js b/pool/shard001/JavaScript/0006517_common.js new file mode 100644 index 0000000000000000000000000000000000000000..8552f08f7d09e411bc2cdc582621f879f20fb16a --- /dev/null +++ b/pool/shard001/JavaScript/0006517_common.js @@ -0,0 +1,45 @@ +ls.comments = ls.comments || {}; + +if (ls.comments) { + ls.comments.options.type.image = { + url_add: aRouter.gallery + 'ajaxaddcomment/', + url_response: aRouter.gallery + 'ajaxresponsecomment/' + }; +} + +ls.favourite = ls.favourite || {}; + +if (ls.favourite) { + ls.favourite.options.type.image = { + url: aRouter.galleryajax + 'favourite/', + targetName: 'idImage' + }; +} + +ls.vote = ls.vote || {}; + +if (ls.vote) { + ls.vote.options.type.image = { + url: aRouter.galleryajax + 'vote/', + targetName: 'idImage' + }; +} + +ls.blocks = ls.blocks || {}; + +if (ls.blocks) { + ls.blocks.options.type.block_gallery_new_images = { + url: aRouter.galleryajax + 'getnewimages/' + }; + ls.blocks.options.type.block_gallery_best_images = { + url: aRouter.galleryajax + 'getbestimages/' + }; + ls.blocks.options.type.block_gallery_images_comments = { + url: aRouter.galleryajax + 'getimagescomments/' + }; +} + +jQuery('document').ready(function(){ + ls.blocks.init('block_gallery', {group_items: true}); +}); + diff --git a/pool/shard001/JavaScript/0006518_region.js b/pool/shard001/JavaScript/0006518_region.js new file mode 100644 index 0000000000000000000000000000000000000000..a33d86c3971bb3df4f4604cdfa54a7fe7febdb13 --- /dev/null +++ b/pool/shard001/JavaScript/0006518_region.js @@ -0,0 +1,23 @@ +/* jshint indent: 2 */ + +module.exports = function(sequelize, DataTypes) { + var Region = sequelize.define('Region', { + ref : { type: DataTypes.STRING(5), unique: true, validate: { isNull: false } }, + code : { type: DataTypes.STRING(2), allowNull: false, unique: true }, + countryCode : { type: DataTypes.STRING(2), allowNull: false }, + name : { type: DataTypes.STRING, allowNull: false }, + + createdBy : { type: DataTypes.STRING, defaultValue: 'unknown' }, + updatedBy : { type: DataTypes.STRING, defaultValue: 'unknown' } + }, { + classMethods: { } + }); + + // TODO: Associations commented out because not working... + // Region.belongsTo(Country, { foreignKey: 'countryCode'}); + // Region.hasMany(City, { foreignKey: 'regionRef'}); + + return Region; +}; + + diff --git a/pool/shard001/JavaScript/0006519_userform.js b/pool/shard001/JavaScript/0006519_userform.js new file mode 100644 index 0000000000000000000000000000000000000000..166d46c5a3c54de892fb2c7b95ba018f8357dedf --- /dev/null +++ b/pool/shard001/JavaScript/0006519_userform.js @@ -0,0 +1,193 @@ +import React from 'react'; +import pluralize from 'pluralize'; +import { + Button, + Checkbox, + Dialog, + DialogActions, + DialogContent, + DialogTitle, + FormControl, + FormHelperText, + ListItemText, + InputLabel, + MenuItem, + Select +} from '@material-ui/core'; + +import Form from '../common/forms/form'; +import TextInput from '../common/forms/textinput'; +import PasswordInput from '../common/forms/passwordinput'; +import { rolesByName } from '../../constants/userConstants'; +import { colors } from '../../themes/mender-theme'; +import { deepCompare } from '../../helpers'; + +import { OAuth2Providers } from './oauth2providers'; + +export default class UserForm extends React.Component { + constructor(props, context) { + super(props, context); + const isCreation = !Object.keys(props.user).length; + this.state = { + editPass: isCreation, + hadRoleChanges: false, + isCreation, + selectedRoles: (props.user.roles || []).reduce((accu, role) => { + const foundRole = props.roles.find(currentRole => currentRole.id === role); + if (foundRole) { + accu.push(foundRole); + } + return accu; + }, []) + }; + } + + componentDidUpdate(prevProps, prevState) { + // TODO: this is needed due to the re-registering of inputs in the form component and should be fixed at some point + if (prevState.editPass !== this.state.editPass || prevState.selectedRoles !== this.state.selectedRoles) { + this.forceUpdate(); + } + } + + onSelect(role) { + const { selectedRoles } = this.state; + const { + user: { roles = [] } + } = this.props; + const isSelectedAlready = selectedRoles.some(currentRole => role.id === currentRole.id); + let newlySelectedRoles; + if (isSelectedAlready) { + newlySelectedRoles = selectedRoles.filter(currentRole => role.id !== currentRole.id); + } else { + newlySelectedRoles = [...selectedRoles, role]; + } + const hadRoleChanges = + roles.length !== newlySelectedRoles.length || roles.some(currentRoleId => !newlySelectedRoles.some(role => currentRoleId === role.id)); + this.setState({ selectedRoles: newlySelectedRoles, hadRoleChanges }); + } + + onSubmit(data) { + const { submit, user } = this.props; + const { hadRoleChanges, isCreation, selectedRoles } = this.state; + let submissionData = Object.assign({}, data, hadRoleChanges ? { roles: selectedRoles.map(role => role.id) } : {}); + delete submissionData['password_new']; + submissionData['password'] = data.password_new; + submissionData = Object.entries(submissionData).reduce((accu, [key, value]) => { + if (!deepCompare(user[key], value)) { + accu[key] = value; + } + return accu; + }, {}); + return !isCreation ? submit(submissionData, 'edit', user.id) : submit(submissionData, 'create'); + } + + render() { + const self = this; + const { editPass, isCreation, selectedRoles } = self.state; + const { closeDialog, currentUser, isAdmin, isEnterprise, roles, user } = self.props; + const showRoleUsageNotification = selectedRoles.reduce((accu, item) => { + const hasUiApiAccess = [rolesByName.ci].includes(item.id) + ? false + : item.id === rolesByName.admin || item.permissions.some(permission => ![rolesByName.deploymentCreation.action].includes(permission.action)); + if (hasUiApiAccess) { + return false; + } + return typeof accu !== 'undefined' ? accu : true; + }, undefined); + const isOAuth2 = !!user.login; + const provider = isOAuth2 ? OAuth2Providers.find(provider => !!user.login[provider.id]) : null; + return ( + + {isCreation ? 'Create new user' : 'Edit user'} + +
      self.onSubmit(data)} + handleCancel={closeDialog} + submitLabel={isCreation ? 'Create user' : 'Save changes'} + submitButtonId="submit_button" + showButtons={true} + autocomplete="off" + > + + {isOAuth2 ? ( +
      +
      {provider.icon}
      +
      + This user logs in using his {provider.name} account. +
      + He can connect to {provider.name} to update his login settings. +
      +
      + ) : editPass ? ( + self.setState({ editPass: !editPass })} + edit={isCreation ? false : true} + required={isCreation} + autocomplete="off" + /> + ) : ( + + )} + {isEnterprise && isAdmin ? ( +
      + + Roles + + {showRoleUsageNotification && ( + + The selected {pluralize('role', selectedRoles.length)} may prevent {currentUser.email === user.email ? 'you' : {user.email}} from + using the Mender UI. +
      + Consider adding the Read only role as well. +
      + )} +
      +
      + ) : ( + <> + )} + +
      + +
      + ); + } +} diff --git a/pool/shard001/JavaScript/0006522_musicArpeggiate.js b/pool/shard001/JavaScript/0006522_musicArpeggiate.js new file mode 100644 index 0000000000000000000000000000000000000000..342b53a80e5b738381307c96b731277e0847751b --- /dev/null +++ b/pool/shard001/JavaScript/0006522_musicArpeggiate.js @@ -0,0 +1,41 @@ +'use strict'; + +(function (scope) { + /** + * Music arpeggiate + * + * @class MusicArpeggiate + * @extends MusicElement + * @param {Object} [obj] + * @constructor + */ + function MusicArpeggiate(obj) { + scope.MusicElement.call(this, obj); + if (obj) { + this.type = obj.type; + } + } + + /** + * Inheritance property + */ + MusicArpeggiate.prototype = new scope.MusicElement(); + + /** + * Constructor property + */ + MusicArpeggiate.prototype.constructor = MusicArpeggiate; + + /** + * Get type + * + * @method getType + * @returns {String} + */ + MusicArpeggiate.prototype.getType = function () { + return this.type; + }; + + // Export + scope.MusicArpeggiate = MusicArpeggiate; +})(MyScript); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006524_base.js b/pool/shard001/JavaScript/0006524_base.js new file mode 100644 index 0000000000000000000000000000000000000000..4475d1567b96ca014dfcce92414ea2da02f2049b --- /dev/null +++ b/pool/shard001/JavaScript/0006524_base.js @@ -0,0 +1,106 @@ +/** + * Base model that contain the common methods. + * + */ +$BaseModelFactory.$inject = ['$http', '$q']; +function $BaseModelFactory($http, $q) { + // The base model. + var BaseModel = function (data, options) { + this.options = options || {}; + + this.initialize.apply(this, arguments); + }; + + BaseModel.prototype.initialize = function () { + if (this.options.baseUrl) { + this.baseUrl = this.options.baseUrl; + } else if (this.options.url) { + this.url = this.options.url; + } + }; + + BaseModel.prototype.computeUrl = function(path, parameters) { + if (parameters !== undefined && typeof parameters == 'object') { + for (var key in parameters) { + path = path.replace('{'+key+'}', parameters[key]); + } + } + + return path; + }; + + BaseModel.prototype.parse = function (httpResponse, options) { + return httpResponse.data; + }; + BaseModel.prototype.getOption = function (key) { + return this.options[key]; + }; + BaseModel.prototype.setOption = function (key, value) { + this.options[key] = value; + }; + + BaseModel.prototype.prepare = function (object) { + return object; + }; + BaseModel.prototype.fetch = function (options) { + return this.sync('GET', undefined, options); + }; + BaseModel.prototype.save = function (options) { + return this.sync('POST', this.prepare(this.attributes), options); + }; + BaseModel.prototype.destroy = function (options) { + return this.sync('DELETE', undefined, options); + }; + BaseModel.prototype._resolve = function (field) { + return resolveValue(this, field); + }; + + BaseModel.prototype.sync = function (method, data, options) { + options = angular.extend({ + method: method, + url: this._resolve('url'), + data: data + }, options); + + if (options.method == 'GET' && options.data !== undefined) { + options.url += options.url.indexOf('?') == -1 ? '?' : '&'; + options.url += $.param(options.data); + } + + var abortDeferred; + if (options.timeout === undefined) { + abortDeferred = $q.defer(); + options.timeout = abortDeferred.promise; + } + + var self = this, + promise = $http(options).then(function (httpResponse) { + var model = self.parse(httpResponse, options); + self.set(model); + + return self; + }); + + if (abortDeferred !== undefined) { + promise.abort = function () { + if (abortDeferred) { + promise.aborted = true; + abortDeferred.resolve(); + } + }; + + promise['finally'](function () { + abortDeferred = null; + }); + } + + return promise; + }; + + BaseModel.extend = modelExtend; + + return BaseModel; +} + +angular.module('angular-simple-model') + .factory('BaseModel', $BaseModelFactory); diff --git a/pool/shard001/JavaScript/0006525_app.js b/pool/shard001/JavaScript/0006525_app.js new file mode 100644 index 0000000000000000000000000000000000000000..277d58a0a1697dc6df0d8968fd4828694c887469 --- /dev/null +++ b/pool/shard001/JavaScript/0006525_app.js @@ -0,0 +1,63 @@ +/* + * 2014 Hack 4 Austin Project @TechRanch Austin + * A basic flash card app with reading materials for children + * + * Project idea was inspired by APIE (Austin Partners in Education) + * + * Developed by Jae Lee + * @leejaew + * http://jael.ee + * + */ + +//bootstrap and check dependencies +if (Ti.version < 1.8) { + alert('Sorry - this application template requires Titanium Mobile SDK 1.8 or later'); +} + +// This is a single context application with multiple windows in a stack +(function() { + //render appropriate components based on the platform and form factor + var osname = Ti.Platform.osname, + version = Ti.Platform.version, + height = Ti.Platform.displayCaps.platformHeight, + width = Ti.Platform.displayCaps.platformWidth; + + //considering tablets to have width over 720px and height over 600px - you can define your own + function checkTablet() { + var platform = Ti.Platform.osname; + + switch (platform) { + case 'ipad': + return true; + case 'android': + var psc = Ti.Platform.Android.physicalSizeCategory; + var tiAndroid = Ti.Platform.Android; + return psc === tiAndroid.PHYSICAL_SIZE_CATEGORY_LARGE || psc === tiAndroid.PHYSICAL_SIZE_CATEGORY_XLARGE; + default: + return Math.min( + Ti.Platform.displayCaps.platformHeight, + Ti.Platform.displayCaps.platformWidth + ) >= 400; + } + } + + var isTablet = checkTablet(); + console.log(isTablet); + + var Window; + + if (isTablet) { + Window = require('ui/tablet/ApplicationWindow'); + } else { + // Android uses platform-specific properties to create windows. + // All other platforms follow a similar UI pattern. + if (osname === 'android') { + Window = require('ui/handheld/android/ApplicationWindow'); + } else { + Window = require('ui/handheld/ApplicationWindow'); + } + } + + new Window().open(); +})(); diff --git a/pool/shard001/JavaScript/0006526_log.js b/pool/shard001/JavaScript/0006526_log.js new file mode 100644 index 0000000000000000000000000000000000000000..394b356c232d97eaa1ebf2a2848225a36216e544 --- /dev/null +++ b/pool/shard001/JavaScript/0006526_log.js @@ -0,0 +1,63 @@ +'use strict'; +var _ = require('underscore'); + +var chalk = require('./chalk'); +var sprintf = require('./sprintf'); + +const log = { + output: _.bind(console.log, console), + level: null, + levels: new Map([ + ['TRACE', {value: 0, color: 'gray'}], + ['DEBUG', {value: 1, color: 'gray'}], + ['INFO', {value: 2, color: ''}], + ['WARN', {value: 3, color: 'yellow'}], + ['ERROR', {value: 4, color: 'red'}] + ]) +}; + +log.setLevel = function(name) { + this.level = this.levels.get(name) || this.levels.get('INFO'); +}; + +log.isEnabled = function(name) { + return this.level.value <= this.levels.get(name).value; +}; + +log.fail = function(e) { + let msg = sprintf('%s', (e.msg || e)); + if (e.statusCode) { + msg += sprintf(' [code=%s]', e.statusCode); + } + log.error(msg); +}; + +log.fatal = function(e) { + log.error(e); + process.exit(1); +}; + +log.printf = function() { + log.info(sprintf.apply(null, Array.from(arguments))); +}; + +log.init = function() { + this.setLevel('INFO'); + + for (let name of this.levels.keys()) { + log[name.toLowerCase()] = function() { + const level = log.levels.get(name); + if (log.level.value > level.value) return; + + const args = Array.from(arguments); + if (name !== 'INFO') args.unshift('[' + name + ']'); + + let s = args.map(x => x.toString()).join(' '); + if (level.color) s = chalk[level.color](s); + + this.output(s); + }; + } +}; + +module.exports = log; diff --git a/pool/shard001/JavaScript/0006529_fractions-data.js b/pool/shard001/JavaScript/0006529_fractions-data.js new file mode 100644 index 0000000000000000000000000000000000000000..f5d254fa7288736096fc97bc79542efbc56eb03e --- /dev/null +++ b/pool/shard001/JavaScript/0006529_fractions-data.js @@ -0,0 +1,113 @@ +/* globals Promise */ + +'use strict'; + +module.exports = function (Fraction) { + function createFraction(fraction) { + return new Promise((resolve, reject) => { + const newFraction = Fraction.getFraction(fraction); + + newFraction.save((err) => { + if (err) { + return reject(err); + } + + return resolve(newFraction); + }); + }); + } + + function findByName(name) { + return new Promise((resolve, reject) => { + Fraction.findOne({ + name + }, (err, fraction) => { + if (err) { + return reject(err); + } + + return resolve(fraction); + }); + }); + } + + function findById(id) { + return new Promise((resolve, reject) => { + Fraction.findOne({ + _id: id + }, (err, fraction) => { + if (err) { + return reject(err); + } + + return resolve(fraction); + }); + }); + } + + function allWithPagination(page = 0, size = 5) { + const promiseData = new Promise((resolve, reject) => { + Fraction + .find() + .skip(page * size) + .limit(size) + .exec((err, fractions) => { + if (err) { + return reject(err); + } + + return resolve(fractions); + }); + }); + + const promisePageCount = new Promise((resolve, reject) => { + Fraction.count((err, count) => { + if (err) { + return reject(err); + } + + const pageCount = Math.ceil(count / size); + return resolve(pageCount); + }); + }); + + return Promise.all([ + promiseData, + promisePageCount + ]); + } + + function updateFractionPlanets(fraction) { + return new Promise((resolve, reject) => { + fraction.save((err) => { + if (err) { + return reject(err); + } + + return resolve(fraction); + }); + + // Fraction.update({ + // _id: fraction._id + // }, { + // $set: { + // planets: fraction.planets + // } + // }, (err, updatedFraction) => { + // if (err) { + // return reject(err); + // } + + // return resolve(updatedFraction); + // }); + }); + } + + return { + createFraction, + findByName, + findById, + allWithPagination, + updateFractionPlanets + }; +}; \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006532_getPartials.js b/pool/shard001/JavaScript/0006532_getPartials.js new file mode 100644 index 0000000000000000000000000000000000000000..520e21a92d2aa9d71e3d61c837ab7e315cd49ca5 --- /dev/null +++ b/pool/shard001/JavaScript/0006532_getPartials.js @@ -0,0 +1,14 @@ +var _ = require('lodash'); + +var _getPartials = function(){ + var self = this; + return { + content: '
      ' + _.map(self.pages, function (Page, page_name) { + return '{{#route.name=="' + page_name + '"}}' + + '
      ' + + '{{/}}'; + }).join('') + '
      ' + } +}; + +module.exports = _getPartials; \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006535_users.server.routes.js b/pool/shard001/JavaScript/0006535_users.server.routes.js new file mode 100644 index 0000000000000000000000000000000000000000..a9f199044f685144246cd5424ddd22304ef302fc --- /dev/null +++ b/pool/shard001/JavaScript/0006535_users.server.routes.js @@ -0,0 +1,65 @@ +'use strict'; + +/** + * Module dependencies. + */ +var passport = require('passport'); + +module.exports = function(app) { + // User Routes + var users = require('../../app/controllers/users.server.controller'); + + // Setting up the users profile api + app.route('/users/me').get(users.me); + app.route('/users') + .put(users.update) + .get(users.list); + app.route('/users/:userId') + .get(users.read); + app.route('/users/accounts').delete(users.removeOAuthProvider); + + // Setting up the users password api + app.route('/users/password').post(users.changePassword); + app.route('/auth/forgot').post(users.forgot); + app.route('/auth/reset/:token').get(users.validateResetToken); + app.route('/auth/reset/:token').post(users.reset); + + // Setting up the users authentication api + app.route('/auth/signup').post(users.signup); + app.route('/auth/signin').post(users.signin); + app.route('/auth/signout').get(users.signout); + + // Setting the facebook oauth routes + app.route('/auth/facebook').get(passport.authenticate('facebook', { + scope: ['email'] + })); + app.route('/auth/facebook/callback').get(users.oauthCallback('facebook')); + + // Setting the twitter oauth routes + app.route('/auth/twitter').get(passport.authenticate('twitter')); + app.route('/auth/twitter/callback').get(users.oauthCallback('twitter')); + + // Setting the google oauth routes + app.route('/auth/google').get(passport.authenticate('google', { + scope: [ + 'https://www.googleapis.com/auth/userinfo.profile', + 'https://www.googleapis.com/auth/userinfo.email' + ] + })); + app.get('/auth/google/callback', passport.authenticate('google', { + + })); + app.route('/auth/google/callback').get(users.oauthCallback('google' + )); + + // Setting the linkedin oauth routes + app.route('/auth/linkedin').get(passport.authenticate('linkedin')); + app.route('/auth/linkedin/callback').get(users.oauthCallback('linkedin')); + + // Setting the github oauth routes + app.route('/auth/github').get(passport.authenticate('github')); + app.route('/auth/github/callback').get(users.oauthCallback('github')); + + // Finish by binding the user middleware + app.param('userId', users.userByID); +}; \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006537_array2d.js b/pool/shard001/JavaScript/0006537_array2d.js new file mode 100644 index 0000000000000000000000000000000000000000..5728c0745cf0064c1534732128496b83247c3636 --- /dev/null +++ b/pool/shard001/JavaScript/0006537_array2d.js @@ -0,0 +1,67 @@ +const { assert, skip, test, module: describe, only } = require('qunit'); +const { GPU } = require('../../../../../../src'); + +describe('feature: to-string unsigned precision constants Array2D'); + +function testConstant(mode, context, canvas) { + const gpu = new GPU({ mode }); + const a = [ + [1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12], + [13, 14, 15, 16], + ]; + const originalKernel = gpu.createKernel(function() { + let sum = 0; + for (let y = 0; y < 4; y++) { + sum += this.constants.a[y][this.thread.x]; + } + return sum; + }, { + canvas, + context, + output: [4], + precision: 'unsigned', + constants: { + a + } + }); + const expected = new Float32Array([28,32,36,40]); + const originalResult = originalKernel(); + assert.deepEqual(originalResult, expected); + const kernelString = originalKernel.toString(); + const Kernel = new Function('return ' + kernelString)(); + const newResult = Kernel({ context, constants: { a } })(); + assert.deepEqual(newResult, expected); + + const b = [ + [1, 1, 1, 1], + [1, 1, 1, 1], + [1, 1, 1, 1], + [1, 1, 1, 1], + ]; + const expected2 = new Float32Array([4,4,4,4]); + const newResult2 = Kernel({ context, constants: { a: b } })(); + assert.deepEqual(newResult2, expected2); + gpu.destroy(); +} + +(GPU.isWebGLSupported ? test : skip)('webgl', () => { + const canvas = document.createElement('canvas'); + const context = canvas.getContext('webgl'); + testConstant('webgl', context, canvas); +}); + +(GPU.isWebGL2Supported ? test : skip)('webgl2', () => { + const canvas = document.createElement('canvas'); + const context = canvas.getContext('webgl2'); + testConstant('webgl2', context, canvas); +}); + +(GPU.isHeadlessGLSupported ? test : skip)('headlessgl', () => { + testConstant('headlessgl', require('gl')(1, 1), null); +}); + +test('cpu', () => { + testConstant('cpu'); +}); diff --git a/pool/shard001/JavaScript/0006542_arm.availset-parameter-create-tests.js b/pool/shard001/JavaScript/0006542_arm.availset-parameter-create-tests.js new file mode 100644 index 0000000000000000000000000000000000000000..ecc93e7c0758f097ad4cdb88d1567a69dd2fe0f4 --- /dev/null +++ b/pool/shard001/JavaScript/0006542_arm.availset-parameter-create-tests.js @@ -0,0 +1,125 @@ +/** + * Copyright (c) Microsoft. 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. + */ +'use strict'; + +var should = require('should'); +var path = require('path'); +var fs = require('fs'); +var util = require('util'); +var profile = require('../../../../lib/util/profile'); +var testUtils = require('../../../util/util'); +var CLITest = require('../../../framework/arm-cli-test'); +var testprefix = 'arm-cli-avail-parameter-create-tests'; +var groupPrefix = 'xplatTstAvsGCreate'; +var VMTestUtil = require('../../../util/vmTestUtil'); +var requiredEnvironment = [{ + name: 'AZURE_VM_TEST_LOCATION', + defaultValue: 'southeastasia' +}]; + +var groupName, + avsPrefix5 = 'xplattestavs5', + location, + paramFileName = 'test/data/availParam1.json'; + +var makeCommandStr = function(component, verb, file, others) { + var cmdFormat = 'availset config %s %s --parameter-file %s %s --json'; + return util.format(cmdFormat, component, verb, file, others ? others : ''); +}; + +describe('arm', function() { + describe('compute', function() { + var suite, retry = 5; + var vmTest = new VMTestUtil(); + before(function(done) { + suite = new CLITest(this, testprefix, requiredEnvironment); + suite.setupSuite(function() { + location = process.env.AZURE_VM_TEST_LOCATION; + groupName = suite.generateId(groupPrefix, null); + avsPrefix5 = suite.isMocked ? avsPrefix5 : suite.generateId(avsPrefix5, null); + done(); + }); + }); + + after(function(done) { + this.timeout(vmTest.timeoutLarge * 10); + vmTest.deleteUsedGroup(groupName, suite, function(result) { + suite.teardownSuite(done); + }); + }); + + beforeEach(function(done) { + suite.setupTest(done); + }); + + afterEach(function(done) { + suite.teardownTest(done); + }); + + describe('availset', function() { + + it('required resources (group) create should pass', function(done) { + this.timeout(vmTest.timeoutLarge * 10); + vmTest.checkImagefile(function() { + vmTest.createGroup(groupName, location, suite, function(result) { + done(); + }); + }); + }); + + it('create-or-update-parameter generate set and remove should pass', function(done) { + this.timeout(vmTest.timeoutLarge * 10); + vmTest.getVMSize(location, suite, function() { + var cmd = util.format('availset config create --parameter-file %s', paramFileName).split(' '); + testUtils.executeCommand(suite, retry, cmd, function(result) { + result.exitStatus.should.equal(0); + var cmd = makeCommandStr('availability-set', 'delete', paramFileName, '--statuses --tags --type --name --id --virtual-machines --sku').split(' '); + testUtils.executeCommand(suite, retry, cmd, function(result) { + result.exitStatus.should.equal(0); + var cmd = makeCommandStr('availability-set', 'set', paramFileName, '--parse --platform-update-domain-count 3 --platform-fault-domain-count 2').split(' '); + testUtils.executeCommand(suite, retry, cmd, function(result) { + result.exitStatus.should.equal(0); + var cmd = makeCommandStr('sku', 'set', paramFileName, util.format('--name %s', 'Aligned')).split(' '); + testUtils.executeCommand(suite, retry, cmd, function(result) { + result.exitStatus.should.equal(0); + var cmd = makeCommandStr('availability-set', 'set', paramFileName, util.format('--name %s --location %s', avsPrefix5, location)).split(' '); + testUtils.executeCommand(suite, retry, cmd, function(result) { + result.exitStatus.should.equal(0); + var cmd = util.format('availset create-or-update -g %s -n %s --parameter-file %s', groupName, avsPrefix5, paramFileName).split(' '); + testUtils.executeCommand(suite, retry, cmd, function(result) { + result.exitStatus.should.equal(0); + result.text.should.containEql('Aligned'); + done(); + }); + }); + }); + }); + }); + }); + }); + }); + + it('delete command should pass', function(done) { + this.timeout(vmTest.timeoutLarge * 20); + var cmd = util.format('availset delete --resource-group %s --name %s -q --json', groupName, avsPrefix5).split(' '); + testUtils.executeCommand(suite, retry, cmd, function(result) { + result.exitStatus.should.equal(0); + done(); + }); + }); + + }); + }); +}); diff --git a/pool/shard001/JavaScript/0006548_script.js b/pool/shard001/JavaScript/0006548_script.js new file mode 100644 index 0000000000000000000000000000000000000000..e6f2407d94bcd22914b36a94ab7d10771be54e4b --- /dev/null +++ b/pool/shard001/JavaScript/0006548_script.js @@ -0,0 +1,60 @@ +'use strict' + +goog.require('Blockly.Firebird.script'); + +goog.provide('Blockly.Firebird'); + +function saveTextAsFile() +{ + +// grab the content of the form field and place it into a variable + var textToWrite = Blockly.Firebird.workspaceToCode(Code.workspace); +// textToWrite.replace(/\n/gi,";\r\n"); + //alert(textToWrite); +// create a new Blob (html5 magic) that conatins the data from your form feild + var textFileAsBlob = new Blob([textToWrite], {type:'text/file'}); +// Specify the name of the file to be saved + var fileNameToSaveAs = "myNewFile.c"; + +// Optionally allow the user to choose a file name by providing +// an imput field in the HTML and using the collected data here +// var fileNameToSaveAs = txtFileName.text; + +// create a link for our script to 'click' + var downloadLink = document.createElement("a"); +// supply the name of the file (from the var above). +// you could create the name here but using a var +// allows more flexability later. + downloadLink.download = fileNameToSaveAs; +// provide text for the link. This will be hidden so you +// can actually use anything you want. + downloadLink.innerHTML = "My Hidden Link"; + +// allow our code to work in webkit & Gecko based browsers +// without the need for a if / else block. + window.URL = window.URL || window.webkitURL; + +// Create the link Object. + downloadLink.href = window.URL.createObjectURL(textFileAsBlob); +// when link is clicked call a function to remove it from +// the DOM in case user wants to save a second file. + downloadLink.onclick = destroyClickedElement; +// make sure the link is hidden. + downloadLink.style.display = "none"; +// add the link to the DOM + document.body.appendChild(downloadLink); + +// click the new link + downloadLink.click(); + + +// alert('The script is working'); +} + +function destroyClickedElement(event) +{ +// remove the link from the DOM + document.body.removeChild(event.target); +} + +// EOF \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006549_parse-if_Parser.js b/pool/shard001/JavaScript/0006549_parse-if_Parser.js new file mode 100644 index 0000000000000000000000000000000000000000..31203bbece3026d488bdc3ea1423bce16cf45cf0 --- /dev/null +++ b/pool/shard001/JavaScript/0006549_parse-if_Parser.js @@ -0,0 +1,34 @@ +this.parseIf = function(idMode) { + this.ensureStmt(idMode); // for now, it is not allowed to be an expression + this.next(); // id:if + + // node-first approach, for the future tolerant mode + var n = { + type: 'IfStatement', + test: null, + consequent: null, + alternate: null + }; + + this.no(NL); + n.test = this.parseExpr(EXPR_NONE); + this.verifyIfTest(n.test); + + n.consequent = this.parseDependentBlock(idMode); + + if (this.peekID('else')) + n.alternate = this.parseElse(idMode); + + return n; +}; + +this.parseElse = function(idMode) { + this.next(); + + if (this.peekID('if')) { + this.no(NL); + return this.parseIf(idMode) + } + + return this.parseDependentBlock(idMode); +}; diff --git a/pool/shard001/JavaScript/0006550_1-Button.stories.js b/pool/shard001/JavaScript/0006550_1-Button.stories.js new file mode 100644 index 0000000000000000000000000000000000000000..2ef7256d437484976218616bb7d3fcdaed5f1e00 --- /dev/null +++ b/pool/shard001/JavaScript/0006550_1-Button.stories.js @@ -0,0 +1,40 @@ +import React from 'react'; + +import { action } from '@storybook/addon-actions'; + +import { foundationPartial } from '../src/styles/foundation'; +import fonts from 'EBI-Icon-fonts/fonts.css'; +const f = foundationPartial(fonts); + +export default { + title: 'Basic UI/Button', +}; + +export const Basic = () => ( + +); +export const Secondary = () => ( + +); +export const JustIcon = () => ( + +); diff --git a/pool/shard001/JavaScript/0006552_index.js b/pool/shard001/JavaScript/0006552_index.js new file mode 100644 index 0000000000000000000000000000000000000000..581b1254c3f5d41739d014098c958c37f103a3e9 --- /dev/null +++ b/pool/shard001/JavaScript/0006552_index.js @@ -0,0 +1,59 @@ +'use strict'; + +var crypto = require('crypto'); +var file = require('file'); +var fs = require('fs'); +var path = require('path'); + +exports.map = function (directories, options) { + + if (directories.length === 0) { + directories.push('.'); + } + if (!options) { + options = {}; + } + + var cwd = process.cwd(); + var algorithm = options.hashAlgorithm ? options.hashAlgorithm : 'sha1'; + var map = { + files: [] + }; + + if (options.cwd) { + process.chdir(options.cwd); + } + + directories.forEach(function (directory) { + + file.walkSync(directory, function (directory) { + + var files = fs.readdirSync(directory); + + files.forEach(function (file) { + var filepath = [directory, file].join('/'); + var filestat = fs.statSync([directory, file].join('/')); + + if (filestat.isFile(filepath)) { + map.files.push({ + name: file, + type: path.extname(filepath), + directory: directory, + filepath: filepath, + size: filestat.size, + blocks: filestat.blocks, + hash: crypto.createHash(algorithm).update(fs.readFileSync(filepath)).digest('hex') + }); + } + }); + }); + }); + + map.hash = crypto.createHash(algorithm).update(JSON.stringify(map.files)).digest('hex'); + + if (options.cwd) { + process.chdir(cwd); + } + + return map; +}; diff --git a/pool/shard001/JavaScript/0006558_kbaseWSReferenceList.js b/pool/shard001/JavaScript/0006558_kbaseWSReferenceList.js new file mode 100644 index 0000000000000000000000000000000000000000..21a31e866a2cb2323e165878c2d1ae7844234c97 --- /dev/null +++ b/pool/shard001/JavaScript/0006558_kbaseWSReferenceList.js @@ -0,0 +1,153 @@ +(function( $, undefined ) { + $.KBWidget({ + name: "KBaseWSReferenceList", + parent: "kbaseAuthenticatedWidget", + version: "1.0.0", + + //wsUrl: "http://dev04.berkeley.kbase.us:7058", + wsUrl:"https://kbase.us/services/ws", + + options: { + wsNameOrId: null, + objNameOrId: null, + objVer: null, + kbCache:{}, + width:900 + }, + + + objName:"", + wsName:"", + + init: function(options) { + this._super(options); + var self = this; + + if (options.wsUrl) { + self.wsUrl = options.wsUrl; + } + var kbws; + if (self.options.kbCache.ws_url) { + self.wsUrl = self.options.kbCache.ws_url; + } + if (self.options.kbCache.token) { + kbws = new Workspace(self.wsUrl, {token: self.options.kbCache.token}); + } else { + kbws = new Workspace(self.wsUrl); + } + + self.objName = options.objNameOrId; + self.wsName = options.wsNameOrId; + + self.$elem.append('



      finding all data that references this object...

      '); + self.$elem.append($('
      ').css("overflow","auto")); + //self.$elem.append(JSON.stringify(options)+"
      "); + + // get the refs + var objectIdentity = self.getObjectIdentity(options.wsNameOrId, options.objNameOrId, options.objVer); + + var request1 = kbws.list_referencing_objects([objectIdentity]); + var request2 = $.getJSON('landing_page_map.json'); + + //kbws.list_referencing_objects([objectIdentity], function(data) { + $.when(request1, request2).done(function(data,typeToUrlMap) { + typeToUrlMap = typeToUrlMap[0]; + if (data[0].length == 0) { + self.$elem.find('#loading-mssg').remove(); + self.$elem.append("
      There are no other data objects (you can access) that reference this object."); + } else { + var refList = {}; + for(var i = 0; i < data[0].length; i++) { + var objInfo = data[0][i]; + //0:obj_id objid, 1:obj_name name, 2:type_string type,3:timestamp save_date, 4:int version, 5:username saved_by, + //6:ws_id wsid, 7:ws_name workspace, 8:string chsum, 9:int size, 10:usermeta meta> + //object_info; + if (!(objInfo[6]+"/"+objInfo[1] in refList)) { + refList[objInfo[6]+"/"+objInfo[1]] = objInfo; + + } else { + if (refList[objInfo[6]+"/"+objInfo[1]][4] < objInfo[4]) { + refList[objInfo[6]+"/"+objInfo[1]] = objInfo; + + } + } + + // load the data into a data object + var refTableData = []; + for(var ref in refList) { + var objInfo = refList[ref]; + var savedate = new Date(objInfo[3]); + var objName = objInfo[1]; + + var full_type = objInfo[2]; + var module = full_type.split('.')[0]; + var type = full_type.slice(full_type.indexOf('.')+1); + type = type.split('-')[0]; + if (typeToUrlMap && typeToUrlMap[module] && typeToUrlMap[module][type]) { + objName = '' + objName + ''; + } + + refTableData.push({ + na:objName+ " ("+objInfo[6]+"/"+objInfo[0]+"/"+objInfo[4]+")", + ty:objInfo[2], + de:"saved by "+objInfo[5]+" on "+self.monthLookup[savedate.getMonth()]+" "+savedate.getDate()+", "+savedate.getFullYear() + }) + } + //self.$elem.append(""+objInfo[1]+" "+objInfo[2]+" ("+objInfo[6]+"/"+objInfo[0]+"/"+objInfo[4]+", saved by " + // +objInfo[5]+" on "+self.monthLookup[savedate.getMonth()]+" "+savedate.getDate()+", "+savedate.getFullYear()+")
      ") + } + + self.$elem.find('#loading-mssg').remove(); + + var $maindiv = self.$elem.find('#mainview'); + $maindiv.append(''); + var sDom = 't' + if (refTableData.length<=10) { sDom = 'tfi'; } + var tblSettings = { + //"sPaginationType": "full_numbers", + "iDisplayLength": 10, + "sDom": sDom, + "aoColumns": [ + {sTitle: "Object Name (reference)", mData: "na", sWidth:"30%"}, + {sTitle: "Type", mData: "ty"}, + {sTitle: "Details", mData: "de"} + ], + "aaData": refTableData + + /*"fnDrawCallback": function() {} + $('.'+pref+'contig-click').unbind('click'); + $('.'+pref+'contig-click').click(function() { + var contigId = [$(this).data('contigname')]; + showContig(contigId); + }); + }*/ + }; + var refTable = self.$elem.find('#ref-table').dataTable(tblSettings); + } + }).fail(function(err){ + self.$elem.find('#loading-mssg').remove(); + self.$elem.append("
      There are no other data objects (you can access) that reference this object."); + console.error("Error in finding referencing objects! (note: v0.1.6 throws this error if no referencing objects were found)"); + console.error(err); + //self.$elem.append("
      Error was:
      "+err['error']['message']+"

      "); + }); + + return this; + }, + + getData: function() { + return {title:"Other data objects that reference this object",id:this.objName, workspace:this.wsName}; + }, + + + /* Construct an ObjectIdentity that can be used to query the WS*/ + getObjectIdentity: function(wsNameOrId, objNameOrId, objVer) { + if (objVer) { return {ref:wsNameOrId+"/"+objNameOrId+"/"+objVer}; } + return {ref:wsNameOrId+"/"+objNameOrId } ; + }, + + monthLookup : ["Jan", "Feb", "Mar","Apr", "May", "Jun", "Jul", "Aug", "Sep","Oct", "Nov", "Dec"] + + }); +})( jQuery ) \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006559_importer.js b/pool/shard001/JavaScript/0006559_importer.js new file mode 100644 index 0000000000000000000000000000000000000000..b614febbf4e9d2521e9a764223a2d8beb83f8053 --- /dev/null +++ b/pool/shard001/JavaScript/0006559_importer.js @@ -0,0 +1,37 @@ +/* +_IMPORTS = {} +_VALID_NAMES = ['stdlib'] +def read_file(fname): + if (!(_VALID_NAMES.indexOf(fname) >= 0)): + #Don't even try to import a name we do not know + throw "Cannot Import " + fname; + if (!(fname in _IMPORTS)): + request = new XMLHttpRequest(); + # `false` makes the request synchronous + request.open('GET', '/rapydscript/src/'+fname+'.pyj', false) + request.send(null) + if (request.status is 200): + _IMPORTS[fname] = request.responseText + else: + throw "404 (File not found)" + + return _IMPORTS[fname] +*/ + +_IMPORTS = {}; + + +function import_read_file(fname) { + var request; + if (!(fname in _IMPORTS)) { + request = new XMLHttpRequest(); + request.open("GET", "/src/lib/" + fname, false); + request.send(null); + if (request.status === 200) { + _IMPORTS[fname] = request.responseText; + } else { + throw "404 (File not found)"; + } + } + return _IMPORTS[fname]; +} diff --git a/pool/shard001/JavaScript/0006560_placeholder_polyfill.jquery.js b/pool/shard001/JavaScript/0006560_placeholder_polyfill.jquery.js new file mode 100644 index 0000000000000000000000000000000000000000..40dc62e46706c46216483270c72df957ce5bc97f --- /dev/null +++ b/pool/shard001/JavaScript/0006560_placeholder_polyfill.jquery.js @@ -0,0 +1,223 @@ +/** +* HTML5 placeholder polyfill +* @requires jQuery - tested with 1.6.2 but might as well work with older versions +* +* code: https://github.com/ginader/HTML5-placeholder-polyfill +* please report issues at: https://github.com/ginader/HTML5-placeholder-polyfill/issues +* +* Copyright (c) 2016 Dirk Ginader (ginader.de) +* Dual licensed under the MIT and GPL licenses: +* http://www.opensource.org/licenses/mit-license.php +* http://www.gnu.org/licenses/gpl.html +* +*/ + +(function($) { + var debug = false, + animId; + function showPlaceholderIfEmpty(input,options) { + if( input.val() === '' ){ + input.data('placeholder').removeClass(options.hideClass); + input.addClass(options.placeholderShownClass); + }else{ + input.data('placeholder').addClass(options.hideClass); + input.removeClass(options.placeholderShownClass); + } + } + function hidePlaceholder(input,options){ + input.data('placeholder').addClass(options.hideClass); + input.removeClass(options.placeholderShownClass); + } + function positionPlaceholder(placeholder,input){ + var ta = input.is('textarea'); + var pt = parseFloat(input.css('padding-top')); + var pl = parseFloat(input.css('padding-left')); + + // Determine if we need to shift the header down more. + var offset = input.offset(); + if (pt) { + offset.top += pt; + } + if (pl) { + offset.left += pl; + } + + placeholder.css({ + width : input.innerWidth()-(ta ? 20 : 4), + height : input.innerHeight()-6, + lineHeight : input.css('line-height'), + whiteSpace : ta ? 'normal' : 'nowrap', + overflow : 'hidden' + }).offset(offset); + } + function startFilledCheckChange(input,options){ + var val = input.val(); + (function checkloop(){ + animId = requestAnimationFrame(checkloop); + if(input.val() !== val){ + hidePlaceholder(input,options); + stopCheckChange(); + startEmptiedCheckChange(input,options); + } + }()); + } + function startEmptiedCheckChange(input,options){ + (function checkloop(){ + animId = requestAnimationFrame(checkloop); + showPlaceholderIfEmpty(input,options); + }()); + } + function stopCheckChange(){ + if (window.cancelAnimationFrame) { + cancelAnimationFrame(animId); + } + } + function log(msg){ + if(debug && window.console && window.console.log){ + window.console.log(msg); + } + } + + $.fn.placeHolder = function(config) { + log('init placeHolder'); + var o = this; + var l = $(this).length; + this.options = $.extend({ + className: 'placeholder', // css class that is used to style the placeholder + placeholderShownClass: 'placeholder-shown', // css class that is applied to a form field when its Placeholder is visible (polyfill for :placeholder-shown pseudo selector: https://www.w3.org/TR/selectors4/#placeholder-shown-pseudo) + visibleToScreenreaders : true, // expose the placeholder text to screenreaders or not + visibleToScreenreadersHideClass : 'placeholder-hide-except-screenreader', // css class is used to visually hide the placeholder + visibleToNoneHideClass : 'placeholder-hide', // css class used to hide the placeholder for all + hideOnFocus : false, // either hide the placeholder on focus or on type + removeLabelClass : 'visuallyhidden', // remove this class from a label (to fix hidden labels) + hiddenOverrideClass : 'visuallyhidden-with-placeholder', // replace the label above with this class + forceHiddenOverride : true, // allow the replace of the removeLabelClass with hiddenOverrideClass or not + forceApply : false, // apply the polyfill even for browser with native support + autoInit : true // init automatically or not + }, config || window.placeHolderConfig); + this.options.hideClass = this.options.visibleToScreenreaders ? this.options.visibleToScreenreadersHideClass : this.options.visibleToNoneHideClass; + return $(this).each(function(index) { + var input = $(this), + text = input.attr('placeholder'), + id = input.attr('id'), + label,placeholder,titleNeeded,polyfilled; + + function onFocusIn() { + if(!o.options.hideOnFocus && window.requestAnimationFrame){ + startFilledCheckChange(input,o.options); + }else{ + hidePlaceholder(input,o.options); + } + } + + if(text === "" || text === undefined) { + text = input[0].attributes["placeholder"] ? input[0].attributes["placeholder"].value : ""; + } + label = input.closest('label'); + input.removeAttr('placeholder'); + if(!label.length && !id){ + log('the input element with the placeholder needs an id!'); + return; + } + label = label.length ? label : $('label[for="'+id+'"]').first(); + if(!label.length){ + log('the input element with the placeholder needs a label!'); + return; + } + polyfilled = $(label).find('.' + o.options.className); + if(polyfilled.length) { + //log('the input element already has a polyfilled placeholder!'); + positionPlaceholder(polyfilled,input); + polyfilled.text(text); + return input; + } + if(label.hasClass(o.options.removeLabelClass)){ + label.removeClass(o.options.removeLabelClass) + .addClass(o.options.hiddenOverrideClass); + } + + placeholder = $('').addClass(o.options.className).text(text).appendTo(label); + + titleNeeded = (placeholder.width() > input.width()); + if(titleNeeded){ + placeholder.attr('title',text); + } + positionPlaceholder(placeholder,input); + input.data('placeholder',placeholder); + placeholder.data('input',input); + placeholder.click(function(){ + $(this).data('input').focus(); + }); + input.focusin(onFocusIn); + input.focusout(function(){ + showPlaceholderIfEmpty($(this),o.options); + if(!o.options.hideOnFocus){ + stopCheckChange(); + } + }); + input.change(function(){ + showPlaceholderIfEmpty($(this),o.options); + }); + showPlaceholderIfEmpty(input,o.options); + + // reformat on window resize and optional reformat on font resize - requires: http://www.tomdeater.com/jquery/onfontresize/ + $(document).bind("fontresize resize", function(){ + positionPlaceholder(placeholder,input); + }); + + // optional reformat when a textarea is being resized - requires http://benalman.com/projects/jquery-resize-plugin/ + if($.event.special.resize){ + $("textarea").bind("resize", function(event){ + if ($(this).is(":visible")) { + positionPlaceholder(placeholder,input); + } + event.stopPropagation(); + event.preventDefault(); + }); + }else{ + // we simply disable the resizeablilty of textareas when we can't react on them resizing + $("textarea").css('resize','none'); + } + + if(index >= l-1 && typeof $.attrHooks !== 'undefined'){ + $.attrHooks.placeholder = { + get: function(elem) { + if (elem.nodeName.toLowerCase() === 'input' || elem.nodeName.toLowerCase() === 'textarea') { + if( $(elem).data('placeholder') ){ + // has been polyfilled + return $( $(elem).data('placeholder') ).text(); + }else{ + // native / not yet polyfilled + return $(elem)[0].placeholder; + } + }else{ + return undefined; + } + }, + set: function(elem, value){ + return $( $(elem).data('placeholder') ).text(value); + } + }; + } + + if (input.is(":focus")) { + onFocusIn(); + } + }); + + + + }; + $(function(){ + var config = window.placeHolderConfig || {}; + if(config.autoInit === false){ + log('placeholder:abort because autoInit is off'); + return; + } + if(('placeholder' in $('')[0] || 'placeHolder' in $('')[0]) && !config.forceApply){ // don't run the polyfill when the browser has native support + log('placeholder:abort because browser has native support'); + return; + } + $('input[placeholder], textarea[placeholder]').placeHolder(); + }); +}(jQuery)); diff --git a/pool/shard001/JavaScript/0006564_storage_sql.js b/pool/shard001/JavaScript/0006564_storage_sql.js new file mode 100644 index 0000000000000000000000000000000000000000..f8f819141d0f765a3646d114e3f63b42f6740e2d --- /dev/null +++ b/pool/shard001/JavaScript/0006564_storage_sql.js @@ -0,0 +1,164 @@ +'use strict' + +// a bridge between the generic auth frontend and actual sql backend storage +const async = require('async') +const options = require('template-tools/src/utils/options') +const databaseTools = require('../database/tools') +const tools = require('./tools') + +const SQL = require('./storage_sql_queries') + +const REQUIRED = [ + 'knex' +] + +const DEFAULT_TABLES = { + installation: 'installation', + resource: 'resource', + link: 'resource_link' +} + +const DEFAULTS = { + +} + +const DiggerStorageSQL = (opts) => { + opts = options.processor(opts, { + required: REQUIRED, + defaults: DEFAULTS + }) + + const knex = opts.knex + + const tables = options.processor(opts.tables, { + defaults: DEFAULT_TABLES + }) + + const sqlQueries = SQL({ tables }) + + + // * installationid + // * ids[] + const loadLinks = (query, done) => { + const { sql, params } = sqlQueries.links(query) + knex + .raw(sql, params) + .asCallback(databaseTools.allExtractor(done)) + } + + // id + const getResource = (id, done) => { + return knex + .select() + .table(tables.resource) + .where({ + id + }) + .asCallback(databaseTools.singleExtractor(done)) + } + + + // * installationid + // * id + // * type + // * search + // * namespace + const search = (query, done) => { + const { sql, params } = sqlQueries.search(query) + knex + .raw(sql, params) + .asCallback(databaseTools.allExtractor(done)) + } + + // * installationid + // * id + // * namespace + const children = (query, done) => { + const { sql, params } = sqlQueries.children(query) + knex + .raw(sql, params) + .asCallback(databaseTools.allExtractor(done)) + } + + // * installationid + // * id + // * type + // * search + // * namespace + const descendents = (query, done) => { + const { sql, params } = sqlQueries.descendents(query) + knex + .raw(sql, params) + .asCallback(databaseTools.allExtractor(done)) + } + + + const insertResource = (trx, data, done) => { + return knex + .insert(data) + .into(tables.resource) + .returning('*') + .transacting(trx) + .asCallback(databaseTools.singleExtractor(done)) + } + + const saveResource = (trx, id, data, done) => { + return knex(tables.resource) + .where({id}) + .update(data) + .returning('*') + .transacting(trx) + .asCallback(databaseTools.singleExtractor(done)) + } + + const createLinks = (trx, data, done) => { + return knex + .insert(data) + .into(tables.link) + .returning('*') + .transacting(trx) + .asCallback(databaseTools.allExtractor(done)) + } + + + // * id + // * installationid + const del = (trx, query, done) => { + knex(tables.resource) + .where({ + id: query.id, + installation: query.installationid + }) + .del() + .asCallback(databaseTools.singleExtractor(done)) + } + + // * id + // * installationid + const deleteLinks = (trx, id, done) => { + knex(tables.link) + .where({ + parent: id + }) + .del() + .asCallback(databaseTools.singleExtractor(done)) + } + + const transaction = (handler, done) => databaseTools.knexTransaction(knex, handler, done) + + return { + loadLinks, + getResource, + search, + children, + descendents, + insertResource, + saveResource, + createLinks, + deleteLinks, + del, + transaction + } +} + +module.exports = DiggerStorageSQL \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006565_graph.js b/pool/shard001/JavaScript/0006565_graph.js new file mode 100644 index 0000000000000000000000000000000000000000..c8eef1784cd092cbee14550ff073722cd3396826 --- /dev/null +++ b/pool/shard001/JavaScript/0006565_graph.js @@ -0,0 +1,196 @@ +var margin = {top: 50, right: 0, bottom: 100, left: 500}, + width = 1000 - margin.left - margin.right, + height = 500 - margin.top - margin.bottom; + +/* +* value accessor - returns the value to encode for a given data object. +* scale - maps value to a visual display encoding, such as a pixel position. +* map function - maps from data value to display value +* axis - sets up axis +*/ + +// setup x +var xValue = function(d) { return d.duracao;}, // data -> value + x = d3.scaleLinear().range([0, width]), // value -> display + xMap = function(d) { return x(xValue(d));}, // data -> display + xAxis = d3.axisBottom(x); + +// setup y +var yValue = function(d) { return d["foi"];}, // data -> value + y = d3.scaleLinear().range([height, 0]), // value -> display + yMap = function(d) { return y(yValue(d));}, // data -> display + yAxis = d3.axisLeft(y); + +// setup fill color +var cValue = function(d) { return d.Manufacturer;}, + color = d3.scaleOrdinal(d3.schemeCategory10); + +// add the graph canvas to the body of the webpage +var svg = d3.select("body").append("svg") + .attr("width", width + margin.left + margin.right) + .attr("height", height + margin.top + margin.bottom) +.append("g") + .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); + +// add the tooltip area to the webpage +var tooltip = d3.select("body").append("div") + .attr("class", "tooltip") + .style("opacity", 0); + +// load data +d3.csv("data.csv", function(error, data) { + +// change string (from CSV) into number format +data.forEach(function(d) { + d.duracao = +d.duracao; + d["foi"] = +d["foi"]; + console.log(d); +}); + +// don't want dots overlapping axis, so add in buffer to data domain +x.domain([d3.min(data, xValue), d3.max(data, xValue)]); +y.domain([d3.min(data, yValue), d3.max(data, yValue)+1]); + +var lg = calcLinear(data, "duracao", "foi", d3.min(data, xValue), d3.min(data, yValue)); + +svg.append("line") + .attr("class", "regression") + .attr("x1", x(lg.ptA.x)) + .attr("y1", y(lg.ptA.y)) + .attr("x2", x(lg.ptB.x)) + .attr("y2", y(lg.ptB.y)); + + +// x-axis +svg.append("g") + .attr("class", "x axis") + .attr("transform", "translate(0," + height + ")") + .call(xAxis) + .append("text") + .attr("class", "label") + .attr("x", width) + .attr("y", -6) + .style("text-anchor", "end") + .text("duracao"); + +// y-axis +svg.append("g") + .attr("class", "y axis") + .call(yAxis) + .append("text") + .attr("class", "label") + .attr("transform", "rotate(-90)") + .attr("y", 6) + .attr("dy", ".71em") + .style("text-anchor", "end") + .text("foi"); + +// draw dots +svg.selectAll(".dot") + .data(data) + .enter().append("circle") + .attr("class", "dot") + .attr("r", 3.5) + .attr("cx", xMap) + .attr("cy", yMap) + .style("fill", function(d) { return color(cValue(d));}) + .on("mouseover", function(d) { + tooltip.transition() + .duration(200) + .style("opacity", .9); + tooltip.html(d["foi"] + "
      (" + xValue(d) + + ", " + yValue(d) + ")") + .style("left", (d3.event.pageX + 5) + "px") + .style("top", (d3.event.pageY - 28) + "px"); + }) + .on("mouseout", function(d) { + tooltip.transition() + .duration(500) + .style("opacity", 0); + }); + +// draw legend +var legend = svg.selectAll(".legend") + .data(color.domain()) + .enter().append("g") + .attr("class", "legend") + .attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; }); + + +// draw legend text +legend.append("text") + .attr("x", width - 24) + .attr("y", 9) + .attr("dy", ".35em") + .style("text-anchor", "end") + .text(function(d) { return d;}) +}); + +function calcLinear(data, x, y, minX, minY){ + ///////// + //SLOPE// + ///////// + + // Let n = the number of data points + var n = data.length; + + var pts = []; + data.forEach(function(d,i){ + var obj = {}; + obj.x = d[x]; + obj.y = d[y]; + obj.mult = obj.x*obj.y; + pts.push(obj); + }); + + // Let a equal n times the summation of all x-values multiplied by their corresponding y-values + // Let b equal the sum of all x-values times the sum of all y-values + // Let c equal n times the sum of all squared x-values + // Let d equal the squared sum of all x-values + var sum = 0; + var xSum = 0; + var ySum = 0; + var sumSq = 0; + pts.forEach(function(pt){ + sum = sum + pt.mult; + xSum = xSum + pt.x; + ySum = ySum + pt.y; + sumSq = sumSq + (pt.x * pt.x); + }); + var a = sum * n; + var b = xSum * ySum; + var c = sumSq * n; + var d = xSum * xSum; + + // Plug the values that you calculated for a, b, c, and d into the following equation to calculate the slope + // m = (a - b) / (c - d) + var m = (a - b) / (c - d); + + ///////////// + //INTERCEPT// + ///////////// + + // Let e equal the sum of all y-values + var e = ySum; + + // Let f equal the slope times the sum of all x-values + var f = m * xSum; + + // Plug the values you have calculated for e and f into the following equation for the y-intercept + // y-intercept = b = (e - f) / n = (14.5 - 10.5) / 3 = 1.3 + var b = (e - f) / n; + + // return an object of two points + // each point is an object with an x and y coordinate + return { + ptA : { + x: minX, + y: m * minX + b + }, + ptB : { + y: minY, + x: (minY - b) / m + } + } + +} diff --git a/pool/shard001/JavaScript/0006566_db.js b/pool/shard001/JavaScript/0006566_db.js new file mode 100644 index 0000000000000000000000000000000000000000..bf9fb1a7f56c401d7e266e28ab7efd252ad54ef6 --- /dev/null +++ b/pool/shard001/JavaScript/0006566_db.js @@ -0,0 +1,39 @@ +//import pg from 'pg'; +var pg = require('pg'); +var Pool = require('pg-pool'); +//const conString = "postgres://vbgqlfpjfnnnkf:df3903e05d4711ce45db00b3fccde25e1e74c6805e97a92cc05c1a3f9d703444@ec2-54-243-197-180.compute-1.amazonaws.com:5432/d88the3bl2c30r"; + +var pool = new Pool({ + user: "bsjrwnolzcfanb", + password: "3c5b974c334f538cc9dda4c6e56bc55ffaf226de6c6b57bc58a6287823766024", + database: "d3lp0cr6bvd2f3", + port: 5432, + host: "ec2-184-73-159-137.compute-1.amazonaws.com", + ssl: true, + idleTimeoutMillis: 30000, +}); + +//var pool = new Pool(config); + +module.exports = function(q, callback) { + pool.connect(function(error, client, done) { + if (error) { + callback(error, null); + } + client.query(q, function(err, result) { + //call `done()` to release the client back to the pool + done(); + + if (err) { + callback(err, null) + } + + callback(null, result) + }); + }); + + +} +pool.on('error', function(err, client) { + console.error('idle client error', err.message, err.stack) +}); diff --git a/pool/shard001/JavaScript/0006568_gis.js b/pool/shard001/JavaScript/0006568_gis.js new file mode 100644 index 0000000000000000000000000000000000000000..23cc77dbabd1be8d567d53455406d3bc914f0618 --- /dev/null +++ b/pool/shard001/JavaScript/0006568_gis.js @@ -0,0 +1,55 @@ + +function library(_){ + + var gis = {}; + + var rad = function(x) { + return x * Math.PI / 180; + }; + + gis.point = function(p){ + if(!p){ return(null); } + + var lon = p.lon + if(lon === undefined){ lon = p.lng; } + if(lon === undefined){ lon = p.longitude; } + + var lat = p.lat; + if(lat === undefined){ lat = p.latitude; } + + if(_.isFunction(lon)){ lon = _.bind(lon, p)(); } + if(_.isFunction(lat)){ lat = _.bind(lat, p)(); } + + lat = _.n(lat); + lon = _.n(lon); + + if(lat === null || lon === null){ return(null); } + else{ return({ lat: lat, lon: lon }); } + }; + + // returns the distance in meters + + gis.distance = function(p1, p2, R) { + R = R || 6378137; // Earth's mean radius in meters + + p1 = gis.point(p1); + p2 = gis.point(p2); + + if(!p1 || !p2){ return(null); } + + var dLat = rad(p2.lat - p1.lat); + var dLong = rad(p2.lon - p1.lon); + var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + + Math.cos(rad(p1.lat)) * Math.cos(rad(p2.lat)) * + Math.sin(dLong / 2) * Math.sin(dLong / 2); + var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); + var d = R * c; + return d; + }; + + gis.library = library; + + return(gis); +} + +exports.library = library; diff --git a/pool/shard001/JavaScript/0006572_index.js b/pool/shard001/JavaScript/0006572_index.js new file mode 100644 index 0000000000000000000000000000000000000000..f801d1b2e262df31274ab9f65fa2ba21ba2c21e9 --- /dev/null +++ b/pool/shard001/JavaScript/0006572_index.js @@ -0,0 +1,49 @@ +// The module api is in *Locked* state, so it will not change +// see http://nodejs.org/api/modules.html +// that is why I just copyed and pasted the orig module wrapper. +// +// By the way, in test.js checks if the content of *origWrapper* needs an update. + +var origWrapper = '(function (exports, require, module, __filename, __dirname) { ' +var strictWrapper = origWrapper + '"use strict";' + +/** + * Wraps module `exports` + * + * See [Usage](http://npm.im/strict-mode#usage) + * ) + * + * @param {Function} callback containing caller package's exports statements + */ + +function strictMode (callback) { + "use strict"; + + if (typeof callback !== 'function') { + throw new TypeError('Argument *callback* must be a function') + } + + var module = require('module') + + if (typeof module.wrapper === 'undefined') { + // If you enter here, you are in a context other than server side Node.js. + // Since module.wrapper it is not defined do not switch strict mode on. + callback() + } else { + if (module.wrapper[0] === origWrapper) { + module.wrapper[0] = strictWrapper + + // Every require in this callback will load modules in strict mode. + try { callback() } + catch (err) { console.error(err.stack) } + + // Restore orig module wrapper, play well with others. + module.wrapper[0] = origWrapper + } else { + // If module.wrapper[0] changed, do not switch strict mode on. + callback() + } + } +} + +module.exports = strictMode diff --git a/pool/shard001/JavaScript/0006576_merkle.js b/pool/shard001/JavaScript/0006576_merkle.js new file mode 100644 index 0000000000000000000000000000000000000000..79a6338912724e4976e61c50e5ff96b0b19e2666 --- /dev/null +++ b/pool/shard001/JavaScript/0006576_merkle.js @@ -0,0 +1,106 @@ +/*jslint node: true */ +"use strict"; +var crypto = require('crypto'); + +function hash(str){ + return crypto.createHash("sha256").update(str, "utf8").digest("base64"); +} + +function getMerkleRoot(arrElements){ + var arrHashes = arrElements.map(hash); + while (arrHashes.length > 1){ + var arrOverHashes = []; // hashes over hashes + for (var i=0; i= arrElements.length) + throw Error("invalid index"); + var arrHashes = arrElements.map(hash); + var index = element_index; + var arrSiblings = []; + while (arrHashes.length > 1){ + var arrOverHashes = []; // hashes over hashes + var overIndex = null; + for (var i=0; i 1) + serialized_proof += "-"+proof.siblings.join("-"); + serialized_proof += "-"+proof.root; + return serialized_proof; +}*/ + +// returns a string element_index-siblings_joined_by_dash-root +function serializeMerkleProof(proof){ + var serialized_proof = proof.index; + if (proof.siblings.length > 0) + serialized_proof += "-"+proof.siblings.join("-"); + serialized_proof += "-"+proof.root; + return serialized_proof; +} + +function deserializeMerkleProof(serialized_proof){ + var arr = serialized_proof.split("-"); + var proof = {}; + proof.root = arr.pop(); + proof.index = arr.shift(); + proof.siblings = arr; + return proof; +} + +function verifyMerkleProof(element, proof){ + var index = proof.index; + var the_other_sibling = hash(element); + for (var i=0; i 0) { + siteserver.displayResponse(errors.join(", "), 'error'); + } + else { + var userURL = document.getElementById('userURL').value; + if (!userURL) // if user did not provide a userURL, default to #owner + userURL = '#owner'; + var account = { + 'ce_account_id' : accountId, + 'ce_password': password, + 'vcard_email': email, + 'ce_user': { + 'rdf_type': new rdf_util.URI(FOAF+'Person'), + 'foaf_givenName' : document.getElementById('givenName').value, + 'foaf_familyName' : document.getElementById('familyName').value, + 'foaf_nick' : document.getElementById('nick').value, + '_subject': userURL + }, + 'vcard_adr': { + 'rdf_type': new rdf_util.URI(VCARD+'Home'), + 'vcard_street__address': document.getElementById('street').value, + 'vcard_locality': document.getElementById('city').value, + 'vcard_region': document.getElementById('state').value, + 'vcard_postal__code': document.getElementById('zip').value, + 'vcard_country__name': document.getElementById('country').value, + '_subject': '_:address' + }, + 'rdf_type': new rdf_util.URI(CE+'Account'), + '_subject': '' + } + var rdf_util_doc = APPLICATION_ENVIRON.rdf_converter.convert_to_rdf_jso(account); + // normally new resources are created via POST, and the server controls the URL of the newly-created resource + // In the case of accounts, we want to control the URL, so we make up the URL below and use PUT to do the create + ld_util.send_create(APPLICATION_ENVIRON.initial_simple_jso.ce_account__container, rdf_util_doc, self.handle_result); + } + }; +} diff --git a/pool/shard001/JavaScript/0006578_contact.server.model.tests.js b/pool/shard001/JavaScript/0006578_contact.server.model.tests.js new file mode 100644 index 0000000000000000000000000000000000000000..0be144adbe11c86f77d7cdfc0578a2eee448f16a --- /dev/null +++ b/pool/shard001/JavaScript/0006578_contact.server.model.tests.js @@ -0,0 +1,93 @@ +/** + * Module dependencies. + */ +const should = require('should'); +const mongoose = require('mongoose'); +const utils = require('../../../../testutils/server/data.server.testutil'); + +const User = mongoose.model('User'); +const Contact = mongoose.model('Contact'); + +/** + * Globals + */ +let user1; +let user2; +let user1Id; +let user2Id; +let contact; + +/** + * Unit tests + */ +describe('Contact Model Unit Tests:', function () { + beforeEach(function (done) { + user1 = new User({ + firstName: 'Full', + lastName: 'Name', + displayName: 'Full Name', + email: 'test1@test.com', + username: 'username1', + password: 'password123!', + provider: 'local', + }); + + user2 = new User({ + firstName: 'Full', + lastName: 'Name', + displayName: 'Full Name', + email: 'test2@test.com', + username: 'username2', + password: 'password123!', + provider: 'local', + }); + + // Create users + user1.save(function () { + user1Id = user1._id; + + user2.save(function () { + user2Id = user2._id; + + // Create connection between users + contact = new Contact({ + userFrom: user1Id, + userTo: user2Id, + created: new Date(), + confirmed: true, + }); + + done(); + }); + }); + }); + + afterEach(utils.clearDatabase); + + describe('Method Save', function () { + it('should be able to save without problems', function (done) { + contact.save(function (err) { + should.not.exist(err); + return done(); + }); + }); + + it('should be able to show an error when try to save without `userFrom`', function (done) { + contact.userFrom = ''; + + contact.save(function (err) { + should.exist(err); + return done(); + }); + }); + + it('should be able to show an error when try to save without `userTo`', function (done) { + contact.userTo = ''; + + contact.save(function (err) { + should.exist(err); + return done(); + }); + }); + }); +}); diff --git a/pool/shard001/JavaScript/0006579_b2Contact.js b/pool/shard001/JavaScript/0006579_b2Contact.js new file mode 100644 index 0000000000000000000000000000000000000000..1626a7e074ad47a24d750a2423590f34ffef7240 --- /dev/null +++ b/pool/shard001/JavaScript/0006579_b2Contact.js @@ -0,0 +1,201 @@ +/* +* Copyright (c) 2006-2007 Erin Catto http: +* +* This software is provided 'as-is', without any express or implied +* warranty. In no event will the authors be held liable for any damages +* arising from the use of this software. +* Permission is granted to anyone to use this software for any purpose, +* including commercial applications, and to alter it and redistribute it +* freely, subject to the following restrictions: +* 1. The origin of this software must not be misrepresented; you must not +* claim that you wrote the original software. If you use this software +* in a product, an acknowledgment in the product documentation would be +* appreciated but is not required. +* 2. Altered source versions must be plainly marked, and must not be +* misrepresented the original software. +* 3. This notice may not be removed or altered from any source distribution. +*/ + + + + + +//typedef b2Contact* b2ContactCreateFcn(b2Shape* shape1, b2Shape* shape2, b2BlockAllocator* allocator); +//typedef void b2ContactDestroyFcn(b2Contact* contact, b2BlockAllocator* allocator); + + + +var b2Contact = Class.create(); +b2Contact.prototype = +{ + GetManifolds: function(){return null}, + GetManifoldCount: function() + { + return this.m_manifoldCount; + }, + + GetNext: function(){ + return this.m_next; + }, + + GetShape1: function(){ + return this.m_shape1; + }, + + GetShape2: function(){ + return this.m_shape2; + }, + + //--------------- Internals Below ------------------- + + // this.m_flags + // enum + + + initialize: function(s1, s2) + { + // initialize instance variables for references + this.m_node1 = new b2ContactNode(); + this.m_node2 = new b2ContactNode(); + // + + this.m_flags = 0; + + if (!s1 || !s2){ + this.m_shape1 = null; + this.m_shape2 = null; + return; + } + + this.m_shape1 = s1; + this.m_shape2 = s2; + + this.m_manifoldCount = 0; + + this.m_friction = Math.sqrt(this.m_shape1.m_friction * this.m_shape2.m_friction); + this.m_restitution = b2Math.b2Max(this.m_shape1.m_restitution, this.m_shape2.m_restitution); + + this.m_prev = null; + this.m_next = null; + + this.m_node1.contact = null; + this.m_node1.prev = null; + this.m_node1.next = null; + this.m_node1.other = null; + + this.m_node2.contact = null; + this.m_node2.prev = null; + this.m_node2.next = null; + this.m_node2.other = null; + }, + + //virtual ~b2Contact() {} + + Evaluate: function(){}, + + m_flags: 0, + + // World pool and list pointers. + m_prev: null, + m_next: null, + + // Nodes for connecting bodies. + m_node1: new b2ContactNode(), + m_node2: new b2ContactNode(), + + m_shape1: null, + m_shape2: null, + + m_manifoldCount: 0, + + // Combined friction + m_friction: null, + m_restitution: null}; +b2Contact.e_islandFlag = 0x0001; +b2Contact.e_destroyFlag = 0x0002; +b2Contact.AddType = function(createFcn, destroyFcn, type1, type2) + { + //b2Settings.b2Assert(b2Shape.e_unknownShape < type1 && type1 < b2Shape.e_shapeTypeCount); + //b2Settings.b2Assert(b2Shape.e_unknownShape < type2 && type2 < b2Shape.e_shapeTypeCount); + + b2Contact.s_registers[type1][type2].createFcn = createFcn; + b2Contact.s_registers[type1][type2].destroyFcn = destroyFcn; + b2Contact.s_registers[type1][type2].primary = true; + + if (type1 != type2) + { + b2Contact.s_registers[type2][type1].createFcn = createFcn; + b2Contact.s_registers[type2][type1].destroyFcn = destroyFcn; + b2Contact.s_registers[type2][type1].primary = false; + } + }; +b2Contact.InitializeRegisters = function(){ + b2Contact.s_registers = new Array(b2Shape.e_shapeTypeCount); + for (var i = 0; i < b2Shape.e_shapeTypeCount; i++){ + b2Contact.s_registers[i] = new Array(b2Shape.e_shapeTypeCount); + for (var j = 0; j < b2Shape.e_shapeTypeCount; j++){ + b2Contact.s_registers[i][j] = new b2ContactRegister(); + } + } + + b2Contact.AddType(b2CircleContact.Create, b2CircleContact.Destroy, b2Shape.e_circleShape, b2Shape.e_circleShape); + b2Contact.AddType(b2PolyAndCircleContact.Create, b2PolyAndCircleContact.Destroy, b2Shape.e_polyShape, b2Shape.e_circleShape); + b2Contact.AddType(b2PolyContact.Create, b2PolyContact.Destroy, b2Shape.e_polyShape, b2Shape.e_polyShape); + + }; +b2Contact.Create = function(shape1, shape2, allocator){ + if (b2Contact.s_initialized == false) + { + b2Contact.InitializeRegisters(); + b2Contact.s_initialized = true; + } + + var type1 = shape1.m_type; + var type2 = shape2.m_type; + + //b2Settings.b2Assert(b2Shape.e_unknownShape < type1 && type1 < b2Shape.e_shapeTypeCount); + //b2Settings.b2Assert(b2Shape.e_unknownShape < type2 && type2 < b2Shape.e_shapeTypeCount); + + var createFcn = b2Contact.s_registers[type1][type2].createFcn; + if (createFcn) + { + if (b2Contact.s_registers[type1][type2].primary) + { + return createFcn(shape1, shape2, allocator); + } + else + { + var c = createFcn(shape2, shape1, allocator); + for (var i = 0; i < c.GetManifoldCount(); ++i) + { + var m = c.GetManifolds()[ i ]; + m.normal = m.normal.Negative(); + } + return c; + } + } + else + { + return null; + } + }; +b2Contact.Destroy = function(contact, allocator){ + //b2Settings.b2Assert(b2Contact.s_initialized == true); + + if (contact.GetManifoldCount() > 0) + { + contact.m_shape1.m_body.WakeUp(); + contact.m_shape2.m_body.WakeUp(); + } + + var type1 = contact.m_shape1.m_type; + var type2 = contact.m_shape2.m_type; + + //b2Settings.b2Assert(b2Shape.e_unknownShape < type1 && type1 < b2Shape.e_shapeTypeCount); + //b2Settings.b2Assert(b2Shape.e_unknownShape < type2 && type2 < b2Shape.e_shapeTypeCount); + + var destroyFcn = b2Contact.s_registers[type1][type2].destroyFcn; + destroyFcn(contact, allocator); + }; +b2Contact.s_registers = null; +b2Contact.s_initialized = false; diff --git a/pool/shard001/JavaScript/0006582_user.js b/pool/shard001/JavaScript/0006582_user.js new file mode 100644 index 0000000000000000000000000000000000000000..dd040406a4a2743ac8c205269e72412f1a194425 --- /dev/null +++ b/pool/shard001/JavaScript/0006582_user.js @@ -0,0 +1,86 @@ + +/*! + * Module dependencies + */ + +var mongoose = require('mongoose'); +var crypto = require('crypto'); +var Schema = mongoose.Schema; + +/** + * User schema + */ + +var UserSchema = new Schema({ + name: { type: String, default: '' }, + email: { type: String, default: '', unique: true}, + password: { type: String, default: '' }, + salt: { type: String, default: '' }, + role: {type: 'String', enum: ['user', 'admin'], default: 'user'} +}); + +/** + * User plugin + */ + +// UserSchema.plugin(userPlugin, {}); + +/** + * Add your + * - pre-save hooks + * - validations + * - virtuals + */ + +/** + * Hook a pre save method to hash the password + */ +UserSchema.pre('save', function (next) { + // Save only if password is password is not empty and longer than 3 characters + if (this.password && this.isModified('password') && this.password.length >= 3) { + this.salt = crypto.randomBytes(16).toString('base64'); + this.password = this.hashPassword(this.password); + } + + next(); +}); + +/** + * Create instance method for hashing a password + * PBKDF2: password based key derivation function 2 + */ +UserSchema.methods.hashPassword = function (password) { + if (this.salt && password) { + return crypto.pbkdf2Sync(password, new Buffer(this.salt, 'base64'), 10000, 128, 'sha1').toString('base64'); + } else { + return password; + } +}; + +/** + * Create instance method for authenticating user + */ +UserSchema.methods.authenticate = function (password) { + return this.password === this.hashPassword(password); +}; + +/** + * Methods + */ + +UserSchema.method({ + +}); +/** + * Statics + */ + +UserSchema.static({ + +}); + +/** + * Register + */ + +mongoose.model('User', UserSchema); diff --git a/pool/shard001/JavaScript/0006584_array-utils.js b/pool/shard001/JavaScript/0006584_array-utils.js new file mode 100644 index 0000000000000000000000000000000000000000..cd5b3fe93f6011347e2d37672b4b054a1890cb2e --- /dev/null +++ b/pool/shard001/JavaScript/0006584_array-utils.js @@ -0,0 +1,29 @@ +function removeItem(array, condemned){ + return array.filter(function(item){ + return item !== condemned; + }); +} + +function removeAt(array, index){ + var working = array.splice(0); + working.splice(index, 1); + return working; +} + +function reduce(array, callback){ + var reduced = []; + + for(var i = 0; i < array.length; i++){ + reduced[i] = callback(array[i]); + } + + return reduced; +} + +function pluck(array, property){ + return reduce(array, function(item){ + return item[property]; + }); +} + +export { removeItem, removeAt, reduce, pluck }; \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006586_Game.js b/pool/shard001/JavaScript/0006586_Game.js new file mode 100644 index 0000000000000000000000000000000000000000..8b92e0ee149b85468b480691a5bb1e8db578edc2 --- /dev/null +++ b/pool/shard001/JavaScript/0006586_Game.js @@ -0,0 +1,96 @@ +var Veggies = Veggies || {}; + +Veggies.GameState = { + + init: function(currentLevel) { + //keep track of the current level + this.currentLevel = currentLevel ? currentLevel : 'level1'; + + //constants + this.HOUSE_X = 60; + + //no gravity in a top-down game + this.game.physics.arcade.gravity.y = 0; + }, + create: function() { + this.background = this.add.sprite(0, 0, 'background'); + + //group for game objects + this.bullets = this.add.group(); + this.plants = this.add.group(); + this.zombies = this.add.group(); + this.suns = this.add.group(); + + var zombieData = { + asset: 'zombie', + health: 10, + animationFrames: [0, 1, 2, 1], + attack: 0.1, + velocity: -40 + }; + + this.zombie = new Veggies.Zombie(this, 300, 100, zombieData); + this.zombies.add(this.zombie); + + + var plantData = { + plantAsset: 'plant', + health: 10 + }; + + this.plant = new Veggies.Plant(this, 100, 100, plantData); + this.plants.add(this.plant); + + this.bullet = new Veggies.Bullet(this, 100, 200); + this.bullets.add(this.bullet); + }, + update: function() { + this.game.physics.arcade.collide(this.plants, this.zombies, this.attackPlant, null, this) + + this.zombies.forEachAlive(function(zombie){ + //zombies need to keep their speed + zombie.body.velocity.x = zombie.defaultVelocity; + + //if one of them reaches the house, it's game over + if(zombie.x <= this.HOUSE_X) { + this.gameOver(); + } + }, this); + }, + gameOver: function() { + this.game.state.start('Game'); + }, + attackPlant: function(plant, zombie) { + plant.damage(zombie.attack); + }, + createZombie: function(x, y, data) { + //look for a dead element + var newElement = this.zombies.getFirstDead(); + + //if there are no dead ones, create a new one + if(!newElement) { + newElement = new Veggies.Zombie(this, x, y, data); + this.zombies.add(newElement); + } + else { + newElement.reset(x, y, data); + } + + return newElement; + }, + createPlant: function(x, y, data) { + //look for a dead element + var newElement = this.plants.getFirstDead(); + + //if there are no dead ones, create a new one + if(!newElement) { + newElement = new Veggies.Plant(this, x, y, data); + this.plants.add(newElement); + } + else { + newElement.reset(x, y, data); + } + + return newElement; + } +}; diff --git a/pool/shard001/JavaScript/0006587_js_image.js b/pool/shard001/JavaScript/0006587_js_image.js new file mode 100644 index 0000000000000000000000000000000000000000..d964a469ad4bafb34ac0801e042cc91077204895 --- /dev/null +++ b/pool/shard001/JavaScript/0006587_js_image.js @@ -0,0 +1,171 @@ +/** + * JavaScript + * Image object, js 1.3. + * + * 16.07.2001, torstein@opera.com + * $Id: + * + */ +var tprop; +var imageArray; + +function main( imageArray ) +{ + try + { + var cvs = "$Id: js_image.js 4838 2006-01-18 05:59:01Z hallvord $"; + testmodule( "The Image object", cvs ); + + testcase( "document.images exists" ); + this.imageArray = imageArray; + this.tprop = make_tprop( document ); + tprop( "images", "collection" ); + tprop( "mypicture", "object" ); + test( 'length', imageArray.length, 2 ); + + var imageObject = imageArray[ 0 ]; + this.tprop = make_tprop( imageObject ); + testcase( 'Image object properties' ); + testImageProperties( imageObject ); + + testcase( 'Image object methods' ); + testImageMethods( imageObject ); + + testcase( 'Image object event handlers' ); + testImageEventHandlers( imageObject ); + + /* IE5 crashed here */ + try + { + testcase( "Empty Image constructor" ); + var newimage = Image(); + newimage.width = 20; + newimage.height = 2; + this.tprop = make_tprop( newimage ); + testImageConstructor( newimage ); + } + catch( e ) + { + exception( e ); + } + + testcase( "Image constructor with width" ); + var anothernewimage = Image( "20" ); + anothernewimage.height = 2; + test( "width", anothernewimage.width, 20, "81283" ); + test( "width", anothernewimage.height, 2 ); + this.tprop = make_tprop( anothernewimage ); + testImageConstructor( anothernewimage ); + + testcase( "Image constructor with width and height" ); + var yetanothernewimage = Image( "20", "2" ); + test( "width", yetanothernewimage.width, 20, "81283" ); + test( "height", yetanothernewimage.height, 2, "81283" ); + this.tprop = make_tprop( yetanothernewimage ); + testImageConstructor( yetanothernewimage ); + } + catch( e ) + { + exception( e ); + } + + testmodule_finished(); +} + +function testImageConstructor( imageObject ) +{ + if( isExplorer() ) + { + test( 'toString', imageObject, "[object]" ); + } + else + { + test( 'toString', imageObject, "[object HTMLImageElement]" ); + } + + imageObject.hspace = 2; + imageObject.vspace = 10; + imageObject.border = 1; + imageObject.name = "mypicture"; + imageObject.src = "http://www.opera.com/graphics/logo_z.gif"; + imageObject.lowsrc="http://www.opera.com/graphics/company/gallery/ledergruppe.jpg"; + testImageProperties( imageObject ); + testImageMethods( imageObject ); +} + +/* Width and height value tests are performed in main() */ +function testImageProperties( image ) +{ + tprop( "border", "number" ); + tprop( "complete", "boolean" ); + tprop( "height", "number" ); + tprop( "hspace", "number" ); + tprop( "vspace", "number" ); + + if( is_phase( 2 ) ) + tprop( "lowsrc", "string" ); + + tprop( "name", "string" ); + + tprop( "src", "string" ); + tprop( "width", "number" ); + + test( "border", image.border, 1 ); + test( "hspace", image.hspace, 2 ); + test( "vspace", image.vspace, 10 ); + + if( image.lowsrc != undefined ) + { + test( "lowsrc", image.lowsrc, "http://www.opera.com/graphics/company/gallery/ledergruppe.jpg" ); + } + + test( "name", image.name, "mypicture" ); + test( "src", image.src, "http://www.opera.com/graphics/logo_z.gif" ); + + image.src = "http://www.opera.com/newimage.jpg"; + test( "changing src", image.src, "http://www.opera.com/newimage.jpg" ); + + if( image.lowsrc != undefined ) + { + image.lowsrc = "http://www.opera.com/newlowimage.jpg"; + test( "changing lowsrc", image.lowsrc, "http://www.opera.com/newlowimage.jpg" ); + } + + /* Read-only JS 1.3, not read-only in DOM2-HTML */ + image.border = 2; + image.width = 1; + image.height = 1; + image.hspace = 1; + image.vspace = 1; + image.name ="new name"; + + test( "changing image.border", image.border, 2 ); + test( "changing image.width", image.width, 1 ); + test( "changing image.height", image.height, 1 ); + test( "changing image.hspace", image.hspace, 1 ); + test( "changing image.vspace", image.vspace, 1 ); + test( "changing image.name", image.name, "new name" ); + + expect_exception( "Changing a readonly value, complete", Error, function() { image.complete = true; } ); // Bug #85182 is fixed +} + +function testImageMethods( image ) +{ + if( is_phase( 2 ) ) + { + tprop( "handlEvent", "function" ); + } +} + +function testImageEventHandlers( image ) +{ + test_expect_failure( "onabort", "81290", + removeWhiteSpace( "" + image.onabort ), + removeWhiteSpace( getEventHandlerSource( 0 ) ) ); + + test_spaceagnostic( "onerror", "" + image.onerror, getEventHandlerSource( 1 ) ); + test_spaceagnostic( "onkeydown", "" + image.onkeydown, getEventHandlerSource( 2 ) ); + test_spaceagnostic( "onkeypress", "" + image.onkeypress, getEventHandlerSource( 3 ) ); + test_spaceagnostic( "onkeyup", "" + image.onkeyup, getEventHandlerSource( 4 ) ); + test_spaceagnostic( "onload", "" + image.onload, getEventHandlerSource( 5 ) ); +} diff --git a/pool/shard001/JavaScript/0006590_textFixes.js b/pool/shard001/JavaScript/0006590_textFixes.js new file mode 100644 index 0000000000000000000000000000000000000000..6ba88dcbc834bc8d8e400353e33fe19a4f16fdac --- /dev/null +++ b/pool/shard001/JavaScript/0006590_textFixes.js @@ -0,0 +1,87 @@ +// node[~"."~"([\u00A0\u0020][\u00A0\u0020]+|$[\u00A0\u0020]|[\u00A0\u0020]^)"](area.a); +/* +WORK IN PROGRESS +*/ + +var print = require("josm/util").println; +var layer = josm.layers.get(0); +var ds = layer.data; + +function main() +{ + var fixes = [ + {name: "Double whitespace fix", regex: /[\u00A0\u0020][\u00A0\u0020]+/, replaceWith: " "}, + {name: "Whitespace trim", func: function(str){return str.trim();}} + ] + + initStats(fixes); // set all fixes[i] counters to 0 + + print("### Running script - textFixes.js"); + ds.each(function(p){ + for (key in p.tags) + { + for (var i = 0; i < fixes.length; ++i) + { + applyFixToKey(p, fixes[i], key); + } + } + for (key in p.tags) + { + for (var i = 0; i < fixes.length; ++i) + { + applyFixToValue(p, fixes[i], key); + } + } + }); + + print("==Fix stats=="); + + for (var i = 0; i < fixes.length; ++i) + { + var fix = fixes[i]; + print(fix.name + ": " + fix.stats); + } + + print("### Script finished"); +} + +function applyFixToKey(p, fix, key) +{ + var newKey = applyFixToStr(fix, key); + if ((newKey !== null) && (key !== newKey)) + { + p.tags[newKey] = p.tags[key]; + p.removeTag(key); + fix.stats++; + } + +} + +function applyFixToValue(p, fix, key) +{ + var value = p.tags[key]; + var newValue = applyFixToStr(fix, value); + if ((newValue !== null) && (newValue !== value)) + { + p.tags[key] = newValue; + fix.stats++; + } +} + +function applyFixToStr(fix, str) +{ + if (fix.func === undefined) + return str.replace(fix.regex, fix.replaceWith); + else + return fix.func(str); +} + +function initStats(fixes) +{ + for (var i = 0; i < fixes.length; ++i) + { + fixes.stats = 0; + } +} +main(); + diff --git a/pool/shard001/JavaScript/0006595_index.js b/pool/shard001/JavaScript/0006595_index.js new file mode 100644 index 0000000000000000000000000000000000000000..11d25d63e0d896c3445cf254b90d07ef35cd4327 --- /dev/null +++ b/pool/shard001/JavaScript/0006595_index.js @@ -0,0 +1,31 @@ +const path = require('path'); + +module.exports = parser; + +function parser(data, opts) { + if (typeof data === 'string') { + var pptx = JSON.parse(data); + } else { + var pptx = data; + } + let entries = Object.keys(pptx); + let relations = require('./lib/relationParser')(entries, pptx); + let types = require('./lib/typeParser')(entries, pptx); + let presentation = require('./lib/presentationParser')(entries, pptx, relations); + let themes = require('./lib/themeParser')(entries, pptx, presentation); + let slideMasters = require('./lib/slideMasterParser')(entries, pptx, relations, presentation, themes); + let slideLayouts = require('./lib/slideLayoutParser')(entries, pptx, relations, themes); + let slides = require('./lib/slidesParser')(entries, pptx, relations, presentation, themes, slideMasters, slideLayouts); + + let ret = require('./lib/summarize')(relations, presentation, themes, slideMasters, slideLayouts, slides); + + /*opts = {file: 'main.js'}; + if(!!opts && !!opts.file && typeof opts.file === 'string') { + const fs = require('fs'); + fs.writeFile(opts.file, 'var data = ' + JSON.stringify(ret, null, 2), 'utf-8', err => { + if(!!err) console.error(err); + }); + }*/ + + return ret; +} diff --git a/pool/shard001/JavaScript/0006598_gcm.js b/pool/shard001/JavaScript/0006598_gcm.js new file mode 100644 index 0000000000000000000000000000000000000000..0928c8426aeeba8eb000c3f142929cbb314fa8a7 --- /dev/null +++ b/pool/shard001/JavaScript/0006598_gcm.js @@ -0,0 +1,75 @@ +/** + * Module dependencies. + */ + +var EventEmitter = require('events').EventEmitter; +var util = require('util'); +var gcm = require('node-gcm'); +var _ = require('lodash'); + +/** + * Expose module. + */ + +module.exports = Sender; + +/** + * Create a new GCM sender. + * + * @param {object} options + * @param {string} options.apiKey + * @param {number} options.retries + */ + +function Sender(options) { + EventEmitter.call(this); + _.extend(this, _.defaults(options || {}, { + retries: 4 + })); +} + +util.inherits(Sender, EventEmitter); + +/** + * Send a notification. + * + * @param {object} data + * @see https://github.com/ToothlessGear/node-gcm + */ + +Sender.prototype.send = function (data) { + var sender = this; + sender.gcmSender = sender.gcmSender || sender.createGcmSender(); + + // Registration id can be string or array. + if (! _.isArray(data.registrationId)) data.registrationId = [data.registrationId]; + + // Create GCM message. + var message = new gcm.Message(_.omit(data, 'registrationId')); + + sender.gcmSender.send(message, data.registrationId, sender.retries, function (err, res) { + if (err) return _.each(data.registrationId, function (registrationId) { + sender.emit('transmissionError', err, message, registrationId); + }); + + _.each(res.results, function (result, index) { + if (result.error) + return sender.emit('transmissionError', result.error, message, data.registrationId[index]); + + if (result.registration_id) + sender.emit('updated', result, data.registrationId[index]); + + sender.emit('transmitted', result, message, data.registrationId[index]); + }); + }); +}; + +/** + * Create a new GCM sender. + * + * @returns {gcm.Sender} + */ + +Sender.prototype.createGcmSender = function () { + return new gcm.Sender(this.apiKey); +}; \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006600_broadcast-node.js b/pool/shard001/JavaScript/0006600_broadcast-node.js new file mode 100644 index 0000000000000000000000000000000000000000..00ceb826af40ba99b9f6423db1ac561a7211afa3 --- /dev/null +++ b/pool/shard001/JavaScript/0006600_broadcast-node.js @@ -0,0 +1,59 @@ +var readline = require('readline'); +// for real you will do require('webstomp-client') +var webstomp = require('../dist/webstomp'); +// you can use any WebSocket client library you want +// just carefully read for each one specificities +var WebSocket = require('ws'); + + + +var rl = readline.createInterface(process.stdin, process.stdout), + url = 'ws://localhost:15674/ws', + login = 'guest', password = 'guest', + options = {debug: false, protocols: webstomp.VERSIONS.supportedProtocols()}; + +var users = [ + { + name: 'user 1', + client: webstomp.over(new WebSocket(url), options) + }, + { + name: 'user 2', + client: webstomp.over(new WebSocket(url), options) + } +]; +var master = { + name: 'palpatine', + client: webstomp.over(new WebSocket(url), options) +}; + +function onMessage(user, msg) { + console.log('MESSAGE', user.name, msg.body); +} +function onError(user, err) { + console.log('DISCONNECTED', user.name, err); +} +function onConnect(user) { + console.log('CONNECTED', user.name); + user.client.subscribe('/topic/webstomp-chat-example', onMessage.bind(this, user)); +} +function onMasterConnect(master) { + rl.setPrompt('something to broadcast? > '); + rl.prompt(); + rl.on('line', function(line) { + master.client.send('/topic/webstomp-chat-example', line.trim()); + }); + rl.on('close', function() { + console.log('bye bye'); + master.client.disconnect(); + users.forEach(function(user) { + user.client.disconnect(); + }); + }); +} + +users.forEach(function(user) { + user.client.connect(login, password, onConnect.bind(this, user), onError.bind(this, user)); +}); + +master.client.connect(login, password, onMasterConnect.bind(this, master), onError.bind(this, master)); diff --git a/pool/shard001/JavaScript/0006602_getRemoteIdentities.js b/pool/shard001/JavaScript/0006602_getRemoteIdentities.js new file mode 100644 index 0000000000000000000000000000000000000000..79f1e8188d3f652c187a9a757b13c21afcebaaeb --- /dev/null +++ b/pool/shard001/JavaScript/0006602_getRemoteIdentities.js @@ -0,0 +1,16 @@ +import { requestRemoteIdentities } from '../../../store/modules/remote-identity'; + +export const getRemoteIdentities = () => async (dispatch, getState) => { + let remoteIdentityState = getState().remoteIdentity; + const { remoteIdentities, didInvalidate } = remoteIdentityState; + + if (remoteIdentities.length > 0 && !didInvalidate) { + return remoteIdentities.map(identityId => remoteIdentityState.remoteIdentitiesById[identityId]); + } + + await dispatch(requestRemoteIdentities()); + + remoteIdentityState = getState().remoteIdentity; + + return remoteIdentities.map(identityId => remoteIdentityState.remoteIdentitiesById[identityId]); +}; diff --git a/pool/shard001/JavaScript/0006606_type-none.js b/pool/shard001/JavaScript/0006606_type-none.js new file mode 100644 index 0000000000000000000000000000000000000000..fd67b04a44897828f861c88210d7133fcfb94ef1 --- /dev/null +++ b/pool/shard001/JavaScript/0006606_type-none.js @@ -0,0 +1,51 @@ +'use strict'; + +var TestRunner = require('test-runner'); +var cliArgs = require('../../'); +var a = require('core-assert'); + +var runner = new TestRunner(); + +var optionDefinitions = [{ name: 'one' }, { name: 'two' }]; + +runner.test('name: no argv values', function () { + var argv = []; + var result = cliArgs(optionDefinitions, argv); + a.deepStrictEqual(result, {}); +}); + +runner.test('name: just names, no values', function () { + var argv = ['--one', '--two']; + var result = cliArgs(optionDefinitions, argv); + a.deepStrictEqual(result, { + one: true, + two: true + }); +}); + +runner.test('name: just names, no values, unpassed value', function () { + var argv = ['--one', '--two']; + var result = cliArgs(optionDefinitions, argv); + a.deepStrictEqual(result, { + one: true, + two: true + }); +}); + +runner.test('name: just names, one value, one unpassed value', function () { + var argv = ['--one', 'one', '--two']; + var result = cliArgs(optionDefinitions, argv); + a.deepStrictEqual(result, { + one: 'one', + two: true + }); +}); + +runner.test('name: just names, two values', function () { + var argv = ['--one', 'one', '--two', 'two']; + var result = cliArgs(optionDefinitions, argv); + a.deepStrictEqual(result, { + one: 'one', + two: 'two' + }); +}); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006609_parser.js b/pool/shard001/JavaScript/0006609_parser.js new file mode 100644 index 0000000000000000000000000000000000000000..92aec0b8f607d8cfca63f899467b698189230cc6 --- /dev/null +++ b/pool/shard001/JavaScript/0006609_parser.js @@ -0,0 +1,197 @@ +'use strict'; + +var fs = require('fs'); + +var FILE_PATH = 'stories'; +var WRITE_PATH = 'generalstore/config'; +var KEYWORDS = { + level: true, + location: true, + background_image: true, + audio: true, + description: true +}; + +var KEYWORDS_GROUP = { + character: 'characters', + item: 'items' +}; + +var SEC_PROPERTY = /^\w+:\s/gi; + +/** + * Creates the parser. + * @constructor + */ +var Parser = function () { + this.resultJSON = { + level: 0, + location: false, + background_image: false, + audio: false, + description: false, + characters: {}, + items: {} + }; + this.secProperties = {}; + this.currLevel = 0; +}; + +/** + * Generates the content and writes to a JSON config file. + * @param {string} data File contents + * @param {function (err, resultJSON)} callback Returns JSON content for the + * level. + */ +Parser.prototype.processContent = function (data, callback) { + var self = this; + + self.resultJSON.characters = {}; + self.resultJSON.items = {}; + + var content = data.split(/\n|\r/gi); + + if (!content[content.length - 1].match(/\n|\r/)) { + content.push('\n'); + } + + for (var i = 0; i < content.length; i ++) { + var c = content[i].toString().trim(); + + try { + this.setProperty(c); + } catch (err) { + callback(err); + } + } + + fs.writeFile(this.writePath + '/level' + this.currLevel + '.json', + JSON.stringify(this.resultJSON, undefined, 4), function (err) { + if (err) { + callback(err); + } else { + callback(null, self.resultJSON); + self = null; + } + }); +}; + +/** + * Sets the properties for the level. + * @param {string} c Property name within level. + */ +Parser.prototype.setProperty = function (c) { + // primary properties + if (KEYWORDS[c] || KEYWORDS_GROUP[c]) { + this.currProperty = c; + + // secondary properties + } else if (c.match(SEC_PROPERTY)) { + var propArray = c.split(/:\s/); + + if (!isNaN(propArray[1])) { + propArray[1] = parseInt(propArray[1], 10); + + } else if (propArray[1] === 'false') { + propArray[1] = ''; + } + + this.secProperties[propArray[0]] = propArray[1]; + + // level content + } else if (c.length > 0) { + if (this.currProperty === 'level') { + this.currLevel = parseInt(c, 10); + } + + if (!isNaN(c)) { + c = parseInt(c, 10); + } + + if (c === 'false') { + c = ''; + } + + this.resultJSON[this.currProperty] = c; + + // line break + } else { + if (KEYWORDS_GROUP[this.currProperty]) { + if (!this.secProperties.name) { + throw new Error('Invalid secondary property.'); + } + + var propId = this.currLevel + '-' + this.secProperties.name; + + this.resultJSON[KEYWORDS_GROUP[this.currProperty]][propId] = this.secProperties; + } + + this.secProperties = {}; + this.currProperty = null; + } +}; + +/** + * Reads through and processes a file. + * @param {string} result Filename for the level. + * @param {function (err, json)} callback Returns JSON content for the + * level. + */ +Parser.prototype.processText = function (result, callback) { + var self = this; + + fs.readFile(self.filePath + '/' + result, 'utf8', function (err, data) { + if (err) { + callback(err); + + } else { + self.processContent(data, callback); + } + }); +}; + +/** + * Reads through the stories directory and generates each as a json file. + * @param {function (err, result)} callback Returns the complete list of JSON + * content for all files in the directory. + */ +exports.run = function (options, callback) { + var result = []; + var currFilePath = options.filePath || FILE_PATH; + var currWritePath = options.writePath || WRITE_PATH; + + fs.readdir(currFilePath, function (err, files) { + if (files.length < 1) { + return callback(new Error('No files found. Please create a story')); + } + + if (err) { + callback(err); + + } else { + var count = 0; + + files.filter(function (file) { + return file.substr(-4) === '.txt'; + + }).forEach(function (file) { + count = count + 1; + var parser = new Parser(); + parser.filePath = currFilePath; + parser.writePath = currWritePath; + + parser.processText(file, function (err, f) { + if (err) { + callback(err); + + } else { + result.push(f); + if (result.length === count) { + callback(null, result); + } + } + }); + }); + } + }); +}; diff --git a/pool/shard001/JavaScript/0006614_webpack.config.js b/pool/shard001/JavaScript/0006614_webpack.config.js new file mode 100644 index 0000000000000000000000000000000000000000..f331ee9842eee76458c9eb3715034bb9101e7308 --- /dev/null +++ b/pool/shard001/JavaScript/0006614_webpack.config.js @@ -0,0 +1,193 @@ +/** **************************************************************************** + * A common webpack configuration. + **************************************************************************** */ +require('dotenv').config({ silent: true }); // get local environment variables from .env +const checkEnv = require('@flumens/has-env'); + +checkEnv({ + warn: ['APP_TRAINING', 'APP_MANUAL_TESTING', 'APP_INDICIA_API_HOST'], + required: [ + 'APP_OS_MAP_KEY', + 'APP_MAPBOX_MAP_KEY', + 'APP_SENTRY_KEY', + 'APP_INDICIA_API_KEY', + ], +}); + +const path = require('path'); +const webpack = require('webpack'); +const autoprefixer = require('autoprefixer'); +const HtmlWebpackPlugin = require('html-webpack-plugin'); +const MiniCssExtractPlugin = require('mini-css-extract-plugin'); + +const pkg = require('./package.json'); + +const ROOT_DIR = path.resolve(__dirname, './'); +const DIST_DIR = path.resolve(ROOT_DIR, 'build'); + +const isDevEnv = process.env.NODE_ENV === 'development'; +const isProdEnv = process.env.NODE_ENV === 'production'; +const isTestEnv = process.env.NODE_ENV === 'test'; + +const config = { + mode: process.env.NODE_ENV === 'production' ? 'production' : 'development', + entry: ['index.js', 'vendor.js'], + devtool: 'source-map', + target: 'web', + + output: { + path: DIST_DIR, + filename: '[name].js', + publicPath: '/', + }, + resolve: { + modules: [ + path.resolve(ROOT_DIR, './node_modules/'), + path.resolve(ROOT_DIR, './src/'), + path.resolve(ROOT_DIR, './src/common/vendor'), + ], + alias: { + Lib: 'common/Lib', + Components: 'common/Components', + config: 'common/config/config', + helpers: 'common/helpers', + saved_samples: 'common/saved_samples', + sample: 'common/models/sample', + occurrence: 'common/models/occurrence', + app_model: 'common/models/app_model', + user_model: 'common/models/user_model', + model_factory: 'common/models/model_factory', + }, + }, + module: { + rules: [ + { + test: /^((?!data\.).)*\.js$/, + exclude: /(node_modules|vendor(?!\.js))/, + loader: 'babel-loader', + }, + { + test: /(\.png)|(\.svg)|(\.jpg)/, + loader: 'file-loader?name=images/[name].[ext]', + }, + { + test: /(\.woff)|(\.ttf)/, + loader: 'file-loader?name=font/[name].[ext]', + }, + { + test: /\.s?[c|a]ss$/, + use: [ + 'style-loader', + MiniCssExtractPlugin.loader, + { + loader: 'string-replace-loader', + options: { + search: './default-skin.svg', + replace: '/images/default-skin.svg', + flags: 'g', + }, + }, + 'css-loader?-url', + { + loader: 'postcss-loader', + options: { + sourceMap: true, + plugins() { + return [autoprefixer('last 2 version')]; + }, + }, + }, + `sass-loader`, + ], + }, + ], + }, + + optimization: { + runtimeChunk: false, + splitChunks: { + cacheGroups: { + commons: { + test: /[\\/]node_modules[\\/]/, + name: 'vendors', + chunks: 'all', + }, + }, + }, + }, + + // ignore file sizes since cordova is localhost + performance: { + maxEntrypointSize: 10000000, + maxAssetSize: 10000000, + }, + + plugins: [ + // Extract environmental variables and replace references with values in the code + new webpack.DefinePlugin({ + __ENV__: JSON.stringify(process.env.NODE_ENV || 'development'), + __DEV__: isDevEnv, + __PROD__: isProdEnv, + __TEST__: isTestEnv, + + 'process.env': { + // package.json variables + APP_BUILD: JSON.stringify( + process.env.TRAVIS_BUILD_ID || pkg.build || new Date().getTime() + ), + APP_NAME: JSON.stringify(pkg.name), // no need to be an env value + APP_VERSION: JSON.stringify(pkg.version), // no need to be an env value + + // mandatory env. variables + APP_INDICIA_API_KEY: JSON.stringify( + process.env.APP_INDICIA_API_KEY || '' + ), + APP_OS_MAP_KEY: JSON.stringify(process.env.APP_OS_MAP_KEY || ''), + APP_MAPBOX_MAP_KEY: JSON.stringify( + process.env.APP_MAPBOX_MAP_KEY || '' + ), + + // compulsory env. variables + APP_INDICIA_API_HOST: JSON.stringify( + process.env.APP_INDICIA_API_HOST || '' + ), + APP_TRAINING: process.env.APP_TRAINING || false, + APP_SCREENSHOTS: process.env.APP_SCREENSHOTS || false, + APP_EXPERIMENTS: process.env.APP_EXPERIMENTS || false, + APP_SENTRY_KEY: JSON.stringify(process.env.APP_SENTRY_KEY || ''), + APP_GA: JSON.stringify(process.env.APP_GA || false), + + // https://github.com/webpack-contrib/karma-webpack/issues/316 + SAUCE_LABS: JSON.stringify(process.env.SAUCE_LABS), + }, + }), + new MiniCssExtractPlugin({ + filename: 'style.css', + }), + new HtmlWebpackPlugin({ + template: 'src/index.html', + sourceMap: true, + // https://github.com/marcelklehr/toposort/issues/20 + chunksSortMode: 'none', + }), + new webpack.NamedModulesPlugin(), + new webpack.optimize.OccurrenceOrderPlugin(), + ], + stats: { + children: false, + }, + cache: true, + devServer: { + historyApiFallback: true, + }, +}; + +if (process.env.APP_MANUAL_TESTING) { + config.entry.push('./test/manual-test-utils.js'); +} + +if (process.env.APP_SCREENSHOTS) { + config.entry.push('./other/cordova/screenshots-setup.js'); +} + +module.exports = config; diff --git a/pool/shard001/JavaScript/0006616_practice3.1.js b/pool/shard001/JavaScript/0006616_practice3.1.js new file mode 100644 index 0000000000000000000000000000000000000000..1d4cb94a622b731de2ef255c2d0188af2f5b458d --- /dev/null +++ b/pool/shard001/JavaScript/0006616_practice3.1.js @@ -0,0 +1,14 @@ +function enterNumberFst(){ +var n = document.getElementById("enterNumber").value +//----以下兩行為變數名稱設定------------------------------------------------------------------------- +var num = n; +var sum = 0; +//-----題目:計算從1到輸入數字的總和(用for的方法)----------------------------------------------------- +for(var i = 1; i <= num; i = i + 1) +{ + sum = sum + i ; +} +//------------------------------------------------------------------------------------------------- +var c = document.getElementById("Number"); +c.innerHTML = "Result:
      The sum from 1 to "+Number(n)+" is "+Number(sum) +} \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006617_temperature.js b/pool/shard001/JavaScript/0006617_temperature.js new file mode 100644 index 0000000000000000000000000000000000000000..56297e3b42368d46a2b65a0d0da423e91eaf6c06 --- /dev/null +++ b/pool/shard001/JavaScript/0006617_temperature.js @@ -0,0 +1,27 @@ +var b = require('bonescript'); +var port = '/dev/i2c-2'; +var addr = 0x18; +var COM_MANIFACTURER = 0x06; +var COM_DEVICE = 0x07; +var COM_AMBIENT_TEMP = 0x05; + +function setupTemperature(){ + if(!b.i2cOpen( port, addr)) return false; + if(b.i2cReadBytes(port, COM_MANIFACTURER, 2).toString("hex") != "0054") return false; + if(b.i2cReadBytes(port, COM_DEVICE, 2) .toString("hex") != "0400") return false; + console.log("Temperature sensor running") + return true; +} +function checkTemperature(){ + var t = b.i2cReadBytes(port, COM_AMBIENT_TEMP, 2).readInt16BE(0); + var temp = (t & 0x0fff) / 16; + console.log(temp); + console.log(t & 0x1000) + if (t & 0x1000 <0) temp -= 256; + + console.log("temperature: " + temp); +} + +if(setupTemperature()){ + setInterval(checkTemperature, 1000); +} diff --git a/pool/shard001/JavaScript/0006620_Optimistic.js b/pool/shard001/JavaScript/0006620_Optimistic.js new file mode 100644 index 0000000000000000000000000000000000000000..628d50adc248edec080e20443c89c124438d8780 --- /dev/null +++ b/pool/shard001/JavaScript/0006620_Optimistic.js @@ -0,0 +1,104 @@ +import React from 'react'; +import createReactClass from 'create-react-class'; +import PropTypes from 'prop-types'; +import _ from 'lodash'; +import { result as _result } from 'lore-utils'; +import { SchemaForm } from 'lore-react-forms'; +import { CardTitle } from 'material-ui'; + +export default createReactClass({ + displayName: 'Optimistic', + + propTypes: { + model: PropTypes.object.isRequired, + data: PropTypes.object, + validators: PropTypes.oneOfType([ + PropTypes.func, + PropTypes.object + ]), + onChange: PropTypes.func, + onSubmit: PropTypes.func, + callbacks: PropTypes.object, + schema: PropTypes.object.isRequired, + fieldMap: PropTypes.object.isRequired, + actionMap: PropTypes.object.isRequired, + fields: PropTypes.array.isRequired, + actions: PropTypes.array.isRequired + }, + + getInitialState: function() { + const { model } = this.props; + + return { + data: _.merge({}, model.data) + }; + }, + + request: function(data) { + const { modelName } = this.props; + const { model, request } = this.props; + return request ? request(data) : lore.actions[modelName].destroy(model).payload; + }, + + onSubmit: function() { + const { data } = this.state; + this.request(data); + this.onCancel(); + }, + + onCancel: function(data) { + this.props.onCancel(data); + }, + + onChange: function(name, value) { + const nextData = _.merge({}, this.state.data); + nextData[name] = value; + this.setState({ + data: nextData + }); + }, + + getValidators: function(data) { + const { validators } = this.props; + return _result(validators || {}, data); + }, + + render: function() { + const { modelName } = this.props; + const { + title = `Delete ${_.capitalize(modelName)}`, + description = '', + schema, + fieldMap, + actionMap, + fields, + actions + } = this.props; + const { data } = this.state; + const validators = this.getValidators(data); + + return ( +
      + + +
      + ); + } + +}); diff --git a/pool/shard001/JavaScript/0006622_index.js b/pool/shard001/JavaScript/0006622_index.js new file mode 100644 index 0000000000000000000000000000000000000000..a4a297898a760c16cf5f35570cfcb568d34d88dc --- /dev/null +++ b/pool/shard001/JavaScript/0006622_index.js @@ -0,0 +1,111 @@ +'use strict'; + +var consts = require('../../constants'); + +function configure (app, wares, ctx) { + var express = require('express'), + api = express.Router( ); + + // invoke common middleware + api.use(wares.sendJSONStatus); + // text body types get handled as raw buffer stream + api.use(wares.bodyParser.raw( )); + // json body types get handled as parsed json + api.use(wares.bodyParser.json({ + limit: 1048576 + , extended: true + })); + // also support url-encoded content-type + api.use(wares.bodyParser.urlencoded({ extended: true })); + + api.use(ctx.authorization.isPermitted('api:profile:read')); + + + /** + * @function query_models + * Perform the standard query logic, translating API parameters into mongo + * db queries in a fairly regimented manner. + * This middleware executes the query, returning the results as JSON + */ + function query_models (req, res, next) { + var query = req.query; + + // If "?count=" is present, use that number to decide how many to return. + if (!query.count) { + query.count = consts.PROFILES_DEFAULT_COUNT; + } + + // perform the query + ctx.profile.list_query(query, function payload(err, profiles) { + return res.json(profiles); + }); + } + + // List profiles available + api.get('/profiles/', query_models); + + // List profiles available + api.get('/profile/', function(req, res) { + const limit = req.query && req.query.count ? Number(req.query.count) : consts.PROFILES_DEFAULT_COUNT; + ctx.profile.list(function (err, attribute) { + return res.json(attribute); + }, limit); + }); + + // List current active record (in current state LAST record is current active) + api.get('/profile/current', function(req, res) { + ctx.profile.last( function(err, records) { + return res.json(records.length > 0 ? records[0] : null); + }); + }); + + function config_authed (app, api, wares, ctx) { + + // create new record + api.post('/profile/', ctx.authorization.isPermitted('api:profile:create'), function(req, res) { + var data = req.body; + ctx.purifier.purifyObject(data); + ctx.profile.create(data, function (err, created) { + if (err) { + res.sendJSONStatus(res, consts.HTTP_INTERNAL_ERROR, 'Mongo Error', err); + console.log('Error creating profile'); + console.log(err); + } else { + res.json(created.ops); + console.log('Profile created', created); + } + }); + }); + + // update record + api.put('/profile/', ctx.authorization.isPermitted('api:profile:update'), function(req, res) { + var data = req.body; + ctx.profile.save(data, function (err, created) { + if (err) { + res.sendJSONStatus(res, consts.HTTP_INTERNAL_ERROR, 'Mongo Error', err); + console.log('Error saving profile'); + console.log(err); + } else { + res.json(created); + console.log('Profile saved', created); + } + + }); + }); + + api.delete('/profile/:_id', ctx.authorization.isPermitted('api:profile:delete'), function(req, res) { + ctx.profile.remove(req.params._id, function ( ) { + res.json({ }); + }); + }); + } + + if (app.enabled('api')) { + config_authed(app, api, wares, ctx); + } + + return api; +} + +module.exports = configure; + diff --git a/pool/shard001/JavaScript/0006624_test.js b/pool/shard001/JavaScript/0006624_test.js new file mode 100644 index 0000000000000000000000000000000000000000..1b00833bbc00d6f635bd313a81fbf2193a4e8ae9 --- /dev/null +++ b/pool/shard001/JavaScript/0006624_test.js @@ -0,0 +1,52 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2020 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var proxyquire = require( 'proxyquire' ); +var IS_NODE = require( '@stdlib/assert/is-node' ); +var EXEC_PATH = require( './../lib' ); + + +// TESTS // + +tape( 'main export is either a string or `null`', function test( t ) { + t.ok( true, __filename ); + t.equal( typeof EXEC_PATH === 'string' || EXEC_PATH === null, true, 'main export is either a string or `null`' ); + t.end(); +}); + +tape( 'if running in a Node.js process, the main export is a string; otherwise, the export is equal to `null`.', function test( t ) { + if ( IS_NODE ) { + t.equal( typeof EXEC_PATH, 'string', 'exports a string' ); + } else { + t.equal( EXEC_PATH, null, 'exports null' ); + } + t.end(); +}); + +tape( 'if not running in a Node.js process, the main export is `null`', function test( t ) { + var EXEC_PATH = proxyquire( './../lib', { + '@stdlib/assert/is-node': false + }); + t.equal( EXEC_PATH, null, 'exports null' ); + t.end(); +}); diff --git a/pool/shard001/JavaScript/0006630_querystream.js b/pool/shard001/JavaScript/0006630_querystream.js new file mode 100644 index 0000000000000000000000000000000000000000..064bd7a31ec36b1e577dc0a2b15757f7f772d1e8 --- /dev/null +++ b/pool/shard001/JavaScript/0006630_querystream.js @@ -0,0 +1,319 @@ + +/*! + * Module dependencies. + */ + +var Stream = require('stream').Stream +var utils = require('./utils') +var K = function(k){ return k } + +/** + * Provides a Node.js 0.8 style [ReadStream](http://nodejs.org/docs/v0.8.21/api/stream.html#stream_readable_stream) interface for Queries. + * + * var stream = Model.find().stream(); + * + * stream.on('data', function (doc) { + * // do something with the mongoose document + * }).on('error', function (err) { + * // handle the error + * }).on('close', function () { + * // the stream is closed + * }); + * + * + * The stream interface allows us to simply "plug-in" to other _Node.js 0.8_ style write streams. + * + * Model.where('created').gte(twoWeeksAgo).stream().pipe(writeStream); + * + * _NOTE: plugging into an HTTP response will *not* work out of the box. Those streams expect only strings or buffers to be emitted, so first formatting our documents as strings/buffers is necessary._ + * + * _NOTE: these streams are Node.js 0.8 style read streams which differ from Node.js 0.10 style. Node.js 0.10 streams are not well tested yet and are not guaranteed to work._ + * + * @param {Query} query + * @inherits NodeJS Stream http://nodejs.org/docs/v0.8.21/api/stream.html#stream_readable_stream + * @event `data`: emits a single Mongoose document + * @event `error`: emits when an error occurs during streaming. This will emit _before_ the `close` event. + * @event `close`: emits when the stream reaches the end of the cursor or an error occurs, or the stream is manually `destroy`ed. After this event, no more events are emitted. + * @api public + */ + +function QueryStream (query, options) { + Stream.call(this); + + this.query = query; + this.readable = true; + this.paused = false; + this._cursor = null; + this._destroyed = null; + this._fields = null; + this._buffer = null; + this._inline = T_INIT; + this._running = false; + this._transform = options && 'function' == typeof options.transform + ? options.transform + : K; + + // give time to hook up events + var self = this; + process.nextTick(function () { + self._init(); + }); +} + +/*! + * Inherit from Stream + */ + +QueryStream.prototype.__proto__ = Stream.prototype; + +/** + * Flag stating whether or not this stream is readable. + * + * @property readable + * @api public + */ + +QueryStream.prototype.readable; + +/** + * Flag stating whether or not this stream is paused. + * + * @property paused + * @api public + */ + +QueryStream.prototype.paused; + +// trampoline flags +var T_INIT = 0; +var T_IDLE = 1; +var T_CONT = 2; + +/** + * Initializes the query. + * + * @api private + */ + +QueryStream.prototype._init = function () { + if (this._destroyed) return; + + var query = this.query + , model = query.model + , options = query._optionsForExec(model) + , self = this + + try { + query.cast(model); + } catch (err) { + return self.destroy(err); + } + + self._fields = utils.clone(query._fields); + options.fields = query._castFields(self._fields); + + model.collection.find(query._conditions, options, function (err, cursor) { + if (err) return self.destroy(err); + self._cursor = cursor; + self._next(); + }); +} + +/** + * Trampoline for pulling the next doc from cursor. + * + * @see QueryStream#__next #querystream_QueryStream-__next + * @api private + */ + +QueryStream.prototype._next = function _next () { + if (this.paused || this._destroyed) { + return this._running = false; + } + + this._running = true; + + if (this._buffer && this._buffer.length) { + var arg; + while (!this.paused && !this._destroyed && (arg = this._buffer.shift())) { + this._onNextObject.apply(this, arg); + } + } + + // avoid stack overflows with large result sets. + // trampoline instead of recursion. + while (this.__next()) {} +} + +/** + * Pulls the next doc from the cursor. + * + * @see QueryStream#_next #querystream_QueryStream-_next + * @api private + */ + +QueryStream.prototype.__next = function () { + if (this.paused || this._destroyed) + return this._running = false; + + var self = this; + self._inline = T_INIT; + + self._cursor.nextObject(function cursorcb (err, doc) { + self._onNextObject(err, doc); + }); + + // if onNextObject() was already called in this tick + // return ourselves to the trampoline. + if (T_CONT === this._inline) { + return true; + } else { + // onNextObject() hasn't fired yet. tell onNextObject + // that its ok to call _next b/c we are not within + // the trampoline anymore. + this._inline = T_IDLE; + } +} + +/** + * Transforms raw `doc`s returned from the cursor into a model instance. + * + * @param {Error|null} err + * @param {Object} doc + * @api private + */ + +QueryStream.prototype._onNextObject = function _onNextObject (err, doc) { + if (this._destroyed) return; + + if (this.paused) { + this._buffer || (this._buffer = []); + this._buffer.push([err, doc]); + return this._running = false; + } + + if (err) return this.destroy(err); + + // when doc is null we hit the end of the cursor + if (!doc) { + this.emit('end'); + return this.destroy(); + } + + if (this.query.options && true === this.query.options.lean) { + this.emit('data', this._transform(doc)); + + // trampoline management + if (T_IDLE === this._inline) { + // no longer in trampoline. restart it. + this._next(); + } else { + // in a trampoline. tell __next that its + // ok to continue jumping. + this._inline = T_CONT; + } + return; + } + + var instance = new this.query.model(undefined, this._fields, true); + + var self = this; + instance.init(doc, this.query, function (err) { + if (err) return self.destroy(err); + self.emit('data', self._transform(instance)); + + // trampoline management + if (T_IDLE === self._inline) { + // no longer in trampoline. restart it. + self._next(); + } else + // in a trampoline. tell __next that its + // ok to continue jumping. + self._inline = T_CONT; + }); +} + +/** + * Pauses this stream. + * + * @api public + */ + +QueryStream.prototype.pause = function () { + this.paused = true; +} + +/** + * Resumes this stream. + * + * @api public + */ + +QueryStream.prototype.resume = function () { + this.paused = false; + + if (!this._cursor) { + // cannot start if not initialized + return; + } + + // are we within the trampoline? + if (T_INIT === this._inline) { + return; + } + + if (!this._running) { + // outside QueryStream control, need manual restart + return this._next(); + } +} + +/** + * Destroys the stream, closing the underlying cursor. No more events will be emitted. + * + * @param {Error} [err] + * @api public + */ + +QueryStream.prototype.destroy = function (err) { + if (this._destroyed) return; + this._destroyed = true; + this._running = false; + this.readable = false; + + if (this._cursor) { + this._cursor.close(); + } + + if (err) { + this.emit('error', err); + } + + this.emit('close'); +} + +/** + * Pipes this query stream into another stream. This method is inherited from NodeJS Streams. + * + * ####Example: + * + * query.stream().pipe(writeStream [, options]) + * + * This could be particularily useful if you are, for example, setting up an API for a service and want to stream out the docs based on some criteria. We could first pipe the QueryStream into a sort of filter that formats the stream as an array before passing on the document to an http response. + * + * var format = new ArrayFormatter; + * Events.find().stream().pipe(format).pipe(res); + * + * As long as ArrayFormat implements the WriteStream API we can stream large formatted result sets out to the client. See this [gist](https://gist.github.com/1403797) for a hacked example. + * + * @method pipe + * @memberOf QueryStream + * @see NodeJS http://nodejs.org/api/stream.html + * @api public + */ + +/*! + * Module exports + */ + +module.exports = exports = QueryStream; diff --git a/pool/shard001/JavaScript/0006633_soap-action-schedule.js b/pool/shard001/JavaScript/0006633_soap-action-schedule.js new file mode 100644 index 0000000000000000000000000000000000000000..34fa0d006cf1c4399a3216d4621421b9fdcea0c7 --- /dev/null +++ b/pool/shard001/JavaScript/0006633_soap-action-schedule.js @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2018, salesforce.com, inc. + * All rights reserved. + * Licensed under the BSD 3-Clause license. + * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause + */ + +'use strict'; + +var assert = require('assert'); +var proxyquire = require('proxyquire'); +var sinon = require('sinon'); + +describe('SOAP Action - schedule', function() { + var FuelSoap; + var soapRequestSpy; + var parsedOptions = { parsedOptions: true }; + var simpleVerifyTestCases = [ + { property: 'action', expected: 'Schedule' } + , { property: 'key', expected: 'ScheduleResponseMsg' } + , { property: 'retry', expected: true } + , { property: 'reqOptions', expected: parsedOptions } + ]; + + var exampleSchedule = { + Recurrence: { + $: {'xsi:type': 'MinutelyRecurrence'}, + MinutelyRecurrencePatternType: 'Interval', + MinuteInterval: '10' + }, + RecurrenceType: 'Minutely', + RecurrenceRangeType: 'EndAfter', + StartDateTime: '2019-04-10T10:10:00.046+01:00', + Occurrences: '999999' + }; + var exampleInteractions =[ + { + Interaction: { + ObjectID: '1234' + } + } + ]; + + beforeEach(function() { + FuelSoap = proxyquire('../../lib/fuel-soap', { + './helpers': { + parseReqOptions: function() { return parsedOptions; } + } + }); + soapRequestSpy = sinon.stub(FuelSoap.prototype, 'soapRequest'); + }); + + afterEach(function() { + FuelSoap.prototype.soapRequest.restore(); + }); + simpleVerifyTestCases.forEach(function(testCase) { + it('should call soapRequest with correct ' + testCase.property, function() { + // Act + FuelSoap.prototype.schedule( + 'Test', + exampleSchedule, + exampleInteractions, + 'start', + { options: true }, + function() {}); + // Assert + assert.equal(soapRequestSpy.args[0][0][testCase.property], testCase.expected); + }); + }); + it('should pass correct body to soapRequest', function() { + + // Act + FuelSoap.prototype.schedule('Test', exampleSchedule, exampleInteractions,'start',{ options: true } , function() {}); + // Assert + var actualObj = soapRequestSpy.args[0][0].req; + assert.equal(actualObj.ScheduleRequestMsg.Schedule, exampleSchedule); + assert.equal(actualObj.ScheduleRequestMsg.Interactions, exampleInteractions); + assert.ok(!actualObj.ScheduleRequestMsg.Options.QueryAllAccounts); + }); + + it('should pass callback to soapRequest when options', function() { + // Arrange + var sampleCallback = sinon.spy(); + + // Act + FuelSoap.prototype.schedule('Test', exampleSchedule, exampleInteractions,'start', { options: true }, sampleCallback); + + // Assert + assert.ok(soapRequestSpy.calledWith(sinon.match.object, sampleCallback)); + }); + + it('should add QueryAllAccounts to body when option passed', function() { + // Arrange + var sampleOptions = { queryAllAccounts: true }; + + // Act + FuelSoap.prototype.schedule('Test', exampleSchedule, exampleInteractions,'start',sampleOptions , function() {}); + + // Assert + var actualObj = soapRequestSpy.args[0][0].req; + assert.ok(actualObj.ScheduleRequestMsg.Options.QueryAllAccounts); + }); +}); diff --git a/pool/shard001/JavaScript/0006638_stream.js b/pool/shard001/JavaScript/0006638_stream.js new file mode 100644 index 0000000000000000000000000000000000000000..74f3099e6534ae1a4b368cb3fbb8ae01e6806bf8 --- /dev/null +++ b/pool/shard001/JavaScript/0006638_stream.js @@ -0,0 +1,50 @@ +'use strict'; +const assert = require('assert'); +const plugins = require('../../plugins'); +const config = require('../config'); +const fs = require('fs'); +const path = require('path'); + +const imageController = plugins.getFirst('image-controller'); +if (!imageController) { + throw new Error('Expected at least one image controller!'); +} + +/** + * A simplified controller that does not assume we're streaming an image but supports HTTP 206 + * + * @param req + * @param res + * @param next + */ +exports.stream = function (req, res, next) { + const collection = req.params.collection; + const id = req.params.id; + + let size = 'original'; + const option = config.downloadOptions[size]; + + // The request against the backend system. + var proxyRequest; + const range = req.headers.range; + if (range) { + proxyRequest = imageController.proxyDownload(collection + '/' + id, size, range); + } else { + proxyRequest = imageController.proxyDownload(collection + '/' + id, size); + } + + proxyRequest + .on('error', function (error) { + // We can't assume that it's ok to reply with eg. an error-image, so we + // just close the connection. + res.end(); + }) + .on('response', function (response) { + // Handle normal GET as well as partials. + if (response.statusCode === 200 || response.statusCode === 206) { + proxyRequest.pipe(res); + } else { + res.status(500).send('Error occured while processing request.'); + } + }); +}; diff --git a/pool/shard001/JavaScript/0006640_test-templated-output.js b/pool/shard001/JavaScript/0006640_test-templated-output.js new file mode 100644 index 0000000000000000000000000000000000000000..076585d35ff17cc3d99f04e23635a84c91852595 --- /dev/null +++ b/pool/shard001/JavaScript/0006640_test-templated-output.js @@ -0,0 +1,40 @@ +import { default as React } from "react"; + +import { template, render } from "../src"; +import { alternateColor } from "./_util"; + + +let someState = "STATE BEFORE RENDERING"; +const getSomeState = () => someState; + + +const MyComponent = ({ prop }) => { + return ( +
      + + { "other things" } + +
      + ); +}; + +const Child = () => { + someState = "STATE AFTER RENDERING"; + return
      ; +}; + +const getTemplateRenderer = componentRenderer => template` + + + ${ getSomeState } + ${ componentRenderer } + ${ getSomeState } + + +`; + +const componentRenderer = render(); +const htmlRenderer = getTemplateRenderer(componentRenderer); +htmlRenderer + .toStream() + .on("data", segment => process.stdout.write(alternateColor(segment))); diff --git a/pool/shard001/JavaScript/0006642_validate_config.js b/pool/shard001/JavaScript/0006642_validate_config.js new file mode 100644 index 0000000000000000000000000000000000000000..9c0ae1bf98adc3d96bc5692e845601e6ca467869 --- /dev/null +++ b/pool/shard001/JavaScript/0006642_validate_config.js @@ -0,0 +1,75 @@ +define('js/core/element/view/validate_config', [ + 'backbone', + 'js/core/element/view/base_element', + 'text!js/core/element/template/validate_config.tpl' +], function(Backbone, BaseElementView, Tpl) { + var HtmlView = BaseElementView.extend({ + events: { + "change .type": "_typeChoose", + }, + initialize: function(options, eleBean, attributes, eves, editAble) { + var t = this; + BaseElementView.prototype.initialize.apply(t, arguments); + this.defaultAttributes = {} + this.attributes = $.extend({}, this.defaultClientAttribute, attributes); + t.render(); + }, + render: function() { + var t = this; + this.$el.html(tpl(Tpl, { + eleBean: this.eleBean, + attributes: this.attributes, + editAble: this.editAble + })); + return this; + }, + supportAttribute: function() { + return []; + }, + supportEventNames: function() { + return []; + }, + supportServerEventNames: function() { + return []; + }, + _typeChoose: function() { + var t = this; + var type = t.$el.find(".type").val(); + if (type == 'number') { + t.$el.find(".digitContainer").removeClass("hidden"); + } else { + t.$el.find(".digitContainer").addClass("hidden"); + } + }, + + setAttribute: function(attributeName, attributeValue) { + var t = this; + t.attributes[attributeName] = attributeValue; + }, + setValue: function(value) { + var t = this; + t.$el.find(".type").val(""); + t.$el.find(".digit").val("0"); + if (value && typeof value == 'string' && value.length > 0) { + value = eval("(" + value + ")"); + var type = value['type']; + t.$el.find(".type").val(type); + if (type == 'number') { + t.$el.find(".digit").val(value['digit']); + } + t._typeChoose(); + } + }, + getValue: function() { + var t = this; + var type = t.$el.find(".type").val(); + var value = {}; + value['type'] = type; + if (type == 'number') { + value['digit'] = t.$el.find(".digit").val(); + } + return JSON.stringify(value); + } + }); + return HtmlView; +}); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006645_037-add-company-founder.js b/pool/shard001/JavaScript/0006645_037-add-company-founder.js new file mode 100644 index 0000000000000000000000000000000000000000..269fe0abc1c64f4fb8e3f8b59456355bdb6f52e9 --- /dev/null +++ b/pool/shard001/JavaScript/0006645_037-add-company-founder.js @@ -0,0 +1,23 @@ +import { defineMigration } from '/server/imports/utils/defineMigration'; +import { executeBulksSync } from '/server/imports/utils/executeBulksSync'; +import { dbCompanies } from '/db/dbCompanies'; +import { dbLog } from '/db/dbLog'; +import { dbFoundations } from '/db/dbFoundations'; + +defineMigration({ + version: 37, + name: 'add company founder', + up() { + const companyBulk = dbCompanies.rawCollection().initializeUnorderedBulkOp(); + const foundationBulk = dbFoundations.rawCollection().initializeUnorderedBulkOp(); + + dbLog.find({ logType: '創立公司' }).forEach(({ companyId, userId }) => { + const founder = userId[0]; + + companyBulk.find({ _id: companyId }).updateOne({ $set: { founder } }); + foundationBulk.find({ _id: companyId }).updateOne({ $set: { founder } }); + }); + + executeBulksSync(companyBulk, foundationBulk); + } +}); diff --git a/pool/shard001/JavaScript/0006646_photos.server.controller.js b/pool/shard001/JavaScript/0006646_photos.server.controller.js new file mode 100644 index 0000000000000000000000000000000000000000..3feb5c371db752e8b4f1351db1af9caed6e39fba --- /dev/null +++ b/pool/shard001/JavaScript/0006646_photos.server.controller.js @@ -0,0 +1,105 @@ +'use strict'; + +/** + * Module dependencies. + */ +var mongoose = require('mongoose'), + errorHandler = require('./errors'), + Photo = mongoose.model('Photo'), + _ = require('lodash'); + +/** + * Create a Photo + */ +exports.create = function(req, res) { + var photo = new Photo(req.body); + photo.user = req.user; + + photo.save(function(err) { + if (err) { + return res.status(400).send({ + message: errorHandler.getErrorMessage(err) + }); + } else { + res.jsonp(photo); + } + }); +}; + +/** + * Show the current Photo + */ +exports.read = function(req, res) { + res.jsonp(req.photo); +}; + +/** + * Update a Photo + */ +exports.update = function(req, res) { + var photo = req.photo ; + + photo = _.extend(photo , req.body); + + photo.save(function(err) { + if (err) { + return res.status(400).send({ + message: errorHandler.getErrorMessage(err) + }); + } else { + res.jsonp(photo); + } + }); +}; + +/** + * Delete an Photo + */ +exports.delete = function(req, res) { + var photo = req.photo ; + + photo.remove(function(err) { + if (err) { + return res.status(400).send({ + message: errorHandler.getErrorMessage(err) + }); + } else { + res.jsonp(photo); + } + }); +}; + +/** + * List of Photos + */ +exports.list = function(req, res) { Photo.find().sort('-created').populate('user', 'displayName').exec(function(err, photos) { + if (err) { + return res.status(400).send({ + message: errorHandler.getErrorMessage(err) + }); + } else { + res.jsonp(photos); + } + }); +}; + +/** + * Photo middleware + */ +exports.photoByID = function(req, res, next, id) { Photo.findById(id).populate('user', 'displayName').exec(function(err, photo) { + if (err) return next(err); + if (! photo) return next(new Error('Failed to load Photo ' + id)); + req.photo = photo ; + next(); + }); +}; + +/** + * Photo authorization middleware + */ +exports.hasAuthorization = function(req, res, next) { + if (req.photo.user.id !== req.user.id) { + return res.status(403).send('User is not authorized'); + } + next(); +}; \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006648_parseString.js b/pool/shard001/JavaScript/0006648_parseString.js new file mode 100644 index 0000000000000000000000000000000000000000..6191ad3c7756a5f893f74dfbee952aa8e1357843 --- /dev/null +++ b/pool/shard001/JavaScript/0006648_parseString.js @@ -0,0 +1,11 @@ +function parseString(resource){ + if(resource.indexOf('{') === 0 && resource.lastIndexOf('}') === resource.length - 1){ + resource = JSON.parse(resource.replace(/,/g, '","').replace(/:(?!\/\/)/g, '":"').replace(/\{/, '{"').replace(/\}/, '"}')); + } else if(resource.indexOf('[') === 0 && resource.lastIndexOf(']') === resource.length - 1){ + resource = JSON.parse(resource.replace(/,/g, '","').replace(/\[/g, '["').replace(/\]/g, '"]')); + } + + return resource; +} + +module.exports = parseString; diff --git a/pool/shard001/JavaScript/0006649_mv-image-selector.js b/pool/shard001/JavaScript/0006649_mv-image-selector.js new file mode 100644 index 0000000000000000000000000000000000000000..a9ae1e18ba630217f452745a1465670508730cfe --- /dev/null +++ b/pool/shard001/JavaScript/0006649_mv-image-selector.js @@ -0,0 +1,100 @@ +(function ($) { + 'use strict'; + + + var frame, + buttons, + container = $('#mgjp_mv_ir_wrap'), + preview = $('#mgjp_mv_ir_preview'), + input = $('#mgjp_mv_ir_id'), + select_btn = $('

      ' + mgjp_mv_options_media.ir_select_btn + '

      '), + restore_btn = $('

      ' + mgjp_mv_options_media.ir_restore_btn + '

      '); + + + + buttons = [ select_btn ]; + if (0 < input.val()) + buttons = [ select_btn.children().text(mgjp_mv_options_media.ir_select_btn2).parent() ]; + if (mgjp_mv_options_media.ir_default !== input.val()) + buttons.push(restore_btn); + + + + container + + // append the controls + .append(buttons) + + + // register the media frame creator callback + .on('click', '#mgjp_mv_ir_select_btn', function (e) { + + e.preventDefault(); + + // If the media frame already exists, reopen it. + if (frame) { + frame.open(); + return; + } + + // Create the media frame. + frame = wp.media.frames.mvCustomIR = wp.media({ + 'id' : 'mgjp_mv_select_placeholder_modal', + 'title' : mgjp_mv_options_media.ir_modal_title, + 'library' : { 'type': 'image' }, + 'button' : { 'text': mgjp_mv_options_media.ir_modal_btn } + }); + + // When an image is selected, run a callback. + frame.on('select', function () { + var attachment = frame.state().get('selection').toJSON(); + + $.get(ajaxurl, { + 'action' : 'mgjp_mv_get_attachment_image', + 'id' : attachment[0].id, + 'size' : mgjp_mv_options_media.ir_size, + 'args' : mgjp_mv_options_media.ir_preview_args + }, function (html) { + + if (-1 !== html && 0 !== html && html) { + input.val(attachment[0].id); + preview.hide().html(html).fadeIn(300); + + if (1 > $('#mgjp_mv_ir_restore_default').length && mgjp_mv_options_media.ir_default !== attachment[0].id) { + container.append(restore_btn); + } else if (mgjp_mv_options_media.ir_default === attachment[0].id) { + $('#mgjp_mv_ir_restore_default').parent().detach(); + } + + } + }); + }); + + // Finally, open the modal + frame.open(); + + }) + + // register the restore default callback + .on('click', '#mgjp_mv_ir_restore_default', function () { + + // attempt to restore the default + $.post(ajaxurl, { + 'action' : 'mgjp_mv_restore_default_placeholder_image', + 'nonce' : mgjp_mv_options_media.ir_restore_nonce, + 'size' : mgjp_mv_options_media.ir_size, + 'args' : mgjp_mv_options_media.ir_preview_args + }, function (data) { + + if (-1 !== data && 0 !== data && data) { + // use json2.js to parse json data + data = JSON.parse(data); + input.val(data.id); + preview.hide().html(data.img).fadeIn(300); + $('#mgjp_mv_ir_restore_default').parent().detach(); + mgjp_mv_options_media.ir_default = data.id; + } + }); + }); + +}(jQuery)); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006650_index.js b/pool/shard001/JavaScript/0006650_index.js new file mode 100644 index 0000000000000000000000000000000000000000..b7dde2a903edabe53a12c27deca7b57b687e8c44 --- /dev/null +++ b/pool/shard001/JavaScript/0006650_index.js @@ -0,0 +1,43 @@ +'use strict'; + +var xsrfToken = require('frau-xsrf-token'); + +var XSRF_HEADER = 'X-Csrf-Token'; + +function noop() {} + +function isRelative/*ly safe*/(url) { + return typeof url === 'string' + && url.length > 0 + && url[0] === '/'; +} + +module.exports = function getXsrfToken(req) { + var end = req.end; + + req.end = function getXsrfTokenEndOverride(cb) { + function completeRequest() { + req.end = end; + return req.end(cb); + } + + if (!isRelative(req.url)) { + return completeRequest(); + } + + xsrfToken() + .then(function(token) { + req.set(XSRF_HEADER, token); + }) + .catch(noop) + .then(function() { + // Run this async in another turn + // So we don't catch errors with our promise + setTimeout(completeRequest); + }); + + return this; + }; + + return req; +}; diff --git a/pool/shard001/JavaScript/0006651_route.js b/pool/shard001/JavaScript/0006651_route.js new file mode 100644 index 0000000000000000000000000000000000000000..e585da008ebb15a850de550ebd32b0de3512e99f --- /dev/null +++ b/pool/shard001/JavaScript/0006651_route.js @@ -0,0 +1,117 @@ +/* + depede + + This module depends on crossroads.min.js and hasher.min.js + to interprete the navigation hash. +*/ +;(function() { + 'use strict'; + + walt.domino.modules = walt.domino.modules || {}; + walt.domino.modules.Route = function() { + domino.module.call(this); + + var _self = this, + _routes = [], + previous_hash; + + + function bind(route, scene) { + _routes[ scene ] = route; + + route.matched.add(function(){ + var scene_args = {}; + + // a delicate pairing! We trust the routing lib so much... + for(var i=0; i param param2 ... paramN}}{{/url}} + + */ + Handlebars.registerHelper("url", function(scene) { + var params = {}; + + for( var i=1; i: }`. + * @param {string[]} svgFiles - A list of filenames. + * @param {Function} getSvg - A function that returns the contents of an SVG file given a filename. + * @returns {Object} + */ +function buildIconsObject(svgFiles, getSvg) { + return svgFiles + .map(svgFile => { + const name = path.basename(svgFile, '.svg'); + const svg = getSvg(svgFile); + const contents = getSvgContents(svg); + return { name, contents }; + }) + .reduce((icons, icon) => { + icons[icon.name] = icon.contents; + return icons; + }, {}); +} + +/** + * Get contents between opening and closing `` tags. + * @param {string} svg + * @returns {string} + */ +function getSvgContents(svg) { + const $ = cheerio.load(svg); + return minify($('svg').html(), { collapseWhitespace: true }); +} + +export default buildIconsObject; diff --git a/pool/shard001/JavaScript/0006657_api-wrapper.js b/pool/shard001/JavaScript/0006657_api-wrapper.js new file mode 100644 index 0000000000000000000000000000000000000000..8c70d0c31a245a7cb219d305f7bb70ba2420adf1 --- /dev/null +++ b/pool/shard001/JavaScript/0006657_api-wrapper.js @@ -0,0 +1,122 @@ +'use strict'; + +//jscs:disable maximumLineLength + +var _ = require('lodash'); +var API500px = require('500px'); +var api500px = new API500px('251YxA969WW86g2EpIv3UoLTiWdUTK6EAgvIzUXf'); + +var Image = require('../../models/image.js').Image; + +var formatResponse = function(list) { + console.log('formatResponse', list.length); + + var result = _.map(list, function(item) { + // console.log('item', item); + + var image = {}; + + image.provider = '500px'; + image.referenceId = item.id; + image.url = item.image_url; + image.author = item.user ? item.user.username : null; + image.votes = item.rating; + image.views = item.times_viewed; + image.caption = item.description || item.name; + image.created = new Date(Date.parse(item.created_at)); + + if (item.comments) { + // image.comments = { + // count: item.comments.count, + // data: _.map(item.comments.data, function(comment) { + // return { + // username: comment.from.username, + // text: comment.text, + // likes: null, + // created: comment.created_time + // } + // }) + // } + } + + var imageModel = new Image(); + imageModel = _.merge(imageModel, image); + + return imageModel; + }); + + return _.compact(result); +}; + +exports.getImages = function(page, callback) { + // console.log('500px getImages'); + + api500px.photos.getPopular( + { + 'sort': 'created_at', + 'page': page || 1 + }, + function(error, results) { + if (error) { + console.log('ERROR', error); + return; + } + + var currentPage = results.current_page; + var totalPages = results.total_pages; + var totalItems = results.total_items; + var photos = results.photos; + + var formattedResponse = formatResponse(photos); + + return callback(formattedResponse); + } + ); + +}; + +exports.getOneImage = function(id, callback) { + console.log('500px getOneImage id', id); + + api500px.photos.getById (id, null, function(error, media) { + console.log(media); + + if (error) { + console.log('ERROR', error); + return; + } + + var photo = media.photo; + var comments = media.comments; + + var image = {}; + + image.provider = '500px'; + image.referenceId = photo.id; + image.url = photo.image_url; + image.author = photo.user ? photo.user.username : null; + image.votes = photo.rating; + image.views = photo.times_viewed; + image.caption = photo.description || photo.name; + image.created = new Date(Date.parse(photo.created_at)).toString(); + + if (comments) { + image.comments = { + count: '', + data: _.map(comments, function(comment) { + return { + username: null, + text: comment, + likes: null, + created: null + }; + }) + }; + } + + var imageModel = new Image(); + imageModel = _.merge(imageModel, image); + + callback(imageModel); + }); +}; diff --git a/pool/shard001/JavaScript/0006660_api.js b/pool/shard001/JavaScript/0006660_api.js new file mode 100644 index 0000000000000000000000000000000000000000..762901335adb7c4fff64def38e4a868e547d398a --- /dev/null +++ b/pool/shard001/JavaScript/0006660_api.js @@ -0,0 +1,17 @@ +const express = require("express") +const router = new express.Router() + +const config = require("../config/config") + +router.get("/test", (req, res) => { + console.log(`**Accessing /api/test route...`) + + res.status(200) + + res.json({ + status: `Success`, + message: `You have called /api/test route.` + }) +}) + +module.exports = router diff --git a/pool/shard001/JavaScript/0006663_restore-built-in-profiles-view.js b/pool/shard001/JavaScript/0006663_restore-built-in-profiles-view.js new file mode 100644 index 0000000000000000000000000000000000000000..e23638f8f5b3e39c7958bb66cfffde74bb70d9cb --- /dev/null +++ b/pool/shard001/JavaScript/0006663_restore-built-in-profiles-view.js @@ -0,0 +1,54 @@ +import $ from 'jquery'; +import _ from 'underscore'; +import ModalFormView from '../../components/common/modal-form'; +import Template from './templates/quality-profiles-restore-built-in-profiles.hbs'; + +export default ModalFormView.extend({ + template: Template, + + onFormSubmit: function () { + ModalFormView.prototype.onFormSubmit.apply(this, arguments); + this.disableForm(); + this.sendRequest(); + }, + + onRender: function () { + ModalFormView.prototype.onRender.apply(this, arguments); + this.$('select').select2({ + width: '250px', + minimumResultsForSearch: 50 + }); + }, + + sendRequest: function () { + var that = this, + url = baseUrl + '/api/qualityprofiles/restore_built_in', + options = { + language: this.$('#restore-built-in-profiles-language').val() + }; + return $.ajax({ + type: 'POST', + url: url, + data: options, + statusCode: { + // do not show global error + 400: null + } + }).done(function () { + that.collection.fetch({ reset: true }); + that.collection.trigger('destroy'); + that.destroy(); + }).fail(function (jqXHR) { + that.showErrors(jqXHR.responseJSON.errors, jqXHR.responseJSON.warnings); + that.enableForm(); + }); + }, + + serializeData: function () { + return _.extend(ModalFormView.prototype.serializeData.apply(this, arguments), { + languages: this.options.languages + }); + } +}); + + diff --git a/pool/shard001/JavaScript/0006665_dashboard_context.js b/pool/shard001/JavaScript/0006665_dashboard_context.js new file mode 100644 index 0000000000000000000000000000000000000000..8c6c49f218d9cab1679f0c934a370d7da5a45b07 --- /dev/null +++ b/pool/shard001/JavaScript/0006665_dashboard_context.js @@ -0,0 +1,32 @@ +var _ = require('lodash'); +require('ui/state_management/app_state'); + + +module.exports = function dashboardContext(Private, getAppState) { + return function () { + var queryFilter = Private(require('ui/filter_bar/query_filter')); + var bool = {must: [], must_not: []}; + var filterBarFilters = queryFilter.getFilters(); + var queryBarFilter = getAppState().query; + + // Add the query bar filter, its handled differently. + bool.must.push(queryBarFilter); + + // Add each of the filter bar filters + _.each(filterBarFilters, function (filter) { + var esFilter = _.omit(filter, function (val, key) { + if (key === 'meta' || key[0] === '$') return true; + return false; + }); + + if (filter.meta.disabled) return; + if (filter.meta.negate) { + bool.must_not.push(esFilter.query || esFilter); + } else { + bool.must.push(esFilter.query || esFilter); + } + }); + + return {bool: bool}; + }; +}; diff --git a/pool/shard001/JavaScript/0006667_lock.js b/pool/shard001/JavaScript/0006667_lock.js new file mode 100644 index 0000000000000000000000000000000000000000..607926e7562f3cddd5e3758f24aa0ceb87a469da --- /dev/null +++ b/pool/shard001/JavaScript/0006667_lock.js @@ -0,0 +1,66 @@ +var getIndexFromOrderedArray = require("../basic/getIndexFromOrderedArray"); +var saveToOrderedArray = require("../basic/saveToOrderedArray"); +var lazy = require("../basic/lazy"); +var cached = [];//500 000; +var multiCount = Object.create(null); +var clearCache = lazy(function () { + var pass = Date.now() - 600 * 1000; + cached = cached.filter(c => c.time > pass); +}, 80); +var preventCached = function (interval = 60000, id) { + clearCache(); + if (cached.length > 0x7ffff) { + // 10分钟最多50万并发 + // 7小时2千万次 + // 5天 1亿 + // 90亿 两年 + + throw new Error("服务器忙,请稍后再试!"); + } + var index = getIndexFromOrderedArray(cached, id); + var c = cached[index]; + var now = Date.now(); + if (c && c.value === id) { + if (now - c.time < interval) { + // 单个ip 最多1个 + var seconds = (interval / 1000 | 0) + 1; + if (seconds < 2) { + seconds = "重试"; + } + if (seconds < 60) { + seconds = seconds + "秒后再试"; + } + else if (seconds < 3600) { + seconds = (seconds / 60 + 1 | 0) + "分钟后再试" + } + else if (seconds < 86400) { + seconds = (seconds / 3600 + 1 | 0) + "小时后再试"; + } + else { + seconds = "过几天再试"; + } + throw new Error("操作过于频繁,请" + seconds); + } + if (!c.count) c.count = 2; + else c.count++; + } + else { + saveToOrderedArray(cached, { time: now, value: id }); + } + var savedLength = cached.length; + if (savedLength === cached.length) { + if (!multiCount[id]) { + multiCount[id] = []; + } + if (multiCount[id].length > 200) { + + } + multiCount[id].push(now); + } +}; +function lock(time) { + return preventCached.bind(null, time); +} + + +module.exports = lock; \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006668_util.js b/pool/shard001/JavaScript/0006668_util.js new file mode 100644 index 0000000000000000000000000000000000000000..1d05c05c0ae6557dba14f10dcac17c7e05339ebe --- /dev/null +++ b/pool/shard001/JavaScript/0006668_util.js @@ -0,0 +1,108 @@ +(function(){ + "use strict"; + var global = window; + + // Return a function for getting values at arbitrarily depth inside an object. + // getPath('a.b.c') is equivalent to function(obj) { return obj.a.b.c; } + // except that it will return undefined if obj, obj.a, or obj.a.b is undefined/falsey. + // Arrays can also be indexed, eg getPath('0.x')([{x:1}]) returns 1 + var getPath = function(path) { + // Natively we need something like getPath(['a','b','c']), but who wants to type that? + if (typeof path === 'string') + path = path.split('.'); + return function(obj) { + _.forEach(path, function(segment) { + if (obj) obj = obj[segment]; + }); + return obj; + }; + }; + + define('Placeholder', + ['lodash'], + function(_) { + // Placeholders that will let us fill templates without having to parse tons of strings. + var Placeholder = function(getter) { + if (typeof getter == 'string') + getter = getPath(getter); + this.fill = getter; + } + Placeholder.fill = function(pattern, context) { + if (typeof pattern !== 'object') + return pattern; + if (pattern instanceof Placeholder) + return pattern.fill(context); + if (pattern instanceof Array) + return _.map(pattern, function(subpattern) { return Placeholder.fill(subpattern, context); }); + return _.mapValues(pattern, function(subpattern) { return Placeholder.fill(subpattern, context); }); + }; + Placeholder.set = function() { + var paths = _.flatten(arguments); + return _(paths).zipObject().transform(function(result, _, path) { + result[path.replace(/\./g, '_')] = new Placeholder(getPath(path)); + }).value(); + }; + return Placeholder; + }); + + var noiseBox; + define('Random', + ['lodash'], + function(_) { + return { + // Poisson distribution: number of events in an arbitrary fixed interval given an expected average. + // http://en.wikipedia.org/wiki/Poisson_distribution#Generating_Poisson-distributed_random_variables + poisson: function(expected) { + return function() { + var x = 0, p = Math.exp(-expected), s = p, u = Math.random(); + while (u > s) { + x += 1; + p *= expected / x; + s += p; + } + return x; + }; + }, + noise1d: function(index) { + if (!noiseBox) { + noiseBox = []; + for (var i = 0; i < 256; ++i) + noiseBox.push(i); + noiseBox = _.shuffle(noiseBox); + } + return function(t) { + var t0 = Math.floor(t), + k0 = noiseBox[(noiseBox[(noiseBox[index & 255] + t0) & 255] + (t0 >> 8)) & 255], + t1 = t0 + 1, + k1 = noiseBox[(noiseBox[(noiseBox[index & 255] + t1) & 255] + (t1 >> 8)) & 255], + f = t - t0; + // Scale the output to 0 to 1 range. + k0 = (k0 & 15) / 15; + k1 = (k1 & 15) / 15; + // Smooth so derivative is 0 at all integral t. + f = 3*f*f - 2*f*f*f; + // Interpolate and scale to -1 .. +1. + return ((f * k1 + (1 - f) * k0) - 0.5) * 2; + }; + }, + }; + }); + + define('Util', + ['lodash'], + function(_) { + return { + SumAcc: (function(){ + var SumAcc = function(init) { this.sum = init || 0; }; + SumAcc.prototype.add = function(x) { this.sum += x; }; + return SumAcc; + })(), + ConcatAcc: (function(){ + var ConcatAcc = function(init) { this.sum = init || []; }; + ConcatAcc.prototype.add = function(x) { this.sum.push(x); }; + return ConcatAcc; + })(), + }; + }); + +})(); diff --git a/pool/shard001/JavaScript/0006669_get.js b/pool/shard001/JavaScript/0006669_get.js new file mode 100644 index 0000000000000000000000000000000000000000..8c53f8d05c21453878ac0b448bfcc0e848ff0382 --- /dev/null +++ b/pool/shard001/JavaScript/0006669_get.js @@ -0,0 +1,196 @@ +'use strict'; + +const boom = require('boom'); +const joi = require('joi'); +const schema = require('screwdriver-data-schema'); +const getSchema = schema.models.collection.get; +const idSchema = joi.reach(schema.models.collection.base, 'id'); +const logger = require('screwdriver-logger'); + +/** + * Helper function to get PR info of pipeline + * + * @param {Pipeline} pipeline Pipeline model to get PR info for + * @returns {Object} + */ +function getPipelinePRInfo(pipeline) { + const prs = { + open: 0, + failing: 0 + }; + + // Get all the PR jobs + return pipeline.getJobs({ type: 'pr' }) + .then((prJobs) => { + if (!prJobs) { + return prs; + } + + // Return array of prJobs' builds + return Promise.all(prJobs.map(job => + job.getBuilds() + )); + }) + .then((prJobsBuilds) => { + if (!prJobsBuilds || !prJobsBuilds.length) { + return prs; + } + + // prJobsBuilds is a 2D array where each element is an array of builds + // for one PR job. + prs.open = prJobsBuilds.length; + + prJobsBuilds.forEach((jobBuilds) => { + // Check the first element (last build) if pr job failed + if (jobBuilds[0].status === 'FAILURE') { + prs.failing += 1; + } + }); + + return prs; + }) + .catch((err) => { + logger.error(err); + + return prs; + }); +} + +/** + * Helper function to get last builds of pipeline + * + * @param {Object} pipeline Pipeline to get last builds for + * @param {Factory} eventFactory Factory for getting last event model + * @returns {Object} + */ +function getPipelineHealth(pipeline, eventFactory) { + let lastBuilds = []; + + if (!pipeline.lastEventId) { + return lastBuilds; + } + + return eventFactory.get(pipeline.lastEventId) + .then((event) => { + if (!event) { + return lastBuilds; + } + + return event.getBuilds() + .then((builds) => { + if (builds.length) { + // The events are sorted by most recent first. Need to reverse the order + // to allow for matching with workflow job on the UI + lastBuilds = builds.map(b => b.toJson()).reverse(); + } + + return lastBuilds; + }); + }) + .catch((err) => { + logger.error(err); + + return lastBuilds; + }); +} + +/** + * Helper function to populate pipelines with last builds and pr info + * + * @param {Array} pipelines Array of pipeline models to get last builds for + * @param {Factory} eventFactory Factory for getting last event model + * @returns {Array} + */ +function getPipelinesInfo(pipelines, eventFactory) { + return pipelines + // Filter out pipelines that don't exist + .filter(pipeline => !!pipeline) + .map(pipeline => + // Get the PR Info and last builds for each pipeline + Promise.all([ + getPipelinePRInfo(pipeline), + getPipelineHealth(pipeline, eventFactory) + ]) + // Combine the PR Info and last builds and return the populated pipeline + .then(([pipelinePRInfo, pipelineHealth]) => { + const result = Object.assign({}, pipeline.toJson()); + + result.prs = pipelinePRInfo; + result.lastBuilds = pipelineHealth; + + return result; + }) + ); +} + +module.exports = () => ({ + method: 'GET', + path: '/collections/{id}', + config: { + description: 'Get a single collection', + notes: 'Returns a collection record', + tags: ['api', 'collections'], + auth: { + strategies: ['token'], + scope: ['user', '!guest'] + }, + plugins: { + 'hapi-swagger': { + security: [{ token: [] }] + } + }, + handler: (request, reply) => { + const { collectionFactory, pipelineFactory, eventFactory, userFactory } + = request.server.app; + const { username, scmContext } = request.auth.credentials; + + return Promise.all([ + collectionFactory.get(request.params.id), + userFactory.get({ username, scmContext }) + ]) + .then(([collection, user]) => { + if (!collection) { + throw boom.notFound('Collection does not exist'); + } + + const result = Object.assign({}, collection.toJson()); + + if (user.id !== result.userId) { + // If the user accessing this collection is not the owner, return shared as type + result.type = 'shared'; + } else if (!result.type) { + // If the collection type is empty, return normal as type + result.type = 'normal'; + } + + // Store promises from pipelineFactory fetch operations + const collectionPipelines = []; + + result.pipelineIds.forEach((id) => { + collectionPipelines.push(pipelineFactory.get(id)); + }); + + return Promise.all(collectionPipelines) + // Populate pipelines with PR Info and then last builds + .then(pipelines => Promise.all(getPipelinesInfo(pipelines, eventFactory))) + .then((pipelinesWithInfo) => { + result.pipelines = pipelinesWithInfo; + // pipelineIds should only contain pipelines that exist + result.pipelineIds = pipelinesWithInfo.map(p => p.id); + delete result.userId; + + return reply(result); + }); + }) + .catch(err => reply(boom.boomify(err))); + }, + response: { + schema: getSchema + }, + validate: { + params: { + id: idSchema + } + } + } +}); diff --git a/pool/shard001/JavaScript/0006670_locations.server.controller.js b/pool/shard001/JavaScript/0006670_locations.server.controller.js new file mode 100644 index 0000000000000000000000000000000000000000..977387f4edd74810c0a16248990b0317911d6628 --- /dev/null +++ b/pool/shard001/JavaScript/0006670_locations.server.controller.js @@ -0,0 +1,186 @@ +'use strict'; + +/** + * Module dependencies. + */ +var mongoose = require('mongoose'), + errorHandler = require('./errors.server.controller'), + Locations = mongoose.model('locations'); + + + +// Crear un nuevo método controller manejador de errores +var getErrorMessage = function(err) { + // Definir la variable de error message + var message = ''; + + // Si un error interno de MongoDB ocurre obtener el mensaje de error + if (err.code) { + switch (err.code) { + // Si un eror de index único ocurre configurar el mensaje de error + case 11000: + case 11001: + message = 'Este Pais ya existe'; + break; + // Si un error general ocurre configurar el mensaje de error + default: + message = 'Se ha producido un error'; + } + } else { + // Grabar el primer mensaje de error de una lista de posibles errores + for (var errName in err.errors) { + if (err.errors[errName].message) message = err.errors[errName].message; + } + } + // Devolver el mensaje de error + return message; +}; + +/** + * Create a Pai + */ +exports.create = function(req, res) { + var locations = new Locations(req.body); + locations.user = req.user; + + locations.save(function(err) { + if (err) { + if(err.code === 11000){ + return res.status(401).send({ + message: 'Centro ya existe' + }); + }else { + return res.status(400).send({ + message: errorHandler.getErrorMessage(err) + }); + } + } else { + res.jsonp(locations); + } + }); +}; + +/** + * Show the current Pai + */ +exports.read = function(req, res) { + res.jsonp(req.location); +}; + +/** + * Update a Pai + */ +exports.update = function(req, res) { + var location = req.location; + location.name = req.body.name; + location.tipo = req.body.tipo; + location.locationRNC = req.body.locationRNC; + location.locationTelefono = req.body.locationTelefono; + location.pais = req.body.pais; + location.ciudad = req.body.ciudad; + location.sector = req.body.sector; + location.locationDireccion = req.body.locationDireccion; + location.save(function(err) { + if (err) { + return res.status(400).send({ + message: errorHandler.getErrorMessage(err) + }); + } else { + res.jsonp(location); + } + }); +}; + +/** + * Delete an Pai + */ +exports.delete = function(req, res) { + var location = req.location ; + location.remove(function(err) { + if (err) { + return res.status(400).send({ + message: errorHandler.getErrorMessage(err) + }); + } else { + res.jsonp(location); + } + }); +}; + +/** + * List of Pais + */ +exports.list = function(req, res) { + + var count = req.query.count || 5; + var page = req.query.page || 1; + + var filter = { + filters: { + field: ['name', 'locationRNC', 'locationTelefono'], + mandatory: { + contains: req.query.filter + } + } + }; + + var pagination = { + start : (page - 1) * count, + count : count + }; + + var sort ={ + sort: { + desc: '_id' + } + }; + + Locations + .find() + .filter(filter) + .order(sort) + .page(pagination, function(err, location){ + if (err) { + return res.status(400).send({ + message: errorHandler.getErrorMessage(err) + }); + } else { + res.jsonp(location); + } + }); +}; + +exports.getList = function(req, res) { + Locations + .find().exec(function(err, patient){ + if (err) { + return res.status(400).send({ + message: errorHandler.getErrorMessage(err) + }); + } else { + res.jsonp(patient); + } + }); +}; + +/** + * Pai middleware + */ +exports.locationsByID = function(req, res, next, id) { + Locations.findById(id).populate('user', 'displayName').exec(function(err, location) { + if (err) return next(err); + if (! location) return next(new Error('Failed to load location ' + id)); + req.location = location ; + next(); + }); +}; + +/** + * Pai authorization middleware + */ +exports.hasAuthorization = function(req, res, next) { + if (req.location.user.id !== req.user.id) { + return res.status(403).send('User is not authorized'); + } + next(); +}; diff --git a/pool/shard001/JavaScript/0006671_graphql-client.js b/pool/shard001/JavaScript/0006671_graphql-client.js new file mode 100644 index 0000000000000000000000000000000000000000..616df1c6996f14894c4cf4663a25c1c5651e8a66 --- /dev/null +++ b/pool/shard001/JavaScript/0006671_graphql-client.js @@ -0,0 +1,42 @@ +import { InMemoryCache } from 'apollo-cache-inmemory' +import { WebSocketLink } from 'apollo-link-ws' +import { persistCache } from 'apollo-cache-persist' +import ApolloClient from 'apollo-client' +import { ApolloLink } from 'apollo-link' + +let client + +export async function getClient({ url, reconnect }) { + + // Client already exists + if (client) { + return client + } + + console.log('Create new GraphQL client for', url) + + // WebSocket connection + const websocketLink = new WebSocketLink({ + uri: url, + options: { + reconnect + } + }) + + // Stitch different links together + const link = ApolloLink.from([ + websocketLink + ]) + + // Cache + const cache = new InMemoryCache().restore(window.__APOLLO_STATE__) + await persistCache({ + cache, + storage: window.localStorage + }) + + // Create a new client + client = new ApolloClient({ cache, link, ssrForceFetchDelay: 100, debug: true }) + + return client +} diff --git a/pool/shard001/JavaScript/0006673_typeProductService.js b/pool/shard001/JavaScript/0006673_typeProductService.js new file mode 100644 index 0000000000000000000000000000000000000000..564927b90ebecdb70080fcad91bec611c07f9084 --- /dev/null +++ b/pool/shard001/JavaScript/0006673_typeProductService.js @@ -0,0 +1,41 @@ +app.service('typeProductService', ['$http', '$q', function ($http, $q) { + + this.noCache = function () { + return '?_' + new Date().getTime(); + } + + this.getTypeProducts = function () { + var defer = $q.defer(); + $http.get('/api/typeProduct').success(function (response) { + defer.resolve(response); + }) + return defer.promise; + } + + this.save = function (typeProduct) { + var defer = $q.defer(); + $http.post('/api/typeProduct', typeProduct).success(function (response) { + defer.resolve(response); + }); + return defer.promise; + } + + this.edit = function (typeProduct) { + var defer = $q.defer(); + + $http.put('/api/typeProduct/'.concat(typeProduct._id), typeProduct).success(function (response) { + defer.resolve(response); + }); + return defer.promise; + } + + this.remove = function (id) { + var defer = $q.defer(); + + $http.delete('/api/typeProduct/'.concat(id)).success(function (response) { + defer.resolve(response); + }); + return defer.promise; + } + +}]); diff --git a/pool/shard001/JavaScript/0006674_component.js b/pool/shard001/JavaScript/0006674_component.js new file mode 100644 index 0000000000000000000000000000000000000000..62893110629bff776183d0e9aeb574f96580c914 --- /dev/null +++ b/pool/shard001/JavaScript/0006674_component.js @@ -0,0 +1,30 @@ +import { get } from '@ember/object'; +import { observer } from '@ember/object'; +import { run } from '@ember/runloop'; +import XBaseComponent from '../x-base/component'; +import layout from './template'; + +export default XBaseComponent.extend({ + layout, + changeUnderlineSize: observer('isEditing', function() { + run.later(() => { + const borderBottom = this.element.querySelector('.borderBottom'); + const select = this.element.querySelector('select'); + const selectContainer = this.element.querySelector('.selectContainer'); + const { text } = select.options[select.selectedIndex]; + + if (!get(this, 'isEditing')) { + const size = this.getTextWidth(select, text); + selectContainer.style.width = 'auto'; + selectContainer.style.height = `${size.height + 16}px`; + select.style.width = `${size.width + 2}px`; + select.style.height = `${size.height + 11}px`; + borderBottom.style.width = size.width; + } else { + selectContainer.style.width = '68%'; + selectContainer.style.height = 'auto'; + select.style.width = '100%'; + } + }); + }) +}); diff --git a/pool/shard001/JavaScript/0006676_candidateRouter.js b/pool/shard001/JavaScript/0006676_candidateRouter.js new file mode 100644 index 0000000000000000000000000000000000000000..3665963bfacd63139298b708b84c19a267f6f3fd --- /dev/null +++ b/pool/shard001/JavaScript/0006676_candidateRouter.js @@ -0,0 +1,169 @@ +/*jslint node: true */ /*eslint-env node*/ +'use strict'; + +var express = require('express'), + CandidateModule = require('../models/candidate'), + Candidate = CandidateModule.model, + getCandidateTemplate = CandidateModule.getTemplate, + // getSubDocPopulateOptions = CandidateModule.getSubDocPopulateOptions, + populateSubDocs = CandidateModule.populateSubDocs, + personRouterModule = require('./personRouter'), + createPerson = personRouterModule.createPerson, + deletePerson = personRouterModule.deletePerson, + updatePerson = personRouterModule.updatePerson, + Verify = require('./verify'), + router_utils = require('./router_utils'), + checkError = router_utils.checkError, + errorReply = router_utils.errorReply, + resultReply = router_utils.resultReply, + populateSubDocsReply = router_utils.populateSubDocsReply, + makeResult = router_utils.makeResult, + removeDocAccessOk = router_utils.removeDocAccessOk, + // utils = require('../misc/utils'), + Consts = require('../consts'); + + +var router = express.Router(); + +function createCandidate (req, res, next) { + + var candidateFields = getCandidateTemplate(req.body, ['person']); // only exclude person as party is required + + Candidate.create(candidateFields, function (err, candidate) { + if (!checkError (err, res)) { + + req.body.owner = candidate._id; // add candidate owner field + + // create person (no access check as done on route) + createPerson(Verify.verifyNoCheck, req, res, function (result, res) { + if (result) { + // person successfully created + candidate.person = result.payload._id; + candidate.save(function (err, newcandidate) { + if (!checkError (err, res)) { + // success + populateSubDocs(newcandidate, function (err, doc) { + populateSubDocsReply(err, res, next, doc, Consts.HTTP_CREATED); + }); + } else { + // tidy up by removing everything + deletePerson(req, candidate.person, res, function (result, res) { }); + removeDocAccessOk(Candidate, candidate._id); + var saveErr = new Error('Unable to save candidate.'); + saveErr.status = Consts.HTTP_INTERNAL_ERROR; + checkError(saveErr, res); + } + }); + } else { + // tidy up by removing candidate + removeDocAccessOk(Candidate, candidate._id); + var err = new Error('Unable to create person.'); + err.status = Consts.HTTP_INTERNAL_ERROR; + checkError(err, res); + } + }); + } + }); +} + +function updateCandidate (id, req, res, next) { + + var candidateFields = getCandidateTemplate(req.body, ['person']); // only exclude person as party is required + + Candidate.findByIdAndUpdate(id, { + $set: candidateFields + }, { + new: true // return the modified document rather than the original + }, function (err, candidate) { + if (!checkError (err, res)) { + // update person (no access check sd done on route) + updatePerson(Verify.verifyNoCheck, candidate.person, req, res, function (result, res) { + if (result) { + // success + populateSubDocs(candidate, function (err, doc) { + populateSubDocsReply(err, res, next, doc, Consts.HTTP_OK); + }); + } + }); + } + }); +} + +function deleteCandidate (id, req, res, next) { + + Candidate.findById(id, function (err, doc) { + if (!checkError (err, res)) { + if (doc) { + // delete person (no access check sd done on route) + deletePerson(Verify.verifyNoCheck, doc.person, req, res, function (result, res) { + if (result) { + // success + doc.remove(function (err, doc) { + if (!checkError (err, res)) { + // success + next(makeResult(Consts.HTTP_OK, doc), res); + } + }); + } + }); + } else { + errorReply(res, Consts.HTTP_NOT_FOUND, 'Unknown candidate identifier'); + } + } + }); +} + + +router.route('/') + + .get(Verify.verifyHasCanvasserAccess, function (req, res, next) { + Candidate.find({}) + .exec(function (err, docs) { + if (!checkError(err, res)) { + populateSubDocs(docs, function (err, docs) { + if (!checkError(err, res)) { + res.json(docs); + } + }); + } + }); + }) + + .post(Verify.verifyHasStaffAccess, function (req, res) { + + createCandidate(req, res, resultReply); + }); + + +router.route('/:objId') + + .get(Verify.verifyHasCanvasserAccess, function (req, res, next) { + Candidate.findById(req.params.objId) + .exec(function (err, doc) { + if (!checkError(err, res)) { + if (doc) { + populateSubDocs(doc, function (err, doc) { + if (!checkError(err, res)) { + res.json(doc); + } + }); + } else { + errorReply(res, Consts.HTTP_NOT_FOUND, 'Unknown candidate identifier'); + } + } + }); + }) + + .put(Verify.verifyHasStaffAccess, function (req, res, next) { + + updateCandidate (req.params.objId, req, res, resultReply); + }) + + .delete(Verify.verifyHasStaffAccess, function (req, res, next) { + + deleteCandidate(req.params.objId, req, res, resultReply); + }); + +module.exports = { + router: router +}; \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006680_user-controller.js b/pool/shard001/JavaScript/0006680_user-controller.js new file mode 100644 index 0000000000000000000000000000000000000000..e09d63ec758aa96b9ddeabdcf6eb2038deef678e --- /dev/null +++ b/pool/shard001/JavaScript/0006680_user-controller.js @@ -0,0 +1,88 @@ +'use strict'; + +angular.module('ping') + .controller('UserController', ['$scope', '$modal', 'resolvedUser', 'User', + function ($scope, $modal, resolvedUser, User) { + + $scope.users = resolvedUser; + + $scope.create = function () { + $scope.clear(); + $scope.open(); + }; + + $scope.update = function (id) { + $scope.user = User.get({id: id}); + $scope.open(id); + }; + + $scope.delete = function (id) { + User.delete({id: id}, + function () { + $scope.users = User.query(); + }); + }; + + $scope.save = function (id) { + if (id) { + User.update({id: id}, $scope.user, + function () { + $scope.users = User.query(); + $scope.clear(); + }); + } else { + User.save($scope.user, + function () { + $scope.users = User.query(); + $scope.clear(); + }); + } + }; + + $scope.clear = function () { + $scope.user = { + + "firstname": "", + + "lastname": "", + + "email": "", + + "photourl": "", + + "id": "" + }; + }; + + $scope.open = function (id) { + var userSave = $modal.open({ + templateUrl: 'user-save.html', + controller: UserSaveController, + resolve: { + user: function () { + return $scope.user; + } + } + }); + + userSave.result.then(function (entity) { + $scope.user = entity; + $scope.save(id); + }); + }; + }]); + +var UserSaveController = + function ($scope, $modalInstance, user) { + $scope.user = user; + + + + $scope.ok = function () { + $modalInstance.close($scope.user); + }; + + $scope.cancel = function () { + $modalInstance.dismiss('cancel'); + }; + }; diff --git a/pool/shard001/JavaScript/0006681_app.js b/pool/shard001/JavaScript/0006681_app.js new file mode 100644 index 0000000000000000000000000000000000000000..94961efd39c7d02c55c4d5cd155bf8c5d46bba1b --- /dev/null +++ b/pool/shard001/JavaScript/0006681_app.js @@ -0,0 +1,86 @@ +define( [ + "jquery", + "sammy", + "moment", + "bootstrap", + "bootstrap-editable", + "bootstrap-slider", + "knockout", + "common/dialog", + "viewmodels/wallet", + "socket.io", + "knockout-amd-helpers", + "knockout-validation", + "knockout-x-editable", + "knockout-file-bindings", + "bindinghandlers/modal", + "bindinghandlers/slider", + "bindinghandlers/numeric-text", + "bindinghandlers/numeric-input" + ], function(jQuery, Sammy, moment, bs, bse, bss, ko, dialog, Wallet, io){ + var App = function(){ + }; + ko.amdTemplateEngine.defaultPath = "../views"; + ko.amdTemplateEngine.defaultSuffix = ".html"; + ko.amdTemplateEngine.defaultRequireTextPluginName = "text"; + ko.bindingHandlers.module.baseDir = "viewmodels"; + + App.prototype.init = function() { + var wallet = new Wallet(); + + var port = (window.location.port === '' ? '' : ":" + window.location.port); + var sockOpt = { + "force new connection" : true, + "reconnectionAttempts": 3, + "timeout" : 3000, + "transports" : ["websocket"] + }; + + //console.log('DEBUG: ' + window.location.protocol + '//' + window.location.hostname + port + '/'); + var socket = io.connect(window.location.protocol + '//' + window.location.hostname + port + '/', sockOpt); + socket.on('news', function (data) { + console.log(data); + }); + socket.on('wallet', function(state) { + // When the server sends a wallet message, set the wallet available state. + if (state === 'down') { + wallet.walletUp(false); + } else { + wallet.walletUp(true); + } + }); + socket.on('abort', function(page) { + // handle abort request and redirect to page. + window.location = wallet.settings().chRoot + '/' + page; + }); + socket.on('continue', function(page) { + // handle abort request and redirect to page. + window.location = wallet.settings().chRoot + '/' + page; + }); + socket.on('connect_error', function(err) { + // handle server error + console.log('Error connecting to server. ' + err); + }); + + //$('.editable').editable.defaults.mode = 'inline'; // Comment or change to 'popup' (default) + + ko.applyBindings(wallet, $('#wrapper')[0]); + dialog.init($('#defaultModal')[0]); + + Sammy(function() { + this.get('#home', function() { + wallet.currentView('home'); + }); + this.get('#profile', function() { + wallet.currentView('profile'); + }); + this.get('#faq', function() { + wallet.currentView('faq'); + }); + this.get('#terms', function() { + wallet.currentView('terms'); + }); + }).run('#home'); + }; + return new App(); +}); diff --git a/pool/shard001/JavaScript/0006684_reducers.js b/pool/shard001/JavaScript/0006684_reducers.js new file mode 100644 index 0000000000000000000000000000000000000000..447c5841fade709c169b59097f6cc0a8abd2b1d4 --- /dev/null +++ b/pool/shard001/JavaScript/0006684_reducers.js @@ -0,0 +1,29 @@ +import { combineActions, handleActions, } from 'redux-actions' +import { + basicFailReducer, + basicLoadCompleteReducer, + basicStartReducer, +} from '../redux-helpers' +import actions from './actions' + +const initialState = { + summaries: [], +} + +export default handleActions( + { + [combineActions(actions.getSummaries.start)]: basicStartReducer, + + [combineActions(actions.getSummaries.fail)]: basicFailReducer, + + [actions.getSummaries.complete]: (state, action) => { + const { summaries, } = action.payload + + return { + ...basicLoadCompleteReducer(state, action), + summaries, + } + }, + }, + initialState +) diff --git a/pool/shard001/JavaScript/0006685_helpers.js b/pool/shard001/JavaScript/0006685_helpers.js new file mode 100644 index 0000000000000000000000000000000000000000..3c246c91603e953ddbcb1759e65b368e2b738e1c --- /dev/null +++ b/pool/shard001/JavaScript/0006685_helpers.js @@ -0,0 +1,27 @@ +// Helper functions, used in apps/budgeting/assets + +// toLocaleDate returns a formatted and internationalized +// date string. Fallback formatting is the German variant. +// input: 2021-11-11T15:37:19.490201+01:00 +// output: 11. November 2021 (depending on locale) +export const toLocaleDate = (isodate, locale = 'de-DE') => { + const date = new Date(isodate) + const formatStyle = { dateStyle: 'long' } + return new Intl.DateTimeFormat(locale, formatStyle).format(date) +} + +// intComma returns a number separated by +// a comma or period depending on the locale +// input: 20000 +// output: 20.000 or 20,000 +export const intComma = (number) => { + return Number(number).toLocaleString() +} + +// wrapSpaces returns the given value +// wrapped by a space before and after +// input: "0" +// output: " 0 " +export const wrapSpaces = (value) => { + return ` ${value} ` +} diff --git a/pool/shard001/JavaScript/0006690_Connection.js b/pool/shard001/JavaScript/0006690_Connection.js new file mode 100644 index 0000000000000000000000000000000000000000..3e34f5db5739c29f3929c7b4506955bb3cb799c1 --- /dev/null +++ b/pool/shard001/JavaScript/0006690_Connection.js @@ -0,0 +1,65 @@ +define([ + 'config', + 'shared/util/EventHelper' +], function( + config, + EventHelper +) { + var nextConnId = 0; + + function Connection(socket) { + var self = this; + this._connId = nextConnId++; + this._bufferedMessages = []; + this._events = new EventHelper([ 'receive', 'disconnect' ]); + + //handle the socket + this._socket = socket; + this._isConnected = true; + if(config.LOG_NETWORK_TRAFFIC) { console.log('[' + this._connId + '] connected'); } + this._socket.on('messages', function(messages) { + for(var i = 0; i < messages.length; i++) { + if(config.LOG_NETWORK_TRAFFIC) { console.log('[' + self._connId + '] received:', messages[i]); } + self._events.trigger('receive', messages[i]); + } + }); + this._socket.on('disconnect', function() { + self._isConnected = false; + if(config.LOG_NETWORK_TRAFFIC) { console.log('[' + self._connId + '] disconnected'); } + self._events.trigger('disconnect'); + }); + } + Connection.prototype.buffer = function(msg) { + this._bufferedMessages.push(msg); + }; + Connection.prototype.flush = function() { + if(this._bufferedMessages.length > 0) { + var messages = this._bufferedMessages; + this._bufferedMessages = []; + for(var i = 0; i < messages.length; i++) { + if(config.LOG_NETWORK_TRAFFIC) { console.log('[' + this._connId + '] sent:', messages[i]); } + } + this._socket.emit('messages', messages); + } + }; + Connection.prototype.send = function(msg) { + this.buffer(msg); + this.flush(); + }; + Connection.prototype.disconnect = function(permanently) { + if(permanently) { + this._socket.emit('force-disconnect'); + } + this._socket.disconnect(); + }; + Connection.prototype.isConnected = function() { + return this._isConnected; + }; + Connection.prototype.on = function(eventName, callback, ctx) { + return this._events.on.apply(this._events, arguments); + }; + Connection.prototype.sameAs = function(other) { + return other && other._connId === this._connId; + }; + return Connection; +}); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006692_author.js b/pool/shard001/JavaScript/0006692_author.js new file mode 100644 index 0000000000000000000000000000000000000000..7d6c6d0b2c5d7f0fa6c78882219118b86a8636b2 --- /dev/null +++ b/pool/shard001/JavaScript/0006692_author.js @@ -0,0 +1,15 @@ +import { Hal } from "threerest"; + +@Hal.halEntity("/authors/:id") +export default class Author { + + @Hal.resourceId() + id = 0; + + constructor(id, firstName, lastName, series) { + this.id = id; + this.firstName = firstName; + this.lastName = lastName; + this.series = series; + } +} diff --git a/pool/shard001/JavaScript/0006697_allowed.js b/pool/shard001/JavaScript/0006697_allowed.js new file mode 100644 index 0000000000000000000000000000000000000000..f4417e71c8445bf685fd3ed141b0beb4e59db678 --- /dev/null +++ b/pool/shard001/JavaScript/0006697_allowed.js @@ -0,0 +1,22 @@ +import DeniedException from 'fireblast-core/lib/exceptions/denied'; + +/** + * + * @param resource + * @param permission + * @returns {Function} + */ +export default function (resource, permission) { + return (request, response, next) => { + var app = response.locals.app, + user = request.user; + + app.logger.debug('checking permissions for %s to %s in %s', user.id, permission, resource); + + if (app.acl.hasPermission(user.group, resource, permission)) { + next(); + } else { + next(new DeniedException(resource, permission)); + } + }; +} \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006700_controls-collection.js b/pool/shard001/JavaScript/0006700_controls-collection.js new file mode 100644 index 0000000000000000000000000000000000000000..828e060971a6d51e70e0d163ac55fa274bce0b38 --- /dev/null +++ b/pool/shard001/JavaScript/0006700_controls-collection.js @@ -0,0 +1,67 @@ +(function() { + 'use strict'; + + /** + * add item control to the collection + * @param {Object} context + * @param {jQueryObject} $itemControl + */ + var add = function(context, $itemControl){ + + var control = context.controlFactory.create($itemControl); + + if(control){ + + //add to the list + context.controls.push(control); + } + }; + + /** + * get panel controls + * @param {Object} context + */ + var initControls = function(context){ + + var $itemsBox; + + if(context.options && context.options.itemsBox){ + $itemsBox = context.$root.find(context.options.itemsBox); + + if($itemsBox.length > 0){ + + $itemsBox.find('[data-control-type]').each(function(){ + + //add control to the list + add(context, jQuery(this)); + }); + } + } + }; + + /** + * Item Control Collection + * @constructor + * @param {Object} options - jplist user options + * @param {Object} observer + * @param {jQuery.fn.jplist.app.History} history + * @param {jQueryObject} $root + * @return {Object} + */ + jQuery.fn.jplist.ui.list.collections.ItemControlCollection = function(options, observer, history, $root){ + + this.options = options; + this.observer = observer; + this.history = history; + this.$root = $root; + this.controls = []; + this.controlFactory = null; + + //ini control factory + this.controlFactory = new jQuery.fn.jplist.ui.list.ItemControlFactory(options, observer, history, $root); + + //init controls + initControls(this); + }; + +})(); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006705_index.js b/pool/shard001/JavaScript/0006705_index.js new file mode 100644 index 0000000000000000000000000000000000000000..f1c1545c2276c0a1c8f0312a07d1d33884da4b5b --- /dev/null +++ b/pool/shard001/JavaScript/0006705_index.js @@ -0,0 +1,54 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2022 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +var filledarrayBy = require( '@stdlib/array/filled-by' ); +var discreteUniform = require( '@stdlib/random/base/discrete-uniform' ).factory; +var naryFunction = require( '@stdlib/utils/nary-function' ); +var add = require( '@stdlib/math/base/ops/add' ); +var array = require( '@stdlib/ndarray/array' ); +var map2 = require( './../lib' ); + +function fill( i ) { + var rand = discreteUniform( -10*(i+1), 10*(i+1) ); + return filledarrayBy( 10, 'generic', rand ); +} + +// Create two-dimensional ndarrays (i.e., matrices): +var opts = { + 'dtype': 'generic', + 'flatten': true +}; +var x = array( filledarrayBy( 10, opts.dtype, fill ), opts ); +var y = array( filledarrayBy( 10, opts.dtype, fill ), opts ); + +// Create an explicit binary function: +var f = naryFunction( add, 2 ); + +// Compute element-wise sums... +var z = map2( x, y, f ); + +console.log( 'x:' ); +console.log( x.data ); + +console.log( 'y:' ); +console.log( y.data ); + +console.log( 'z:' ); +console.log( z.data ); diff --git a/pool/shard001/JavaScript/0006717_homepage.spec.js b/pool/shard001/JavaScript/0006717_homepage.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..b40f91f83811033e899d12da217edb6a7af0be1e --- /dev/null +++ b/pool/shard001/JavaScript/0006717_homepage.spec.js @@ -0,0 +1,30 @@ +import Homepage from '@pages/index.vue' + +describe('Homepage', () => { + let wrapper + let options + + beforeEach(() => { + options = { + mocks: { + $homepageRedirect() {}, + }, + } + + wrapper = createWrapper(Homepage, options) + }) + + it('should be a Vue instance', () => { + expect(wrapper.exists()).toBeTruthy() + }) + + it('render an empty string', () => { + process.server = true + + wrapper = createWrapper(Homepage, { + ...options, + }) + + expect(wrapper).toMatchSnapshot() + }) +}) diff --git a/pool/shard001/JavaScript/0006718_App.test.js b/pool/shard001/JavaScript/0006718_App.test.js new file mode 100644 index 0000000000000000000000000000000000000000..b50a2a7ce4cd52a26b26c3c3cddc3703383da0b2 --- /dev/null +++ b/pool/shard001/JavaScript/0006718_App.test.js @@ -0,0 +1,20 @@ +import * as React from 'react'; +import ReactDOM from 'react-dom'; +import { Provider } from 'react-redux'; +import { createStore } from 'redux'; +import AppContainer from './AppContainer'; +import { initialState } from './Store/initialState'; + +it('renders without crashing', () => { + let store = createStore(function(state) { + return state; + }, initialState); + + const div = document.createElement('div'); + ReactDOM.render( + + + , + div, + ); +}); diff --git a/pool/shard001/JavaScript/0006728_IndexingConfig.js b/pool/shard001/JavaScript/0006728_IndexingConfig.js new file mode 100644 index 0000000000000000000000000000000000000000..c8410c7e49ec063e87473b8fe950486d24e764e5 --- /dev/null +++ b/pool/shard001/JavaScript/0006728_IndexingConfig.js @@ -0,0 +1,74 @@ +import squel from 'squel'; + +import { addBacktick, getIndexedValue } from '../utils/StringDecorator'; + +export default class IndexingConfig { + config; + + constructor(config) { + this.config = config; + } + + get field() { + return this.config.field; + } + + get method() { + return this.config.method; + } + + get interval() { + return this.config.interval; + } + + get categoryRange() { + return this.config.categoryRange; + } + + static build(table, aggregating, indexings, segment) { + const aggregatingString = addBacktick(aggregating.field); + + const query = squel + .select(); + + let isAggregatingGrouping = false; + + indexings.forEach((indexing, index) => { + const isNeedGrouping = (!indexing.method || (indexing.method && indexing.method.match(/each/))) && aggregating.method === 'count'; + + const indexedField = addBacktick(getIndexedValue(index)); + + if (indexing.method && !indexing.method.match(/each/)) { + const method = indexing.method.toUpperCase(); + + query.field(`${method}(${indexedField})`, getIndexedValue(index)); + } else { + query.field(indexedField); + } + + if (segment && isNeedGrouping && segment !== aggregating.field && !indexings.find(i => i.field === segment)) { + query.field(`GROUP_CONCAT(${addBacktick(segment)})`, 'segment_ids'); + } else if (segment) { + query.field(addBacktick(segment), 'segment_ids'); + } + + if (isNeedGrouping) { + isAggregatingGrouping = true; + + query.group(addBacktick(getIndexedValue(index))); + } else if (indexing.method) { + isAggregatingGrouping = true; + } + }); + + if (isAggregatingGrouping) { + query.group(aggregatingString); + } + + query.field(aggregatingString); + + query.from(table, 'matching_table'); + + return query; + } +} diff --git a/pool/shard001/JavaScript/0006729_runfromjson.js b/pool/shard001/JavaScript/0006729_runfromjson.js new file mode 100644 index 0000000000000000000000000000000000000000..2e68cc2f080fff69b20f193fecb223a8239f092e --- /dev/null +++ b/pool/shard001/JavaScript/0006729_runfromjson.js @@ -0,0 +1,29 @@ +// Generated by CoffeeScript 1.9.1 +var protodef, util, + hasProp = {}.hasOwnProperty; + +protodef = require('rethinkdb/proto-def'); + +util = require('rethinkdb/util'); + +module.exports = function(conn, query, cb, opts) { + var key, token, value; + opts = opts || {}; + token = conn.nextToken++; + conn.outstandingCallbacks[token] = { + opts: opts, + cb: cb + }; + query = { + global_optargs: {}, + type: protodef.Query.QueryType.START, + query: query, + token: token + }; + for (key in opts) { + if (!hasProp.call(opts, key)) continue; + value = opts[key]; + query.global_optargs[util.fromCamelCase(key)] = r.expr(value).build(); + } + return conn._sendQuery(query); +}; diff --git a/pool/shard001/JavaScript/0006730_webpack.config.js b/pool/shard001/JavaScript/0006730_webpack.config.js new file mode 100644 index 0000000000000000000000000000000000000000..29695a18dbd65b9916c278dcc51b6f3c2501de46 --- /dev/null +++ b/pool/shard001/JavaScript/0006730_webpack.config.js @@ -0,0 +1,26 @@ +/* eslint no-param-reassign: 0 */ +// Export a function instead of an object, the function will accept the base config: +module.exports = storybookConfig => { + if (process.env.NODE_ENV !== 'production') { + storybookConfig.plugins = storybookConfig.plugins.filter( + plugin => !/uglifyjs/i.test(plugin.constructor.name), // filter out UglifyJS + ); + } + + storybookConfig.module.rules.push( + { + test: /\.css$/, + use: ['style-loader', 'css-loader'], + }, + { + test: /\.md$/, + use: 'raw-loader', + }, // eslint-disable-line comma-dangle + ); + + storybookConfig.node = { + fs: 'empty', + }; + + return storybookConfig; +}; diff --git a/pool/shard001/JavaScript/0006731_userList.js b/pool/shard001/JavaScript/0006731_userList.js new file mode 100644 index 0000000000000000000000000000000000000000..420c3ca581e05a34c3cf44396bb444611f449790 --- /dev/null +++ b/pool/shard001/JavaScript/0006731_userList.js @@ -0,0 +1,95 @@ +(function($) { + "use strict"; + + $(document).ready(function() { + var $root = $("#admin-group-user-list-page"); + var groupId = $root.attr("data-group-id") + var $inputAutocomplete = $root.find("#user-add-form input[name=user]"); + var notification = window.services.notification; + + $inputAutocomplete.attr("autocomplete", "off"); + + $root.find("[data-action=delete]").ConfirmModal({ + title: __("Delete confirmation"), + message: __("Are you sure want to delete this user?"), + confirmBtn: { + "class": "btn btn-danger", + "text": ' '+__("Delete") + } + }); + + /** + * @see https://gist.github.com/tacone/4534615 + */ + function serializeForBootstrap(user) { + + var text = ""; + + if (user.firstname || user.lastname) { + text += user.firstname + " " + user.lastname + " - "; + } + + text += user.email; + + return { + // attributes + id: user.id, + firstname: user.firstname, + lastname: user.lastname, + email: user.email, + + text: text, + + // these functions allows Bootstrap typehead to use this item in places where it was expecting a string + toString: function() { + return JSON.stringify(this); + }, + toLowerCase: function() { + return this.text.toLowerCase(); + }, + indexOf: function(string) { + return String.prototype.indexOf.apply(this.text, arguments); + }, + replace: function(string) { + return String.prototype.replace.apply(this.text, arguments); + } + }; + } + + $inputAutocomplete.typeahead({ + minLength: 3, + // le trie est faite par api + sorter: function(items) { + return items; + }, + // tous les résultats renvoyés par api match la requête + matcher: function() { + return true; + }, + source: function(query, process) { + $.ajax(Routing.generate("admin_group_user_autocomplete", {"group" : groupId}), { + data: {keyword: query} + }) + .done(function(items) { + var data = []; + + for (var i = 0; i < items.length; i++) { + data.push(serializeForBootstrap(items[i])); + } + + process(data); + }); + }, + updater: function(item) { + var item = JSON.parse(item); + + $inputAutocomplete.val(item.id); + notification.loading(); + + $inputAutocomplete.closest("form").submit(); + + return item.email; + } + }); + }); +})(jQuery); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006734_master.js b/pool/shard001/JavaScript/0006734_master.js new file mode 100644 index 0000000000000000000000000000000000000000..8a56947bc6fa22ea15fdc7f9e2f7cafcf82469d6 --- /dev/null +++ b/pool/shard001/JavaScript/0006734_master.js @@ -0,0 +1,268 @@ +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Master = void 0; +const markdown_to_html_1 = require("@bldr/markdown-to-html"); +const core_browser_1 = require("@bldr/core-browser"); +/** + * The icon of a master slide. This icon is shown in the documentation or + * on the left corner of a slide. + */ +class MasterIcon { + constructor({ name, color, size, showOnSlides }) { + if (size != null && !['small', 'large'].includes(size)) { + throw new Error(`The property “size” of the “MasterIcon” has to be “small” or “large” not ${size}`); + } + this.name = name; + this.color = color != null ? color : 'orange'; + this.showOnSlides = showOnSlides !== false; + this.size = size != null ? size : 'small'; + } +} +/** + * Each master slide has an instance of this class. + */ +class Master { + /** + * @param spec - The specification of the master slide provided by a master + * package. + */ + constructor(spec) { + this.spec = spec; + this.icon = new MasterIcon(spec.icon); + } + get name() { + return this.spec.name; + } + get title() { + return this.spec.title; + } + get propNamesInlineMedia() { + const inlineMarkupProps = []; + for (const propName in this.spec.propsDef) { + const propDef = this.spec.propsDef[propName]; + if (propDef.inlineMarkup != null && propDef.inlineMarkup) { + inlineMarkupProps.push(propName); + } + } + return inlineMarkupProps; + } + /** + * Filter the master props for props which are supporting inline media. + */ + // extractInlineMediaUris (props: LampTypes.StringIndexedData): Set { + // const uris = new Set() + // function extractUrisInText (text: string) { + // const matches = text.matchAll(new RegExp(inlineMarkup.regExp, 'g')) + // for (const match of matches) { + // // 12 3 4 + // // [((id):(Fuer-Elise))( caption="Für Elise")] + // if (match[2] === 'id') uris.add(match[1]) + // } + // } + // for (const propName of this.propNamesInlineMedia) { + // const prop = props[propName] + // if (prop) { + // if (typeof prop === 'string') { + // extractUrisInText(prop) + // // `markup` in `generic` is an array. + // } else if (Array.isArray(prop)) { + // for (const item of prop) { + // extractUrisInText(item) + // } + // } + // } + // } + // return uris + // } + /** + * Replace the inline media tags `[id:Beethoven]` in certain props with + * HTML. This function must be called after the media resolution. + */ + // renderInlineMedia (props: LampTypes.StringIndexedData) { + // /** + // * @param {String} text + // */ + // function renderOneMediaUri (text) { + // return text.replace(new RegExp(inlineMarkup.regExp, 'g'), function (match) { + // const item = new inlineMarkup.Item(match) + // return inlineMarkup.render(item) + // }) + // } + // for (const propName of this.propNamesInlineMedia) { + // const prop = props[propName] + // if (prop) { + // if (typeof prop === 'string') { + // props[propName] = renderOneMediaUri(prop) + // // `markup` in `generic` is an array. + // } else if (Array.isArray(prop)) { + // for (let i = 0; i < prop.length; i++) { + // props[propName][i] = renderOneMediaUri(prop[i]) + // } + // } + // } + // } + // } + convertMarkdownToHtml(props) { + if (this.spec.propsDef == null) { + return props; + } + for (const propName in props) { + const prop = this.spec.propsDef[propName]; + if (prop.markup != null && prop.markup) { + props[propName] = markdown_to_html_1.convertMarkdownToHtml(props[propName]); + } + } + return props; + } + detectUnkownProps(props) { + for (const propName in props) { + if ((this.spec.propsDef != null) && !(propName in this.spec.propsDef)) { + throw new Error(`The master slide “${this.name}” has no property named “${propName}”.`); + } + } + } + validateUris(props) { + if (this.spec.propsDef == null) { + return props; + } + for (const propName in props) { + const prop = this.spec.propsDef[propName]; + if (prop.assetUri != null) { + props[propName] = core_browser_1.validateUri(props[propName]); + } + } + return props; + } + /** + * Call a master hook. Master hooks are definied in the `main.js` + * files. + * + * @param hookName - The name of the master hook / function. + * @param payload - The argument the master hook / function is called + * with. + */ + callHook(hookName, payload, thisArg) { + // eslint-disable-next-line + if ((this.spec.hooks != null) && this.spec.hooks[hookName] != null && typeof this.spec.hooks[hookName] === 'function') { + if (thisArg != null) { + return this.spec.hooks[hookName].call(thisArg, payload); + } + return this.spec.hooks[hookName](payload); + } + } + /** + * Asynchronous version. Call a master hook. Master hooks are definied in the + * `main.js` files. + * + * @param hookName - The name of the master hook / function. + * @param payload - The argument the master hook / function is called + * with. + */ + callHookAsync(hookName, payload, thisArg) { + return __awaiter(this, void 0, void 0, function* () { + // eslint-disable-next-line + if (this.spec.hooks != null && this.spec.hooks[hookName] != null && typeof this.spec.hooks[hookName] === 'function') { + if (thisArg != null) { + return this.spec.hooks[hookName].call(thisArg, payload); + } + return this.spec.hooks[hookName](payload); + } + }); + } + normalizeProps(propsRaw) { + return this.callHook('normalizeProps', propsRaw); + } + normalizeUris(uris) { + let normalizedUris; + // To allow undefined return values of the hooks. + if (uris == null) { + normalizedUris = new Set(); + } + else if (typeof uris === 'string') { + normalizedUris = new Set([uris]); + } + else if (Array.isArray(uris)) { + normalizedUris = new Set(uris); + } + else { + normalizedUris = null; + } + if (normalizedUris != null && normalizedUris.size > 0) { + return normalizedUris; + } + } + resolveMediaUris(props) { + const uris = this.callHook('resolveMediaUris', props); + // const inlineUris = this.extractInlineMediaUris(props) + // for (const uri of inlineUris) { + // uris.add(uri) + // } + return this.normalizeUris(uris); + } + resolveOptionalMediaUris(props) { + const uris = this.callHook('resolveOptionalMediaUris', props); + return this.normalizeUris(uris); + } + afterLoading(props, thisArg) { + this.callHook('afterLoading', { props, master: this }, thisArg); + } + afterMediaResolution(props, thisArg) { + return __awaiter(this, void 0, void 0, function* () { + yield this.callHookAsync('afterMediaResolution', { props, master: this }, thisArg); + }); + } + collectPropsMain(props, thisArg) { + const propsMain = this.callHook('collectPropsMain', props, thisArg); + if (propsMain != null) { + return propsMain; + } + return props; + } + collectPropsPreview(payload, thisArg) { + const propsPreview = this.callHook('collectPropsPreview', payload, thisArg); + if (propsPreview != null) { + return propsPreview; + } + if (payload.propsMain != null) { + return payload.propsMain; + } + return payload.props; + } + calculateStepCount(payload, thisArg) { + return this.callHook('calculateStepCount', payload, thisArg); + } + titleFromProps(payload) { + return this.callHook('titleFromProps', payload); + } + plainTextFromProps(props) { + return this.callHook('plainTextFromProps', props); + } + leaveSlide(payload, thisArg) { + this.callHook('leaveSlide', payload, thisArg); + } + enterSlide(payload, thisArg) { + this.callHook('enterSlide', payload, thisArg); + } + afterSlideNoChangeOnComponent(payload, thisArg) { + this.callHook('afterSlideNoChangeOnComponent', payload, thisArg); + } + leaveStep(payload, thisArg) { + return this.callHook('leaveStep', payload, thisArg); + } + enterStep(payload, thisArg) { + return this.callHook('enterStep', payload, thisArg); + } + afterStepNoChangeOnComponent(payload, thisArg) { + this.callHook('afterStepNoChangeOnComponent', payload, thisArg); + } +} +exports.Master = Master; diff --git a/pool/shard001/JavaScript/0006738_validators.js b/pool/shard001/JavaScript/0006738_validators.js new file mode 100644 index 0000000000000000000000000000000000000000..06e2e18c005b70a5e60785aa90cf6b41a83b3816 --- /dev/null +++ b/pool/shard001/JavaScript/0006738_validators.js @@ -0,0 +1,151 @@ +/** + * A set of validators to use with connectForm. All the validators here + * are meant to be used with `combineValidators. + * + * @module higherform + */ + +import invariant from 'invariant'; + +export function context(data) { + const errors = []; + + return { + addViolation: function (err) { + errors.push(err); + }, + + hasViolations: function () { + return errors.length > 0; + }, + + getViolations: function () { + return errors; + }, + + data, + }; +} + +/** + * A vaidation context implementation that only returns the values given. + * + * This is used by complex fields to do validation on their individual pieces. + * + */ +export function stubContext(hasViolations, violations) { + return { + addViolation: function () { + // noop, only here to conform to the interface + }, + + hasViolations: function () { + return hasViolations; + }, + + getViolations: function () { + return violations; + } + }; +} + +export function ensureMessage(message, defaultMessage) { + if (!message) { + message = defaultMessage; + } + invariant( + typeof message === 'string' || typeof message === 'function', + 'Validator messages must be strings or functions' + ); + + return message; +} + +export function toViolation(message, value, ...args) { + return typeof message === 'function' ? message(value, ...args) : message; +} + +/** + * Errors the field if the value is falsy (empty). + * + * @param {string|undefined} message The message to show if the validator fails + * @return {function} + */ +export function required(message) { + let msg = ensureMessage(message, 'This field is required.'); + + return function (value, ctx) { + if (!value) { + ctx.addViolation(toViolation(msg, value)); + } + }; +} + +/** + * Errors the field if the value is not one of the provided values. + * + * @param {array} values The allowed values. + * @param {string|undefined} message the message to show if the validator fails + * @return {function} + */ +export function oneOf(values, message) { + invariant(Array.isArray(values), 'values must be an array'); + let msg = ensureMessage(message, `Must be one of the following values: ${values.join(', ')}`); + + return function (value, ctx) { + if (values.indexOf(value) === -1) { + ctx.addViolation(toViolation(msg, value, values)); + } + }; +} + +/** + * Errors the field if the value doesn't match the pattern. + * + * @param {RegExp} pattern the pattern to check agains + * @param {string} message The message to show if the validator fails. + * @return {function} + */ +export function matches(pattern, message) { + invariant(pattern instanceof RegExp, 'pattern must be a RegExp'); + let msg = ensureMessage(message, 'This value is not valid.'); + + return function (value, ctx) { + if (!pattern.test(value)) { + ctx.addViolation(toViolation(msg, value, pattern)); + } + }; +} + +/** + * Applies all the validators to the value. Every validator will be applied. + * + * @param {function[]} validators The validators to apply. + * @return {function} + */ +export function chain(...validators) { + invariant(validators.length > 0, 'chain requires at least one validator'); + + return function (value, ctx) { + validators.forEach(v => v(value, ctx)); + }; +} + +/** + * Like `chain`, but stops after one validator fails. + * + * @param {function[]} validators The validators to apply + * @return {function} + */ +export function shortChain(...validators) { + invariant(validators.length > 0, 'shortChain requires at least one validator'); + + return function (value, ctx) { + for (let v of validators) { + v(value, ctx); + if (ctx.hasViolations()) { + break; + } + } + }; +} diff --git a/pool/shard001/JavaScript/0006739_find.js b/pool/shard001/JavaScript/0006739_find.js new file mode 100644 index 0000000000000000000000000000000000000000..01135e2e33313f9cec9fe35af107655ae33163e4 --- /dev/null +++ b/pool/shard001/JavaScript/0006739_find.js @@ -0,0 +1,66 @@ +/** + * @copyright + * The MIT License (MIT) + * + * Copyright (c) 2014 Cosmic Dynamo LLC + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * @module jazzHands.parser.match.find + */ +define([ + "dojo/_base/lang", + "blocks/promise/when", + "blocks/require" +], function (lang, when, require) { + /** + * This method will execute each of the input modules in order until one returns a success result + * @method jazzHands.parser.match#find + * @param {jazzHands.parser.Data | Array<*>} data - Information about the parsing process + * @param {Array} parsers - list of module ids or instances to be tried + * @param {Number} [idx ]- start index + * @return {Promise<*> | * | null} - Promise might be created if the module needs to be required in + */ + function find(data, parsers, idx) { + if (!lang.isArray(data)) { + data = [data]; + } + + idx = idx || 0; + if (idx >= parsers.length) { + return null; + } + function go(parse) { + var ready = parse.apply(null, data); + return when(ready, function (result) { + if (result !== null) { + return result; + } + return find(data, parsers, idx + 1); + }) + } + + var parser = parsers[idx]; + if (lang.isString(parser)) { + return require([parser], go); + } + return go(parser); + } + + return find; +}); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006741_Jobs.js b/pool/shard001/JavaScript/0006741_Jobs.js new file mode 100644 index 0000000000000000000000000000000000000000..73e017387c81212152067dddc155fd5a7cf0bf12 --- /dev/null +++ b/pool/shard001/JavaScript/0006741_Jobs.js @@ -0,0 +1,119 @@ +/* + * Copyright (c) 2017, 2018 RockNSM. + * + * This file is part of RockNSM + * (see http://rocknsm.io). + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +import React, { Component } from 'react'; +import { Link } from 'react-router-dom'; +import {Card, CardHeader, CardBody, Table} from 'reactstrap'; + +class Jobs extends Component { + constructor() { + super(); + this.state = { + jobs: [], + entries: [], + urls: {}, + interval: null, + }; + + this.updateTable = this.updateTable.bind(this); + } + + updateTable() { + var Config = require('Config'); + + var statusApi = fetch( Config.serverUrl + '/jobs/' ) + .then(results => { + return results.json(); + }) + + var urlsApi = fetch( Config.serverUrl + '/urls/' ) + .then(results => { + return results.json(); + }) + + Promise.all([statusApi, urlsApi]).then( values => { + var jobs = values[0]; + var urls = values[1]; + + console.log(urls) + + jobs.sort(function(a,b) { return (a.time > b.time) }); + + this.setState({'jobs': jobs, 'urls': urls}); + + let entries = Object.entries(jobs).map((entry, index) => { + + return ( +
      + + + + + + + + ) + }) + + this.setState({'entries': entries}); + }) + } + + componentDidMount() { + this.interval = setInterval(this.updateTable, 1000); + } + + componentWillUnmount() { + clearInterval(this.interval); + } + + render() { + /* Use jQuery to retrieve job data */ + + return ( +
      + + +
      { index + 1 }{ entry[1].time }{ + + {entry[1].id.substring(0, 6)} + + }{ entry[1].query }{ entry[1].state }{ entry[1].id in urls ? Get PCAP : "Unavailable"}
      + + + + + + + + + + { this.state.entries } + +
      #Request TimeIDQueryStateURL
      + + +
      + ) + } +} + +export default Jobs; diff --git a/pool/shard001/JavaScript/0006742_orderActions.js b/pool/shard001/JavaScript/0006742_orderActions.js new file mode 100644 index 0000000000000000000000000000000000000000..ae2287eb3ac882cf8b4964f29dd969ff0d7e58c7 --- /dev/null +++ b/pool/shard001/JavaScript/0006742_orderActions.js @@ -0,0 +1,146 @@ +import { + FETCH_ORDER_STATUSES_REQUEST, + FETCH_ORDER_STATUSES_FAILURE, + FETCH_ORDER_STATUSES_SUCCESS, + + ADMIN_CHANGE_ORDER_REQUEST, + ADMIN_CHANGE_ORDER_FAILURE, + ADMIN_CHANGE_ORDER_SUCCESS, + + ORDER_REQUEST, + ORDER_FAILURE, + ORDER_SUCCESS, + + SET_ORDER_POINT, + CHANGE_ORDER_MESSAGE, + CLEAR_ORDER_DATA, +} from 'constants' +import { + parsePromiseJson, + checkStatus +} from 'helpers' +import { + apiMakeOrder, + apiFetchOrderStatuses, + apiAdminChangeOrder +} from 'api' + + +export const clearOrderData = () => ({ + type: CLEAR_ORDER_DATA +}); + +export const changeOrderMessage = payload => ({ + type: CHANGE_ORDER_MESSAGE, + payload +}); + +export const setOrderPoint = payload => ({ + type: SET_ORDER_POINT, + payload +}); + +export const fetchOrderStatuses = () => dispatch => { + dispatch({type: FETCH_ORDER_STATUSES_REQUEST}); + + apiFetchOrderStatuses() + .then(checkStatus) + .then(parsePromiseJson) + .then(res => { + if (!res.success) { + return dispatch({ + type: FETCH_ORDER_STATUSES_FAILURE, + payload: res.message + }); + } + + dispatch({ + type: FETCH_ORDER_STATUSES_SUCCESS, + payload: res.data + }) + }) + .catch(err => { + if (!err.response || !err.response.json) { + return dispatch({ + type: FETCH_ORDER_STATUSES_FAILURE, + payload: err.message || err + }); + } + + err.response.json().then(res => { + dispatch({ + type: FETCH_ORDER_STATUSES_FAILURE, + payload: res.message || res + }); + }) + }) +}; + +export const makeOrder = () => (dispatch, getState) => { + const { user, order, cities } = getState(); + let data = {}; + + if (!user.isAuthorized) { + const { email, name, phone } = user.info; + + data.user = {email, name, phone} + } + + if (!user.info.byDeliveryGuy) { + data.point = user.info.point && user.info.point.id || + cities.current && cities.current.point && cities.current.point.id || 1; + } else { + if (!data.user) { + data.user = {}; + } + + const address = user.info && user.info.address; + + data.user.address = { + ...address, + city: cities.current && cities.current.id + }; + } + + if (order.message) { + data.message = order.message; + } + + dispatch({type: ORDER_REQUEST}); + + apiMakeOrder(data) + .then(checkStatus) + .then(parsePromiseJson) + .then(res => { + if (!res.success) { + return dispatch({ + type: ORDER_FAILURE, + payload: res.message + }); + } + + dispatch({ + type: ORDER_SUCCESS, + payload: res.order + }) + }) + .catch(err => { + if (!err.response || !err.response.json) { + return dispatch({ + type: ORDER_FAILURE, + payload: err.message || err.messages || err + }); + } + + err.response.json().then(res => { + dispatch({ + type: ORDER_FAILURE, + payload: res.message || res + }); + }) + }) +}; + +export const setOrderError = payload => ({ + type: ORDER_FAILURE, payload +}); diff --git a/pool/shard001/JavaScript/0006743_pp.js b/pool/shard001/JavaScript/0006743_pp.js new file mode 100644 index 0000000000000000000000000000000000000000..65056521b38cfae3bce83279e0e8640ccd2048a5 --- /dev/null +++ b/pool/shard001/JavaScript/0006743_pp.js @@ -0,0 +1,25 @@ +/* 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/. */ + +define(function (require, exports, module) { + 'use strict'; + + var AuthErrors = require('lib/auth-errors'); + var LegalCopyView = require('views/legal_copy'); + var Template = require('stache!templates/pp'); + + var View = LegalCopyView.extend({ + className: 'pp', + copyUrl: '/legal/privacy', + events: { + 'click #fxa-pp-back': 'back', + 'keyup #fxa-pp-back': 'backOnEnter' + }, + fetchError: AuthErrors.toError('COULD_NOT_GET_PP'), + template: Template + }); + + module.exports = View; +}); + diff --git a/pool/shard001/JavaScript/0006748_colorpicker_test.js b/pool/shard001/JavaScript/0006748_colorpicker_test.js new file mode 100644 index 0000000000000000000000000000000000000000..26674cd0ff293eda66ff852dbef955c140e1e13c --- /dev/null +++ b/pool/shard001/JavaScript/0006748_colorpicker_test.js @@ -0,0 +1,110 @@ +if (typeof process !== "undefined") { + require("amd-loader"); + require("../../test/setup_paths"); +} + +var regex = require("./colorpicker_regex"); + +define(function(require, exports, module) { + var assert = require("assert"); + + module.exports = { + "test simple rgb": function(next) { + var res = regex.isRgb.exec("rgb(14, 235, 19)"); + + assert.equal(!!res, true); + assert.equal(res[1], "14"); + assert.equal(res[2], "235"); + assert.equal(res[3], "19"); + assert.equal(res[4], undefined); + + next(); + }, + "test simple rgba": function(next) { + var res = regex.isRgb.exec("rgba(14, 235, 19, .9)"); + + assert.equal(!!res, true); + assert.equal(res[1], "14"); + assert.equal(res[2], "235"); + assert.equal(res[3], "19"); + assert.equal(res[4], ", .9"); + + next(); + }, + "test rgba with transparancy over 1": function(next) { + var res = regex.isRgb.exec("rgba(14, 235, 19, 1.9)"); + + assert.equal(!!res, false); + + next(); + }, + "test rgb with values over 255": function(next) { + var res = regex.isRgb.exec("rgb(256, 19, 32)"); + + assert.equal(!!res, false); + + next(); + }, + "test hsl": function(next) { + var res = regex.isHsl.exec("hsl(14, 99%, 33%)"); + + assert.equal(!!res, true); + assert.equal(res[1], "14"); + assert.equal(res[2], "99"); + assert.equal(res[3], "33"); + assert.equal(res[4], undefined); + + next(); + }, + "test hsla": function(next) { + var res = regex.isHsl.exec("hsla(14, 99%, 33%, .7)"); + + assert.equal(!!res, true); + assert.equal(res[1], "14"); + assert.equal(res[2], "99"); + assert.equal(res[3], "33"); + assert.equal(res[4], ", .7"); + + next(); + }, + "test hsla positive transparancy": function(next) { + var res = regex.isHsl.exec("hsla(14, 99%, 33%, 3.7)"); + + assert.equal(!!res, false); + + next(); + }, + "test hsla values too high": function(next) { + var res = regex.isHsl.exec("hsla(201, 101%, 00000411%, 0.7)"); + + assert.equal(!!res, false); + + next(); + }, + "test hsla bullocks values": function(next) { + var res = regex.isHsl.exec("hsla(abc, def, geh, .9)"); + + assert.equal(!!res, false); + + next(); + }, + "test text colors": function(next) { + var res = regex.isColor.exec("white"); + + assert.equal(!!res, true); + + next(); + }, + "test text any string": function(next) { + var res = regex.isColor.exec("jan is cool"); + + assert.equal(!!res, false); + + next(); + } + }; +}); + +if (typeof module !== "undefined" && module === require.main) { + require("asyncjs").test.testcase(module.exports).exec(); +} \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006752_can.ejs.js b/pool/shard001/JavaScript/0006752_can.ejs.js new file mode 100644 index 0000000000000000000000000000000000000000..1670e68c8a60e2dcf42fcc414c4a74e26f9cbabb --- /dev/null +++ b/pool/shard001/JavaScript/0006752_can.ejs.js @@ -0,0 +1,196 @@ +/*! + * CanJS - 2.1.4 + * http://canjs.us/ + * Copyright (c) 2014 Bitovi + * Fri, 21 Nov 2014 22:25:59 GMT + * Licensed MIT + * Includes: can/view/ejs + * Download from: http://canjs.com + */ +(function(undefined) { + + // ## view/ejs/ejs.js + var __m1 = (function(can) { + // ## Helper methods + var extend = can.extend, + EJS = function(options) { + // Supports calling EJS without the constructor. + // This returns a function that renders the template. + if (this.constructor !== EJS) { + var ejs = new EJS(options); + return function(data, helpers) { + return ejs.render(data, helpers); + }; + } + // If we get a `function` directly, it probably is coming from + // a `steal`-packaged view. + if (typeof options === 'function') { + this.template = { + fn: options + }; + return; + } + // Set options on self. + extend(this, options); + this.template = this.scanner.scan(this.text, this.name); + }; + // Expose EJS via the `can` object. + can.EJS = EJS; + + EJS.prototype. + // ## Render + // Render a view object with data and helpers. + render = function(object, extraHelpers) { + object = object || {}; + return this.template.fn.call(object, object, new EJS.Helpers(object, extraHelpers || {})); + }; + extend(EJS.prototype, { + // ## Scanner + // Singleton scanner instance for parsing templates. See [scanner.js](scanner.html) + // for more information. + // ### Text + // #### Definitions + // * `outStart` - Wrapper start text for view function. + // * `outEnd` - Wrapper end text for view function. + // * `argNames` - Arguments passed into view function. + scanner: new can.view.Scanner({ + text: { + outStart: 'with(_VIEW) { with (_CONTEXT) {', + outEnd: "}}", + argNames: '_CONTEXT,_VIEW', + context: "this" + }, + // ### Tokens + // An ordered token registry for the scanner. Scanner makes evaluations + // based on which tags are considered opening/closing as well as escaped, etc. + tokens: [ + ["templateLeft", "<%%"], + ["templateRight", "%>"], + ["returnLeft", "<%=="], + ["escapeLeft", "<%="], + ["commentLeft", "<%#"], + ["left", "<%"], + ["right", "%>"], + ["returnRight", "%>"] + ], + // ### Helpers + helpers: [{ + // Regex to see if its a func like `()->`. + name: /\s*\(([\$\w]+)\)\s*->([^\n]*)/, + // Evaluate rocket syntax function with correct context. + fn: function(content) { + var quickFunc = /\s*\(([\$\w]+)\)\s*->([^\n]*)/, + parts = content.match(quickFunc); + + return "can.proxy(function(__){var " + parts[1] + "=can.$(__);" + parts[2] + "}, this);"; + } + } + ], + // ### transform + // Transforms the EJS template to add support for shared blocks. + // Essentially, this breaks up EJS tags into multiple EJS tags + // if they contained unmatched brackets. + // For example, this doesn't work: + // `<% if (1) { %><% if (1) { %> hi <% } } %>` + // ...without isolated EJS blocks: + // `<% if (1) { %><% if (1) { %> hi <% } %><% } %>` + // The result of transforming: + // `<% if (1) { %><% %><% if (1) { %><% %> hi <% } %><% } %>` + transform: function(source) { + return source.replace(/<%([\s\S]+?)%>/gm, function(whole, part) { + var brackets = [], + foundBracketPair, i; + // Look for brackets (for removing self-contained blocks) + part.replace(/[{}]/gm, function(bracket, offset) { + brackets.push([ + bracket, + offset + ]); + }); + // Remove bracket pairs from the list of replacements + do { + foundBracketPair = false; + for (i = brackets.length - 2; i >= 0; i--) { + if (brackets[i][0] === '{' && brackets[i + 1][0] === '}') { + brackets.splice(i, 2); + foundBracketPair = true; + break; + } + } + } while (foundBracketPair); + // Unmatched brackets found, inject EJS tags + if (brackets.length >= 2) { + var result = ['<%'], + bracket, last = 0; + for (i = 0; bracket = brackets[i]; i++) { + result.push(part.substring(last, last = bracket[1])); + if (bracket[0] === '{' && i < brackets.length - 1 || bracket[0] === '}' && i > 0) { + result.push(bracket[0] === '{' ? '{ %><% ' : ' %><% }'); + } else { + result.push(bracket[0]); + } + ++last; + } + result.push(part.substring(last), '%>'); + return result.join(''); + } + // Otherwise return the original + else { + return '<%' + part + '%>'; + } + }); + } + }) + }); + + // ## Helpers + // In your EJS view you can then call the helper on an element tag: + // `
      >
      ` + EJS.Helpers = function(data, extras) { + this._data = data; + this._extras = extras; + extend(this, extras); + }; + + EJS.Helpers.prototype = { + // List allows for live binding a can.List easily within a template. + list: function(list, cb) { + can.each(list, function(item, i) { + cb(item, i, list); + }); + }, + // `each` iterates through a enumerated source(such as can.List or array) + // and sets up live binding when possible. + each: function(list, cb) { + // Normal arrays don't get live updated + if (can.isArray(list)) { + this.list(list, cb); + } else { + can.view.lists(list, cb); + } + } + }; + // Registers options for a `steal` build. + can.view.register({ + suffix: 'ejs', + script: function(id, src) { + return 'can.EJS(function(_CONTEXT,_VIEW) { ' + new EJS({ + text: src, + name: id + }) + .template.out + ' })'; + }, + renderer: function(id, text) { + return EJS({ + text: text, + name: id + }); + } + }); + can.ejs.Helpers = EJS.Helpers; + + + return can; + })(window.can, undefined, undefined, undefined, undefined, undefined); + +})(); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006753_fly.js b/pool/shard001/JavaScript/0006753_fly.js new file mode 100644 index 0000000000000000000000000000000000000000..e7697f6c545da27dfacdbabcec423627732b0dd9 --- /dev/null +++ b/pool/shard001/JavaScript/0006753_fly.js @@ -0,0 +1,100 @@ +#!/usr/bin/env node + +var Liftoff = require('liftoff') + , interpret = require('interpret') + , v8flags = require('v8flags') + , semver = require('semver') + , cliPackage = require('../package') + , nopt = require('nopt'); + +var knownOptions = { + 'flightplan': String, + 'username': String, + 'debug': Boolean, + 'color': Boolean, + 'version': Boolean, + 'help': Boolean +}; + +var shortHands = { + 'f': ['--flightplan'], + 'u': ['--username'], + 'd': ['--debug'], + 'C': ['--no-color'], + 'v': ['--version'], + 'h': ['--help'] +}; + +var options = nopt(knownOptions, shortHands, process.argv, 2); + +if(options.help) { + console.log('\n' + + ' Usage: fly [task:]target [options]\n\n' + + ' Options:\n\n' + + ' -f, --flightplan path to flightplan\n' + + ' -u, --username user for connecting to remote hosts\n' + + ' -d, --debug enable debug mode\n' + + ' -C, --no-color disable color output\n' + + ' -v, --version output the version number\n' + + ' -h, --help output usage information\n' + ); + process.exit(1); +} + +if(options.version) { + console.log(cliPackage.version); + process.exit(1); +} + +var task = 'default'; +var target = options.argv.remain.length ? options.argv.remain[0] : null; + +if(target && target.indexOf(':') !== -1) { + target = target.split(':'); + task = target[0]; + target = target[1]; +} + +var cli = new Liftoff({ + name: 'flightplan', + processTitle: 'Flightplan', + configName: 'flightplan', + extensions: interpret.jsVariants, + v8flags: v8flags +}); + +cli.on('requireFail', function(name) { + console.error("Error: Unable to load module '" + name + "'"); + process.exit(1); +}); + +var invoke = function(env) { + if(!target) { + console.error('Error: No target specified'); + process.exit(1); + } + + if(!env.configPath) { + console.error('Error: ' + (options.flightplan || 'flightplan.js') + ' not found'); + process.exit(1); + } + + if(!env.modulePath) { + console.error('Error: Local flightplan package not found in ' + env.cwd); + process.exit(1); + } + + if(!semver.satisfies(env.modulePackage.version, '>=0.5.0')) { + console.error('Error: local flightplan package version should be >=0.5.0'); + process.exit(1); + } + + process.chdir(env.configBase); + require(env.configPath); + var instance = require(env.modulePath); + instance.run(task, target, options); +}; + +cli.launch({ + configPath: options.flightplan +}, invoke); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006754_args.js b/pool/shard001/JavaScript/0006754_args.js new file mode 100644 index 0000000000000000000000000000000000000000..f586a8b81f6523ddee41675ec2e270710880cb57 --- /dev/null +++ b/pool/shard001/JavaScript/0006754_args.js @@ -0,0 +1,167 @@ +/* jshint node: true, esversion: 6, asi: true */ +"use strict" + +var options = [ + "LIST", + "GET", + "CALL", + "SET", + "CREATE", + "DELETE", + "ASSOC" +] + +class Args { + constructor() { + this._option = null + this._fields = null + this._values = null + this._method = null + this._parameters = null + this._switches = [] + this._format = null + } + + list(parameter) { + this.setOption("list", parameter, null) + return this + } + + get(parameters) { + this.setOption("get", parameters, null) + return this + } + + call(method, parameters) { + this.setOption("call", parameters, method) + return this + } + + set(parameters) { + this.setOption("set", parameters, null) + return this + } + + create(parameters) { + this.setOption("create", parameters, null) + return this + } + + delete() { + this.setOption("delete", null, null) + return this + } + + assoc() { + this.setOption("assoc", null, null) + return this + } + + setOption(option, parameters, method) { + if (options.indexOf(option.toUpperCase()) === -1) + throw option + " is not a valid option" + + this._option = option + this._parameters = parameters + this._method = method + } + + /** + * @param {string} + * @param {string} + * @return {Args} + */ + switch(name, value) { + if (name.toUpperCase() == "FORMAT") + this._format = value + else + this._switches.push({name: name, value: value}) + return this + } + + /** + * Sets the class from given {object} + * + * @param {object} + * @return {void} + */ + fromObject(object) { + let parameters = object.parameters !== undefined ? object.parameters : null, + method = object.method !== undefined ? object.method : null + + this.setOption(object.option, parameters, method) + + if ((["LIST", "GET", "ASSOC"].indexOf(object.option.toUpperCase()) !== -1) && Array.isArray(object.switches)) { + object.switches.forEach(elem => { + this.switch(elem.name, elem.value) + }) + } + } + + /** + * Builds the command line + * + * @return {array} + */ + buildCommand() { + var command = [] + + var buildSwitches = () => { + this._switches.forEach(current => { + if (current.value === undefined || current.value === null) { + command.push('/' + current.name.toUpperCase()) + } else { + command.push('/' + current.name.toUpperCase() + ":" + current.value.toUpperCase()) + } + }) + if (this._format !== null) + command.push('/FORMAT:' + this._format.toUpperCase()) + } + + // Default option + if (options.indexOf(this._option.toUpperCase()) === -1) { + this._option = "list" + this._parameters = "full" + } + + command.push(this._option.toUpperCase()) + + // Building parameters according to option + switch(this._option.toUpperCase()) { + case "LIST": + command.push(this._parameters.toUpperCase()) // Only one of brief, full, instance, status, system, writable + buildSwitches() + break; + + case "GET": + if ( ! Array.isArray(this._parameters)) { + this._parameters = [this._parameters] + } + command.push(this._parameters.join(', ')) + buildSwitches() + break; + + case "CALL": + command.push(this._method) + /* falls through */ + case "SET": + case "CREATE": + var assigments = [] + this._parameters.forEach(param => { + assigments.push(param.var + '="' + param.val + '"') + }) + command.push(assigments.join(", ")) + break; + case "ASSOC": + buildSwitches() + break + } + + return command + } +} + + + + +module.exports = Args diff --git a/pool/shard001/JavaScript/0006756_index.js b/pool/shard001/JavaScript/0006756_index.js new file mode 100644 index 0000000000000000000000000000000000000000..36e8f19251c066234edacb794d938e376009031b --- /dev/null +++ b/pool/shard001/JavaScript/0006756_index.js @@ -0,0 +1,42 @@ +'use strict'; + +var fs = require('fs'); + +/** + * Test helpers + */ + +/** + * Compare buffer `a` to buffer `b`, and return true if they are equivalent. + * + * @param {Buffer} `a` + * @param {Buffer} `b` + * @return {Boolean} + */ + +exports.compareBuffers = function compareBuffers(buf1, buf2) { + if (!Buffer.isBuffer(buf1) || !Buffer.isBuffer(buf2)) { + return false; + } + if (buf1.length !== buf2.length) { + return false; + } + for (var i = 0; i < buf2.length; i++) { + if (buf1[i] !== buf2[i]) { + return false; + } + } + return true; +}; + +/** + * Compare filepath `a` to filepath `b`, and return true if they are equivalent. + * + * @param {String} `a` Filepath A + * @param {String} `b` Filepath B + * @return {Boolean} + */ + +exports.compareFiles = function compareFiles(a, b) { + return exports.compareBuffers(fs.readFileSync(a), fs.readFileSync(b)); +}; diff --git a/pool/shard001/JavaScript/0006757_Environment.js b/pool/shard001/JavaScript/0006757_Environment.js new file mode 100644 index 0000000000000000000000000000000000000000..216cce5665485bef8fd337e834ba6620cdeec5c5 --- /dev/null +++ b/pool/shard001/JavaScript/0006757_Environment.js @@ -0,0 +1,249 @@ +/* + * Copyright (C) 2017 Czech Technical University in Prague + * + * 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 . + */ +'use strict'; + +const React = require('react'); +const ReactDOM = require('react-dom'); +const TestUtils = require('react-addons-test-utils'); +const rewire = require('rewire'); + +const Actions = require('../../js/actions/Actions'); +const TestApp = require('./TestApp'); + +module.exports = { + + _currentRenderingResult: null, + + getCurrentRenderingResult: function () { + return this._currentRenderingResult; + }, + + /** + * Renders the specified component, wrapping it in a TestApp instance, which is used to initialize some required + * context data, e.g. i18n. + * @param component Component to render + * @return {*|!ReactComponent} The rendered component + */ + render: function (component) { + let type = component.type, + result = TestUtils.renderIntoDocument({component}), + renderedComponent = TestUtils.findRenderedComponentWithType(result, type); + this._currentRenderingResult = result; + if (renderedComponent.getWrappedInstance) { + let wrapped = renderedComponent.getWrappedInstance(); + return wrapped.getWrappedComponent && wrapped.getWrappedComponent() ? wrapped.getWrappedComponent() : wrapped; + } else { + return renderedComponent; + } + }, + + /** + * Renders the specified component into a table body, wrapping it all in a TestApp instance, which is used to + * initialize some required context data, e.g. i18n. + * + * This is useful for components representing table rows. + * @param component Component to render + * @return {*|!ReactComponent} The rendered component + */ + renderIntoTable: function (component) { + const type = component.type, + result = TestUtils.renderIntoDocument( + + {component} +
      +
      ), + renderedComponent = TestUtils.findRenderedComponentWithType(result, type); + this._currentRenderingResult = result; + if (renderedComponent.getWrappedInstance) { + return renderedComponent.getWrappedInstance(); + } else { + return renderedComponent; + } + }, + + /** + * Finds component with the specified text. + * @param root Root of the tree where the component is searched for + * @param component Component class + * @param text Component text + */ + getComponentByText: function (root, component, text) { + const components = TestUtils.scryRenderedComponentsWithType(root, component); + return this._getNodeByText(components, text, true); + }, + + _getNodeByText: function (components, text, strict) { + for (let i = 0, len = components.length; i < len; i++) { + const node = ReactDOM.findDOMNode(components[i]); + if (strict && node.textContent === text) { + return node; + } else if (!strict && node.textContent.indexOf(text) !== -1) { + return node; + } + } + return null; + }, + + /** + * Finds component with the specified text. + * + * This version searches components by tag, so it will catch also simple components like div. + * @param root Root of the tree where the component is searched for + * @param tag Tag name + * @param text Component text + */ + getComponentByTagAndText: function (root, tag, text) { + const components = TestUtils.scryRenderedDOMComponentsWithTag(root, tag); + return this._getNodeByText(components, text, true); + }, + + /** + * Finds component which contains the specified text. + * + * This version searches components by tag, so it will catch also simple components like div. + * @param root Root of the tree where the component is searched for + * @param tag Tag name + * @param text Text contained in the component's text content + */ + getComponentByTagAndContainedText: function (root, tag, text) { + const components = TestUtils.scryRenderedDOMComponentsWithTag(root, tag); + return this._getNodeByText(components, text, false); + }, + + mockFactors: function (investigation) { + const Factors = rewire('../../js/components/factor/Factors'), + GanttController = jasmine.createSpyObj('GanttController', ['init', 'setScale', 'expandSubtree', 'updateOccurrenceEvent']), + FactorRenderer = jasmine.createSpyObj('FactorRenderer', ['renderFactors']), + FactorJsonSerializer = jasmine.createSpyObj('FactorJsonSerializer', ['getFactorGraph', 'setGanttController']); + Factors.__set__('GanttController', GanttController); + Factors.__set__('FactorRenderer', FactorRenderer); + Factors.__set__('FactorJsonSerializer', FactorJsonSerializer); + investigation.__set__('Factors', Factors); + }, + + /** + * Creates a mock objects with the specified methods. + * + * The methods adhere to the builder pattern - they return the mock instance itself. + * @param reqMockMethods array of methods to mock + */ + mockRequestMethods: function (reqMockMethods) { + const reqMock = jasmine.createSpyObj('request', reqMockMethods); + for (let i = 0; i < reqMockMethods.length; i++) { + // All mock methods just return the instance to adhere to the builder pattern implemented by request + reqMock[reqMockMethods[i]].and.callFake(function () { + return reqMock; + }); + } + return reqMock; + }, + + /** + * Mocks the Logger, so that test console output is not polluted with log messages. + */ + mockLogger: function () { + return jasmine.createSpyObj('Logger', ['warn', 'log', 'error']); + }, + + /** + * Mocks the Gantt component and sets in as global variable to simulate its ordinary behaviour. + * + * Returns the mock for possible further use. + */ + mockGantt: function () { + const gantt = jasmine.createSpyObj('gantt', ['init', 'open', 'addTask', 'addLink', 'getChildren', 'attachEvent', 'clearAll', 'render', 'calculateDuration']); + gantt.config = { + links: {} + }; + gantt.templates = {}; + gantt.date = {}; + gantt.getChildren.and.callFake(() => { + return []; + }); + jasmine.getGlobal().gantt = gantt; + return gantt; + }, + + /** + * Returns true if the arrays are equal, i.e. they have the same size and contain the same elements. + */ + arraysEqual: function (a, b) { + if (a === b) return true; + if (!a || !b) return false; + if (a.length !== b.length) return false; + + for (let i = 0; i < a.length; ++i) { + if (a[i] !== b[i]) { + return false; + } + } + return true; + }, + + /** + * Binds store methods directly to actions to work around asynchronous processing of actions. + * @param actionName Name of the action + * @param store Store, the corresponding store method is found according to the usual onActionName scheme. + */ + bindActionsToStoreMethods: function (actionName, store) { + const fn = 'on' + actionName.charAt(0).toUpperCase() + actionName.substring(1); + // For some reason, it didn't suffice (in some cases) to pass the store[fn] as argument to callFake, so that's + // why the wrapping function is here + spyOn(Actions, actionName).and.callFake(function () { + store[fn].apply(store, arguments); + }); + }, + + /** + * Custom Jasmine matchers + */ + customMatchers: { + + toBeLexGreaterOrEqual: function (util, customEqualityTesters) { + return { + compare: function (actual, expected) { + if (expected === undefined) { + expected = ''; + } + const result = {}; + result.pass = actual.toUpperCase().localeCompare(expected.toUpperCase()) >= 0; + if (result.pass) { + result.message = 'Expected ' + actual + ' not to be lexicographically greater or equal to ' + expected; + } else { + result.message = 'Expected ' + actual + ' to be lexicographically greater or equal to ' + expected; + } + return result; + } + } + }, + toBeLexGreaterThan: function (util, customEqualityTesters) { + return { + compare: function (actual, expected) { + if (expected === undefined) { + expected = ''; + } + const result = {}; + result.pass = actual.toUpperCase().localeCompare(expected.toUpperCase()) > 0; + if (result.pass) { + result.message = 'Expected ' + actual + ' not to be lexicographically greater than ' + expected; + } else { + result.message = 'Expected ' + actual + ' to be lexicographically greater than ' + expected; + } + return result; + } + } + } + } +}; diff --git a/pool/shard001/JavaScript/0006758_testing.js b/pool/shard001/JavaScript/0006758_testing.js new file mode 100644 index 0000000000000000000000000000000000000000..50cfa4cd90576663559d9616f8c122c355cadf18 --- /dev/null +++ b/pool/shard001/JavaScript/0006758_testing.js @@ -0,0 +1,74 @@ +'use strict'; +/* +We can use tls module to get the certificate. All the needed data is inthere, just need get it and work with it. + +http://stackoverflow.com/questions/14599901/read-expiration-date-and-common-name-from-ssl-certificate-using-node-js +Loop through array: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in + +require('tls'); +var cn = tls.connect(443, "www.surveysage.com"); +// the cert is in json form +var cert = cn.getPeerCertifiacte; +var san = cert.subjectaltname.split(','); +// trim leading space up and remove the 'DNS:' prefix +for (var item in san) { + san[item] = san[item].trim(); + san[item] = san[item].substr(4); +} +*/ + +const certf = require('./cert'); +certf.getCert('tlswatch.com', function (err, cert) { + // look for error types, if (err & err.type == 'no cert, invalid domain') + // invalid domain seems to throw an exception + if (err) { + console.error('Error retrieving certificate:\n', err); + return; + } + + console.log('cert:\n', cert.subject); + //mongo(cert); +}); + +return; + + +function mongo(cert) { + var MongoClient = require('mongodb').MongoClient; + var assert = require('assert'); + var mongovar = require('./mongodb.env'); + var uri = mongovar.mongodb.uri; + //console.log('values:\n', uri); + + var insertCertificate = function (db, callback) { + var collection = db.collection('certificate'); + collection.insert(cert, function(err, result) { + assert.equal(err, null); + assert.equal(1, result.result.n); + assert.equal(1, result.ops.length); + console.log('Inserted the certificate into the database'); + callback(result); + }); + } + + var findCertificate = function(db, callback) { + var collection = db.collection('certificate'); + collection.find({}).toArray(function(err, certs) { + assert.equal(err, null); + console.log('Found the following certs'); + console.log(certs); + callback(certs); + }) + } + + MongoClient.connect(uri, function(err, db) { + assert.equal(null, err); + console.log('Connected successfully to server'); + + insertCertificate(db, function() { + findCertificate(db, function() { + db.close(); + }); + }); + }); +} diff --git a/pool/shard001/JavaScript/0006761_group.js b/pool/shard001/JavaScript/0006761_group.js new file mode 100644 index 0000000000000000000000000000000000000000..007bc2e822b82eee7d2e6e6669d7a0d02939224f --- /dev/null +++ b/pool/shard001/JavaScript/0006761_group.js @@ -0,0 +1,18 @@ +var app = require('../../server/server'); + +module.exports = function(Group) { + Group.handleChangeError = function(err) { + console.warn('Cannot update change records for Group: ', err); + }; + + // Create a matching storage container with each new group instance + Group.observe('before save', function(ctx, next) { + if(ctx.isNewInstance) + { + var group = ctx.instance.toJSON(); + app.models.storage.createContainer({name: group.name}, function(err, container) { + }); + } + next(); + }); +}; diff --git a/pool/shard001/JavaScript/0006763_needles.js b/pool/shard001/JavaScript/0006763_needles.js new file mode 100644 index 0000000000000000000000000000000000000000..813e689842a6c614c1b10c13975cb231131f029b --- /dev/null +++ b/pool/shard001/JavaScript/0006763_needles.js @@ -0,0 +1,81 @@ + +var activeConfig = 1; +var totalConfigs = 100; +var offsetX = 25; +var offsetY = 30; +var numHor; +var numVert; +var from = new Point(0,0); +var to; +var count; +var thickness = 40; +generate(); + +function generate(){ + if (activeConfig==1){ + thickness = 25; + numHor = 11; + numVert = 5; + to = [40, 40]; + color = '#ea5a41'; + } + else if (activeConfig>1){ + thickness = Math.floor((Math.random() * 26)) + numHor = Math.floor((Math.random() * 20) + 10); + numVert = Math.floor((Math.random() * 15) + 5); + var bracket = Math.floor(Math.random*3) + if (bracket > 2){ + var x = Math.floor((Math.random() * 800)); + var y = Math.floor((Math.random() * 1000)); + } else if (bracket > 1){ + var x = Math.floor((Math.random() * 400)); + var y = Math.floor((Math.random() * 300)); + } else { + var x = Math.floor((Math.random() * 100)+2); + var y = Math.floor((Math.random() * 100)+2); + } + to = (x, y); + var redRandom = Math.random() + var blueRandom = Math.random() + var greenRandom = Math.random() + color = new Color(redRandom, greenRandom, blueRandom, 1); + } + count = numHor * numVert; + var line = new Path.Line(from, to); + line.style = {strokeColor : color, strokeWidth : thickness, strokeCap : 'round'}; + var symbol = new Symbol(line); + for (var i = 0; i< numHor; i++){ + for (var j = 0; j< numVert; j++){ + var instance = symbol.place(); + instance.position.x = (view.size.width-offsetX)/numHor * i + view.size.width/40 + offsetX; + instance.position.y = (view.size.height-offsetY)/numVert * j + view.size.height/20 + offsetY; + } + } +} +function onMouseMove(event){ + for (var i = 0; i < count; i++) { + var item = project.activeLayer.children[i]; + var vector = event.point - item.position; + var prevVector = event.lastPoint - item.position; + item.rotate(vector.angle-prevVector.angle, item.position); + } +} +//kinda cool but not what I want +// function onResize(){ +// for (var i = 0; i < count; i++) { +// var item = project.activeLayer.children[i]; +// item.position.y = view.size.width/numVert * i/numHor + 30 +// } +// } +// function onMouseDown(event) { +// activeConfig++; +// if (activeConfig>totalConfigs){ +// activeConfig = 1; +// } +// project.activeLayer.removeChildren(); +// generate(); +// } +// function onResize(event){ +// project.activeLayer.removeChildren(); +// generate(); +// } diff --git a/pool/shard001/JavaScript/0006766_lazyest-slideshow.dev.js b/pool/shard001/JavaScript/0006766_lazyest-slideshow.dev.js new file mode 100644 index 0000000000000000000000000000000000000000..af862fc9900b88ceb0bf6914eb6a96e2b27f0fcb --- /dev/null +++ b/pool/shard001/JavaScript/0006766_lazyest-slideshow.dev.js @@ -0,0 +1,78 @@ +/* + jQuery slideshow for Lazyest Gallery + copyright 2009-2010 Marcel Brinkkemper + version 1.1 + */ + +function lg_js_slideshow() { + jQuery('.lg_loading').each( function() { + jQuery(this).hide(); + }); + jQuery('.lg_slideshow').each( function() { + jQuery(this).children('a').css({opacity: 0.0}); + jQuery(this).children('a').css({visibility: 'visible'}); + var maxWidth = 0; + var maxHeight = 0; + jQuery(this).children('a').each( function(index, object) { + var imgWidth = parseInt(jQuery(object).find('img:first').width()); + maxWidth = (imgWidth > maxWidth)? imgWidth : maxWidth; + var imgHeight = parseInt(jQuery(object).find('img:first').height()); + maxHeight = (imgHeight > maxHeight)? imgHeight : maxHeight; + }) + jQuery(this).css({width:maxWidth+'px', height:maxHeight+'px'}); + var first = jQuery(this).children('a:first'); + var firstImg = first.find('img'); + first.css({opacity: 1.0}); + var leftPad = ( maxWidth - parseInt( jQuery(this).children('a:first').find('img').width() ) ) / 2; + var bottomPad = ( maxHeight - parseInt( jQuery(this).children('a:first').find('img').height() ) ) / 2; + var caption = firstImg.attr('rel'); + if ( !caption ) caption = ''; + if ( caption == ' ' ) { caption = '' }; + first.css({opacity: 0.0}) + .addClass('show') + .animate({opacity: 1.0}, lazyestshow.slideview ) + .css({left: leftPad+'px', bottom:bottomPad+'px'}); + jQuery(this).children('.sscaption').animate({opacity: 0.0}, { queue:false, duration:0 }).animate({height: '0px'}, { queue:true, duration:lazyestshow.captionqueue }); + if ( jQuery(this).attr('id').match('lg_slideshow') && ( caption.length > 0 ) ) { + jQuery(this).children('.sscaption').css({ width: firstImg.width(), left: leftPad+'px', bottom:bottomPad+'px' }); + jQuery(this).children('.sscaption').animate({opacity: 0.7},lazyestshow.captionopcty ).animate({height: '100px'},lazyestshow.captionqueue ); + jQuery(this).children('.sscaption').html(caption); + } + }); + setInterval('lg_js_gallery_show()', lazyestshow.duration ); +} + +function lg_js_gallery_show() { + jQuery('.lg_slideshow').each( function() { + var current = jQuery(this).children('a.show'); + var next = ((current.next().length) ? ((current.next().hasClass('sscaption'))? jQuery(this).children('a:first') :current.next()) : jQuery(this).children('a:first')); + var nextImg = next.find('img'); + var leftPad = ( parseInt( jQuery(this).width() ) - parseInt( nextImg.width() ) ) / 2; + var bottomPad = ( parseInt( jQuery(this).height() ) - parseInt( nextImg.height() ) ) / 2; + var caption = nextImg.attr('rel'); + if ( !caption ) caption = ''; + if ( caption == ' ' ) { caption = '' }; + next.css({opacity: 0.0}) + .addClass('show') + .animate({opacity: 1.0}, lazyestshow.slideview ) + .css({left: leftPad+'px', bottom:bottomPad+'px'}); + current.animate({opacity: 0.0}, lazyestshow.slideview ) + .removeClass('show'); + jQuery(this).children('.sscaption').animate({opacity: 0.0}, { queue:false, duration:0 }).animate({height: '0px'}, { queue:true, duration:lazyestshow.captionqueue }); + if ( jQuery(this).attr('id').match('lg_slideshow') && ( caption.length > 0 ) ) { + jQuery(this).children('.sscaption').css({ width: nextImg.width(), left: leftPad+'px', bottom:bottomPad+'px' }); + jQuery(this).children('.sscaption').animate({opacity: 0.7},lazyestshow.captionopcty ).animate({height: '100px'},lazyestshow.captionqueue ); + jQuery(this).children('.sscaption').html(caption); + } + }); +} +var lazyest_slideshow = true; +var lazyestCounter = 0; + +jQuery(window).load(function() { + if(typeof(lazyest_loading) === 'undefined') { + if ( jQuery('.lg_slideshow').length ) { + lg_js_slideshow(); + } + } +}) ; diff --git a/pool/shard001/JavaScript/0006770_test.js b/pool/shard001/JavaScript/0006770_test.js new file mode 100644 index 0000000000000000000000000000000000000000..9a95a1f3feeaa35c135094a9e170911983494e67 --- /dev/null +++ b/pool/shard001/JavaScript/0006770_test.js @@ -0,0 +1,66 @@ +(function(){ + + + var conf = {}; + + var defaults = { + + }; + + var box = $('#box'); + var scene = $('#scene'); + conf = $.extend({}, defaults, conf); + + var data = []; + + for(var i = 0; i < 200; i++){ + data.push(i); + } + + var html = []; + data.forEach(function(text){ + html.push('
      ' + text + '
      '); + }); + scene.html(html.join('')); + + + var sceneLimitRange = 100; + var sceneWidth = 400; + + var getRandomDistance = function(){ + var distance = sceneWidth / 2 - Math.random() * sceneWidth; + distance = distance >= 0 ? distance + sceneLimitRange : distance - sceneLimitRange; + return distance; + }; + + $('.item').each(function(){ + var itemEl = $(this); + var childEl = itemEl.find('.text'); + + var x = getRandomDistance(); + var y = getRandomDistance(); + var z = getRandomDistance(); + + var rx = 360 * Math.random(); + var ry = 360 * Math.random(); + var rz = 360 * Math.random(); + + var r = Math.floor(100 + 155 * Math.random()); + var g = Math.floor(100 + 155 * Math.random()); + var b = Math.floor(100 + 155 * Math.random()); + + itemEl.transform({ + 'rotateX' : rx + 'deg', + 'rotateY' : ry + 'deg', + 'rotateZ' : rz + 'deg', + 'translateX' : x + 'px', + 'translateY' : y + 'px', + 'translateZ' : z + 'px' + }); + childEl.css({ + 'background' : 'rgba(' + r + ',' + g + ',' + b +',0.7)' + }); + }); + + +})(); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006774_popup.js b/pool/shard001/JavaScript/0006774_popup.js new file mode 100644 index 0000000000000000000000000000000000000000..791bc47dcf167064e0f3d37369925875432f42ef --- /dev/null +++ b/pool/shard001/JavaScript/0006774_popup.js @@ -0,0 +1,34 @@ +'use strict'; + +import Utility from './utility.js'; +import ViewModel from './viewModel.js'; + +function popup() { + var viewModel = new ViewModel(); + function onCalculateClick() { + viewModel.calculate(); + viewModel.save(); + return false; + } + function onResetClick() { + viewModel.resetToDefaults(); + viewModel.save(); + } + function setStartingInputs() { + if (viewModel.isLoaded) return; + viewModel.initialize(); + onCalculateClick(); + viewModel.isLoaded = true; + } + function init() { + setStartingInputs(); + var calculateButton = Utility.getElement('calculate'); + calculateButton.addEventListener('click', onCalculateClick, false); + var resetButton = Utility.getElement('reset'); + resetButton.addEventListener('click', onResetClick, false); + } + init(); +} + +export default popup(); + diff --git a/pool/shard001/JavaScript/0006778_CardHelpers.js b/pool/shard001/JavaScript/0006778_CardHelpers.js new file mode 100644 index 0000000000000000000000000000000000000000..c434c642ce653edde4ed604e4d5575ab919910e7 --- /dev/null +++ b/pool/shard001/JavaScript/0006778_CardHelpers.js @@ -0,0 +1,115 @@ +/* + * Copyright (C) 2013 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 . + */ + +.pragma library + +var components = ["title", "art", "subtitle", "mascot", "emblem", "summary", "attributes", "social-actions", "overlayColor", "quickPreviewData"] +var dataKeys = ["title", "art", "subtitle", "mascot", "emblem", "summary", "attributes", "socialActions", "overlayColor", "quickPreviewData"] + +var defaultLayout = ' \ +{ \ + "schema-version": 1, \ + "template": { \ + "category-layout": "grid", \ + "card-layout": "vertical", \ + "card-size": "medium", \ + "overlay-mode": null, \ + "collapsed-rows": 2 \ + }, \ + "components": { \ + "title": null, \ + "art": { \ + "aspect-ratio": 1.0 \ + }, \ + "subtitle": null, \ + "overlayColor": null, \ + "mascot": null, \ + "emblem": null, \ + "summary": null, \ + "attributes": { "max-count": 2 }, \ + "social-actions": null \ + }, \ + "resources": {} \ +}' + +var fullMapping = ' \ +{ \ + "title": "title", \ + "art": "art", \ + "subtitle": "subtitle", \ + "mascot": "mascot", \ + "emblem": "emblem", \ + "overlayColor": "overlayColor", \ + "summary": "summary", \ + "attributes": "attributes", \ + "social-actions": "socialActions" \ +}' + +function tryParse(json, errorLabel) { + var o = undefined; + if (errorLabel !== undefined) { + errorLabel.text = ""; + } + try { + o = JSON.parse(json) + } catch(err) { + if (errorLabel !== undefined) { + errorLabel.text = err + ""; + } else { + console.debug(err); + } + } + return o; +} + +function mapData(json, layout, errorLabel) { + var o = tryParse(json, errorLabel); + var d = undefined; + + if (o !== undefined) { + d = Object(); + for (var k in components) { + try { + if (typeof layout[components[k]] == "object") { + d[dataKeys[k]] = o[layout[components[k]]['field']]; + } else { + d[dataKeys[k]] = o[layout[components[k]]]; + } + } catch(err) { + d[dataKeys[k]] = undefined; + } + } + } + return d; +} + +function update(object, overrides) { + for (var k in overrides) { + if (typeof object[k] == "string" && typeof overrides[k] == "object") { + if (!overrides[k].hasOwnProperty('field')) overrides[k]['field'] = object[k]; + } + if (object[k] === null) { + object[k] = overrides[k]; + } else if (typeof object[k] == "object" && typeof overrides[k] == "string") { + object[k]['field'] = overrides[k]; + } else if (typeof object[k] == "object") { + update(object[k], overrides[k]); + } else { + object[k] = overrides[k]; + } + } + return object; +} diff --git a/pool/shard001/JavaScript/0006779_login-service-adaptor.service.js b/pool/shard001/JavaScript/0006779_login-service-adaptor.service.js new file mode 100644 index 0000000000000000000000000000000000000000..3a6e225be85c8f23139e188f6862a46238228b81 --- /dev/null +++ b/pool/shard001/JavaScript/0006779_login-service-adaptor.service.js @@ -0,0 +1,20 @@ +;(function () { + 'use strict' + + var ngModule = angular.module('eha.login-service-adaptor.service', [ + 'eha.login-service-adaptor-pouchdb.service' + ]) + + ngModule.service('ehaLoginServiceAdaptor', function ( + ehaLoginServiceAdaptorPouchDB + ) { + this.setItem = ehaLoginServiceAdaptorPouchDB.setItem + this.getItem = ehaLoginServiceAdaptorPouchDB.getItem + this.removeItem = ehaLoginServiceAdaptorPouchDB.removeItem + }) + + // Check for and export to commonjs environment + if (typeof module !== 'undefined' && module.exports) { + module.exports = ngModule + } +})() diff --git a/pool/shard001/JavaScript/0006780_app8.js b/pool/shard001/JavaScript/0006780_app8.js new file mode 100644 index 0000000000000000000000000000000000000000..bdc5d9cec1ab90c692ceae2f5812660b01541055 --- /dev/null +++ b/pool/shard001/JavaScript/0006780_app8.js @@ -0,0 +1,32 @@ +// +// Free Code Camp +// 8. Algorithms 2 (Intermediate) +// +// Created by Dulio Denis on 10/7/15. +// Copyright (c) 2015 ddApps. All rights reserved. +// ------------------------------------------------ +// Bonfire 8: Missing Letters +// http://www.freecodecamp.com/challenges/bonfire-missing-letters +// +// Find the missing letter in the passed letter range and return it. + + +var fearNotLetter = function(str) { + var alphabet = "abcdefghijklmnopqrstuvwxyz"; + + // determine where to start and end in the argument's range + var i = alphabet.indexOf(str[0]); + var j = alphabet.indexOf(str[str.length-1]); + + for (; i < j; i++) { + if (str.indexOf(alphabet[i]) == -1) return alphabet[i]; + } + return; // return undefined if no missing letter +} + +// Test Cases +var lettersMissing1 = fearNotLetter("abce"); +console.log("d = " +lettersMissing1); + +var lettersMissing2 = fearNotLetter("bcd"); +console.log("undefined = " +lettersMissing2); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006784_gulp.jslint.js b/pool/shard001/JavaScript/0006784_gulp.jslint.js new file mode 100644 index 0000000000000000000000000000000000000000..84c5172e1d75fa48fc9b3d7a8e1f0e4458421b41 --- /dev/null +++ b/pool/shard001/JavaScript/0006784_gulp.jslint.js @@ -0,0 +1,166 @@ +/** + * gulp.jslint.js + * Copyright (C) 2014 Karim Alibhai. + **/ + +(function () { + "use strict"; + + // load up colorful strings + require('colors'); + + var path = require('path'), + gutil = require('gulp-util'), + evtStr = require('event-stream'), + jslint = require('jslint'), + applyRC = function (options) { + var tmp = {}, + i; + + try { + // evil code helps get + // past jslint's hatred of + // synchronous node.js code + + /*jslint evil:true*/ + tmp = eval("JSON.parse(require('fs').readFileSync(path.resolve('.', '.jslintrc'), 'utf8'))"); + /*jslint evil:false*/ + } finally { + for (i in options) { + if (options.hasOwnProperty(i)) { + tmp[i] = options[i]; + } + } + + return tmp; + } + }, + JSLINT = null, + doLint = function (options) { + return function (src, fn) { + var retVal, js, + lint = function () { + var myRet; + + // prepare for linting exports + src.jslint = {}; + + // convert to string + js = src.contents.toString('utf8'); + + // check for shebang + if (js.substr(0, js.indexOf('\n')).match(/^#! ?/)) { + js = js.replace(js.split('\n', 1) + '\n', ''); + } + + // lint the file + src.jslint.edition = JSLINT.edition; + src.jslint.success = JSLINT(js, options); + src.jslint.errors = JSLINT.errors; + + // only support paths to reporter, or + // pre-loaded reporters + if (options.reporter !== 'default') { + try { + if (typeof options.reporter === 'string') { + options.reporter = require(options.reporter); + } else if (typeof options.reporter !== 'function') { + options.reporter = 'default'; + } + } catch (err_a) { + return fn(err_a); + } + } + + // load the default reporter + if (options.reporter === 'default') { + options.reporter = function (evt) { + var msg = ' ', + i; + + // shorten path + evt.file = evt.file.replace(path.join(path.resolve('./'), '/'), ''); + + // colorify + evt.file = evt.pass ? evt.file.green : evt.file.red; + + // print file name + msg += evt.file; + + // add reasons to errors + if (!evt.pass) { + for (i = 0; i < evt.errors.length; i += 1) { + if (evt.errors[i]) { + msg += ('\n ' + + evt.errors[i].line + ':' + + evt.errors[i].character + ': ' + + evt.errors[i].reason).red; + } + } + } + + // write to screen + if (!(evt.pass && options.errorsOnly)) { + gutil.log(msg); + } + }; + } + + // pass error handling onto reporter + options.reporter({ + pass: src.jslint.success, + file: src.path, + errors: JSLINT.errors + }); + + // decide where to go + if (src.jslint.success) { + myRet = fn(null, src); + } else { + myRet = fn(new gutil.PluginError('gulp-jslint', 'failed to lint ' + src.path)); + } + + return myRet; + }; + + if (src.isStream()) { + retVal = fn(new gutil.PluginError('gulp-jslint', 'bad input file ' + src.path)); + } else if (src.isNull()) { + retVal = fn(null, src); + } else { + if (JSLINT === null) { + JSLINT = jslint.load(options.edition); + } + + retVal = lint(); + } + + return retVal; + }; + }; + + module.exports = function (options) { + // fallback to empty object + options = options || {}; + + // extend .jslintrc; give options + // the priority for directives + options = applyRC(options); + + // set default reporter + options.reporter = options.reporter || 'default'; + + // force boolean + options.errorsOnly = options.hasOwnProperty('errorsOnly') && options.errorsOnly === true; + + // use 'global' for consistency + // prefer 'predef' because of JSLint + options.predef = options.predef || options.global || {}; + + // allow freezing of jslint edition + options.edition = options.edition || 'latest'; + + // begin linting + return evtStr.map(doLint(options)); + }; +}()); diff --git a/pool/shard001/JavaScript/0006786_ovi.js b/pool/shard001/JavaScript/0006786_ovi.js new file mode 100644 index 0000000000000000000000000000000000000000..b4b66039f3df746046a821052a3d746a97a038a5 --- /dev/null +++ b/pool/shard001/JavaScript/0006786_ovi.js @@ -0,0 +1,281 @@ +/* + * Copyright (c) 2013 Benjamin Michotte + * ProduWeb SA + * + * 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. + */ +/** + * OVI API provider + * http://api.maps.ovi.com + */ +jQuery.extend(jQuery.fn.pdwMap.providers, + { + ovi: { + _loadScripts: function(i) + { + var scripts = [ "http://api.maps.ovi.com/base.js", "http://api.maps.ovi.com/search-nokia.js", "http://api.maps.ovi.com/routing-nokia.js", + "http://api.maps.ovi.com/positioning-w3c.js", "http://api.maps.ovi.com/gfx-canvas.js", "http://api.maps.ovi.com/map-js-p2d-dom.js", + "http://api.maps.ovi.com/ui-ovi_web.js", "http://api.maps.ovi.com/language-fr-FR.js" ]; + + var script = document.createElement("script"); + script.setAttribute("type", "text/javascript"); + script.setAttribute("src", scripts[i]); + var $this = $(this); + script.onload = script.onreadystatechange = function() + { + if (script.readyState && script.readyState != "loaded" && script.readyState != "complete") + { + return; + } + script.onload = script.onreadystatechange = null; + + if (i == scripts.length - 1) + { + pdwMapInit(); + } + else + { + $this.pdwMap('_loadScripts', ++i); + } + }; + $(this).pdwMap('_appendScriptToHead', script); + }, + + loadScript: function() + { + var options = $(this).data('options'); + if (typeof options.apiKeys.oviAppId == "undefined" || typeof options.apiKeys.ovi == "undefined") + { + $.error("You need an app ID and authentication token for OVI"); + return; + } + + __pdw_map_loader = $(this); + var script = document.createElement("script"); + script.setAttribute("type", "text/javascript"); + script.setAttribute("src", "http://api.maps.ovi.com/jsl.js"); + var $this = $(this); + script.onload = script.onreadystatechange = function() + { + if (script.readyState && script.readyState != "loaded" && script.readyState != "complete") + { + return; + } + script.onload = script.onreadystatechange = null; + $this.pdwMap('_loadScripts', 0); + }; + $(this).pdwMap('_appendScriptToHead', script); + }, + + initProvider: function() + { + var options = $(this).data('options'); + + ovi.mapsapi.util.ApplicationContext.set({ + "appId": options.apiKeys.oviAppId, + "authenticationToken": options.apiKeys.ovi + }); + ovi.mapsapi.util.ApplicationContext.set("defaultLanguage", options.lang); + + var center = [ options.defaultPosition.lat, options.defaultPosition.lng ]; + if (options.browserGeoloc && navigator.geolocation) + { + navigator.geolocation.getCurrentPosition(function(position) + { + map.setCenter(new ovi.mapsapi.geo.Coordinate(position.coords.latitude, position.coords.longitude)); + }, + function() + { + }); + } + + var components = []; + if (!options.staticMap) + { + var infoBubbles = new ovi.mapsapi.map.component.InfoBubbles(); + components = [ + new ovi.mapsapi.map.component.Behavior(), + new ovi.mapsapi.map.component.TypeSelector(), + new ovi.mapsapi.map.component.ZoomBar(), + new ovi.mapsapi.map.component.ViewControl(), + new ovi.mapsapi.map.component.RightClick(), + infoBubbles + ]; + + $(this).data('infoBubbles', infoBubbles); + } + + $(this).data('locs', []); + $(this).data('markers', []); + + var $this = $(this), + map = new ovi.mapsapi.map.Display($(this).get(0), + { + zoomLevel: options.maps.zoom, + center: center, + components: components, + eventListener: { + mapviewchangeend: [function(event) + { + var map = $this.data('map'); + if ($this.data('circleArea')) + { + var zoom = map.zoomLevel; + $this.data('circleArea').visibility = zoom <= 10; + map.update(10, false); + } + + if (options.onMapLoaded && typeof options.onMapLoaded == 'function') + { + options.onMapLoaded.apply($this, $this); + options.onMapLoaded = false; + } + }, true, null] + }, + fading: 250 + }); + + $(this).pdwMap('_hideOverlay'); + return map; + }, + + cleanMarkers: function() + { + var $this = $(this); + if ($(this).data('markers')) + { + $.each($(this).data('markers'), function(i, n) + { + if (typeof n != 'function') + { + $this.data('map').objects.remove(n); + } + }); + } + $(this).data('locs', []); + $(this).data('markers', []); + }, + + cleanCircle: function() + { + }, + + addMarker: function(point) + { + var options = $(this).data('options'), + map = $(this).data('map'), + $this = $(this), + markerOptions = { + eventListener: { + click: [function(event) + { + $this.pdwMap('closeMarker'); + var infoHtml = $this.pdwMap('formatInfo', point); + var infoBubbles = $this.data('infoBubbles'); + var bubble = infoBubbles.addBubble('

      ' + infoHtml.title + '

      ' + infoHtml.content, new ovi.mapsapi.geo.Coordinate(point.lat, point.lng)); + $this.data('bubble', bubble); + + // callback + if (options.onMarkerClicked && typeof options.onMarkerClicked == 'function') + { + options.onMarkerClicked.apply(this, [ point ]); + } + }, false, null] + } + }; + + if (options.marker != false) + { + var iconUrl = options.marker.url; + if (options.marker.dynamic) + { + iconUrl += '?type=' + point.type; + } + markerOptions.icon = iconUrl; + } + + var marker = new ovi.mapsapi.map.Marker([point.lat, point.lng], markerOptions); + map.objects.add(marker); + $(this).data('markers').push(marker); + $(this).data('locs').push([point.lat, point.lng]); + }, + + openMarker: function(marker) + { + $(this).pdwMap('closeMarker'); + var infoHtml = $(this).pdwMap('formatInfo', marker), + infoBubbles = $(this).data('infoBubbles'), + bubble = infoBubbles.addBubble('

      ' + infoHtml.title + '

      ' + infoHtml.content, new ovi.mapsapi.geo.Coordinate(marker.lat, marker.lng)); + $(this).data('bubble', bubble); + }, + + closeMarker: function() + { + if (undefined != $(this).data('bubble')) + { + var infoBubbles = $(this).data('infoBubbles'), + bubble = $(this).data('bubble'); + if (infoBubbles.bubbleExists(bubble)) + { + infoBubbles.removeBubble(bubble); + } + } + }, + + centerMap: function() + { + var bounds = [] + $.each($(this).data('locs'), function(i, n) + { + bounds.push(new ovi.mapsapi.geo.Coordinate(n[0], n[1])); + }); + + var boundingBox = ovi.mapsapi.geo.BoundingBox.coverAll(bounds), + zoom = $(this).data('map').getBestZoomLevel([ boundingBox ]); + + $(this).data('map').setZoomLevel(zoom, "default"); + $(this).data('map').setCenter(boundingBox.getCenter()); + }, + + setCenter: function(lat, lng, radius) + { + var options = $(this).data('options'); + if (options.circle === false) + { + return; + } + + radius *= 1000; + + var coord = new ovi.mapsapi.geo.Coordinate(lat, lng), + circle = new ovi.mapsapi.map.Circle(coord, radius, + { + pen: { + strokeColor: options.maps.circle.stroke + '7F', + lineWidth: 1 + }, + brush: { + color: options.maps.circle.fill + '2F' + } + }); + $(this).data('map').objects.add(circle); + $(this).data('circleArea', circle); + } + } + }); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006787_configureStore.js b/pool/shard001/JavaScript/0006787_configureStore.js new file mode 100644 index 0000000000000000000000000000000000000000..b7c1123d6f819816d3c3ce823ed889cd2e1e2c44 --- /dev/null +++ b/pool/shard001/JavaScript/0006787_configureStore.js @@ -0,0 +1,29 @@ +import { createBrowserHistory } from 'history' +import { applyMiddleware, compose, createStore } from 'redux' +import { routerMiddleware } from 'connected-react-router/immutable' +import createRootReducer from './reducers' + +export const history = createBrowserHistory() + +export default function configureStore(preloadedState) { + const composeEnhancer = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose + const store = createStore( + createRootReducer(history), + preloadedState, + composeEnhancer( + applyMiddleware( + routerMiddleware(history), + ), + ), + ) + + // Hot reloading + if (module.hot) { + // Enable Webpack hot module replacement for reducers + module.hot.accept('./reducers', () => { + store.replaceReducer(createRootReducer(history)); + }); + } + + return store +} diff --git a/pool/shard001/JavaScript/0006788_publish.js b/pool/shard001/JavaScript/0006788_publish.js new file mode 100644 index 0000000000000000000000000000000000000000..7d2db3b1dcd8199f42466e543690ded669ebc200 --- /dev/null +++ b/pool/shard001/JavaScript/0006788_publish.js @@ -0,0 +1,75 @@ +Meteor.publish('sensorList', function(org_id){ + var thisUser = Meteor.users.findOne({_id: this.userId}); + if(thisUser){ + var controllers = Meteor.users.find({owner_id: this.userId}) + var allController_ids = []; + controllers.forEach(function(doc){ + allController_ids.push(doc._id); + }) + return [ + Sensors.find({controller_id: {$in: allController_ids}}) + ]; + } +}) + +Meteor.publish('latestReading', function(sensor_id){ + var thisUser = Meteor.users.findOne({_id: this.userId}); + if(thisUser){ + return [ + Readings.find({sensor_id: sensor_id}, {sort: {time: -1}, limit:1}), + Alarms.find({sensor_id: sensor_id, active: true, owner_id: this.userId}) + ]; + } +}) + +Meteor.publish('singleSensor', function(sensor_id){ + var thisUser = Meteor.users.findOne({_id: this.userId}); + if(thisUser){ + return [ + Sensors.find({_id: sensor_id}), + Alarms.find({sensor_id: sensor_id, active: true, owner_id: this.userId}) + ]; + } +}) + +Meteor.publish('alarmList', function(sensor_id){ + var thisUser = Meteor.users.findOne({_id: this.userId}); + if(thisUser){ + return [ + Sensors.find({_id: sensor_id}), + Alarms.find({sensor_id: sensor_id, enabled:true, owner_id: this.userId}) + ]; + } +}) + +Meteor.publish('editAlarm', function(alarm_id){ + var thisUser = Meteor.users.findOne({_id: this.userId}); + if(thisUser){ + return [ + Alarms.find({_id: alarm_id, owner_id: this.userId}) + ]; + } +}) + +Meteor.publish('history', function(sensor_id, timeStart, timeStop){ + var thisUser = Meteor.users.findOne({_id: this.userId}); + if(thisUser){ + return [ + HourlyAverage.find({sensor_id: sensor_id, $and:[{time: {$gte: timeStart}}, {time:{$lte: timeStop}}]}), + Sensors.find({_id: sensor_id}) + ]; + } +}) + +Meteor.publish('controllers', function(){ + var thisUser = Meteor.users.findOne({_id: this.userId}); + if(thisUser){ + return [ + Meteor.users.find({type:"controller", owner_id: this.userId}, {fields: {username: 1, profile:1, type: 1, desc: 1, name: 1, owner_id: 1}}) + ]; + } +}) + +Meteor.publish('editAccount', function(){ + return Meteor.users.find({_id: this.userId}, {fields: {profile:1, keys: 1, emails:1}}); +}) diff --git a/pool/shard001/JavaScript/0006790_composes.js b/pool/shard001/JavaScript/0006790_composes.js new file mode 100644 index 0000000000000000000000000000000000000000..d8fb1f27d06a6c1a3a226fd0db539cb3591de022 --- /dev/null +++ b/pool/shard001/JavaScript/0006790_composes.js @@ -0,0 +1,39 @@ +import test from 'ava'; +import debounce from 'lodash.debounce'; +import webpack from 'webpack'; +import 'babel-core/register'; + +import helper from './_helper'; +import expected from './composes/expected.json'; + +test.beforeEach(t => { + + const config = helper.getSuiteConfig('composes'); + + t.context.config = config + t.context.extractOpts = helper.getExtractOptions(config); + t.end(); + +}) + +test('composes', t => { + + t.plan(1); + + const onOutput = debounce((filename, blob, total) => { + t.same(total, expected); + t.end(); + }, t.context.extractOpts.writeDebounceMs); + + const config = Object.assign({}, t.context.config, { + extractCssModuleClassnames: { onOutput } + }); + + const callback = (err, stats) => { + err = err || (stats.hasErrors() ? new Error(stats.toString()) : null); + if (err) { t.fail(err); t.end(); } + } + + webpack(config, callback); + +}); diff --git a/pool/shard001/JavaScript/0006791_console_logger.js b/pool/shard001/JavaScript/0006791_console_logger.js new file mode 100644 index 0000000000000000000000000000000000000000..9741039bd04ec07a8f74dbf713eb32ee61c21a14 --- /dev/null +++ b/pool/shard001/JavaScript/0006791_console_logger.js @@ -0,0 +1,114 @@ +/* Copyright 2019 Google Inc. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +function calculateSeverityCode(severity) { + if (severity == -2) { + return 'E'; + } else if (severity == -1) { + return 'W'; + } else if (severity == 0) { + return 'I'; + } else { + return String(severity); + } +} + +function isoTime() { + return (new Date).toISOString(); +} + +function formatServerTime(timeInMs) { + return timeInMs.toFixed(1); +} + +function formatArg(arg, pretty = false) { + // TODO(applmak): Handle formal exception-like things here. + // That would be things that, say, have a message key. + // Maybe only show the message? + // Maybe format the stacktrace? + if (arg instanceof Error) { + return `${arg.message} +${arg.stack} +`; + } + if (typeof arg == 'string') { + return arg; + } + if (pretty) { + return JSON.stringify(arg, undefined, 2); + } + return JSON.stringify(arg); +} + +function formatArgs(args) { + if (args.length == 0) { + return ''; + } + if (args.length == 1) { + return formatArg(args[0], true); + } + return args.map(arg => formatArg(arg)).join(' '); +} + +const COLORS = [ + 'black', + 'red', + 'green', + 'blue', + 'yellow', + 'orange', + 'purple', + 'cyan', + 'magenta', + 'gray', +]; + +let colorFn; +let nextColorIndex = 0; +function nextColor() { + const ret = colorFn ? colorFn(COLORS[nextColorIndex]) : COLORS[nextColorIndex]; + nextColorIndex = (nextColorIndex+1) % COLORS.length; + return ret; +} + +const channelColors = {}; +function colorForChannel(channel, severity) { + if (!channelColors[channel]) { + channelColors[channel] = nextColor(); + } + if (severity == -2) { + return channelColors[channel].bold.bgRed; + } else if (severity == -1) { + return channelColors[channel].bgBlue; + } + return channelColors[channel]; +} + +export function makeConsoleLogger(newColorFn, now) { + colorFn = newColorFn; + return function(channel, severity, args) { + const color = colorForChannel(channel, severity); + const desc = color.desc; + const str = `${calculateSeverityCode(severity)} ${ + isoTime()} ${ + formatServerTime(now())}: [${ + color(channel)}] ${formatArgs(args)}`; + if (desc) { + console.log(str, desc.join(';'), ''); + } else { + console.log(str); + } + } +} diff --git a/pool/shard001/JavaScript/0006793_reducers.js b/pool/shard001/JavaScript/0006793_reducers.js new file mode 100644 index 0000000000000000000000000000000000000000..1f2031183b881d3c3a531fac8a9f9ec02c663c42 --- /dev/null +++ b/pool/shard001/JavaScript/0006793_reducers.js @@ -0,0 +1,70 @@ +import types from './actionTypes' +import { filterDeleted } from '../shared/utils' + +export const comments = (state = {}, action) => { + switch (action.type) { + case types.COMMENT_CREATED: + case types.COMMENT_UPDATED: + case types.COMMENT_VOTED: + let { comment } = action + return { + ...state, + [comment.id]: comment + } + case types.COMMENT_DELETED: + let comments = Object.values({ + ...state, + [action.comment.id]: action.comment + }) + return filterDeleted(comments) + case types.COMMENTS_LOADED: + return filterDeleted(action.comments) + default: + return state + } +} + +const emptyForm = { + active: false, + type: '', + comment: { + parentId: '', + author: '', + body: '' + } +} + +export const commentForm = (state = emptyForm, action) => { + switch (action.type) { + case types.OPEN_NEW_COMMENT_FORM: + return { + active: true, + type: 'new', + comment: { + ...emptyForm.comment, + parentId: action.parentId + } + } + case types.OPEN_EDIT_COMMENT_FORM: + return { + active: true, + type: 'edit', + comment: action.comment + } + case types.COMMENT_CREATED: + case types.COMMENT_UPDATED: + case types.CLOSE_COMMENT_FORM: + return emptyForm + case types.COMMENT_FORM_VALUE_CHANGED: + const { name, value } = action.input + return { + ...state, + comment: { + ...state.comment, + [name]: value + } + } + default: + return state + } +} diff --git a/pool/shard001/JavaScript/0006794_batch_get.js b/pool/shard001/JavaScript/0006794_batch_get.js new file mode 100644 index 0000000000000000000000000000000000000000..bbc8f610f551d1aa9a212149173eed52482a57ba --- /dev/null +++ b/pool/shard001/JavaScript/0006794_batch_get.js @@ -0,0 +1,169 @@ +/******************************************************************************* + * Copyright 2013-2014 Aerospike, 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. + ******************************************************************************/ + +/******************************************************************************* + * + * Read a batch of records. + * + ******************************************************************************/ + +var fs = require('fs'); +var aerospike = require('aerospike'); +var yargs = require('yargs'); + +var Policy = aerospike.policy; +var Status = aerospike.status; + +/******************************************************************************* + * + * Options parsing + * + ******************************************************************************/ + +var argp = yargs + .usage("$0 [options] key [key ...]") + .options({ + help: { + boolean: true, + describe: "Display this message." + }, + host: { + alias: "h", + default: "127.0.0.1", + describe: "Aerospike database address." + }, + port: { + alias: "p", + default: 3000, + describe: "Aerospike database port." + }, + timeout: { + alias: "t", + default: 10, + describe: "Timeout in milliseconds." + }, + 'log-level': { + alias: "l", + default: aerospike.log.INFO, + describe: "Log level [0-5]" + }, + 'log-file': { + default: undefined, + describe: "Path to a file send log messages to." + }, + namespace: { + alias: "n", + default: "test", + describe: "Namespace for the keys." + }, + set: { + alias: "s", + default: "demo", + describe: "Set for the keys." + } + }); + +var argv = argp.argv; +var keys = argv._.map(function(key) { + return { ns: argv.namespace, set: argv.set, key: key }; +}); + +if ( argv.help === true ) { + argp.showHelp(); + process.exit(0); +} + +if ( keys.length === 0 ) { + console.error("Error: Please provide one or more keys for the operation"); + console.error(); + argp.showHelp(); + process.exit(1); +} + +/******************************************************************************* + * + * Configure the client. + * + ******************************************************************************/ + +config = { + + // the hosts to attempt to connect with. + hosts: [ + { addr: argv.host, port: argv.port } + ], + + // log configuration + log: { + level: argv['log-level'], + file: argv['log-file'] ? fs.openSync(argv['log-file'], "a") : 2 + }, + + // default policies + policies: { + timeout: argv.timeout + } +}; + +/******************************************************************************* + * + * Perform the operation + * + ******************************************************************************/ + +function format(o) { + return JSON.stringify(o, null, ' '); +} + +aerospike.client(config).connect(function (err, client) { + + if ( err.code != Status.AEROSPIKE_OK ) { + console.error("Error: Aerospike server connection error. ", err.message); + process.exit(1); + } + + // + // Perform the operation + // + + if ( argv.profile ) { + console.time("batch_get"); + } + + client.batchGet(keys, function (err, results) { + + var exitCode = 0; + + switch ( err.code ) { + case Status.AEROSPIKE_OK: + console.log(format(results)); + break; + + default: + console.error("Error: " + err.message); + exitCode = 1; + break; + } + + + if ( argv.profile ) { + console.log("---"); + console.timeEnd("batch_get"); + } + + process.exit(exitCode); + }); +}); diff --git a/pool/shard001/JavaScript/0006796_app.js b/pool/shard001/JavaScript/0006796_app.js new file mode 100644 index 0000000000000000000000000000000000000000..7290ba82c0c051552897e83175d98d021fdb7c7f --- /dev/null +++ b/pool/shard001/JavaScript/0006796_app.js @@ -0,0 +1,66 @@ +var express = require('express'); +var fs = require('fs'); +var path = require('path'); +var favicon = require('static-favicon'); +var logger = require('morgan'); +var cookieParser = require('cookie-parser'); +var bodyParser = require('body-parser'); + +var routes = require('./routes/index'); + +var app = express(); + +// view engine setup +app.set('views', path.join(__dirname, 'views')); +app.set('view engine', 'jade'); + +var faviconPath = 'public/images/favicon.ico'; +if (fs.existsSync(faviconPath)) { + app.use(favicon(faviconPath)); +} +else { + app.use(favicon()); +} + +app.use(logger('dev')); +app.use(bodyParser.json()); +app.use(bodyParser.urlencoded()); +app.use(cookieParser()); +app.use(require('stylus').middleware(path.join(__dirname, 'public'))); +app.use(express.static(path.join(__dirname, 'public'))); + +app.use('/', routes); + +/// catch 404 and forwarding to error handler +app.use(function(req, res, next) { + var err = new Error('Not Found'); + err.status = 404; + next(err); +}); + +/// error handlers + +// development error handler +// will print stacktrace +if (app.get('env') === 'development') { + app.use(function(err, req, res, next) { + res.status(err.status || 500); + res.render('error', { + message: err.message, + error: err + }); + }); +} + +// production error handler +// no stacktraces leaked to user +app.use(function(err, req, res, next) { + res.status(err.status || 500); + res.render('error', { + message: err.message, + error: {} + }); +}); + + +module.exports = app; diff --git a/pool/shard001/JavaScript/0006798_Burn.js b/pool/shard001/JavaScript/0006798_Burn.js new file mode 100644 index 0000000000000000000000000000000000000000..cec7709673ff0d2bdee44097fb0c7b6f0c336fab --- /dev/null +++ b/pool/shard001/JavaScript/0006798_Burn.js @@ -0,0 +1,16 @@ + +import SpellEffect from '../../base/SpellEffect'; + +export default class Burn extends SpellEffect { + apply(target, caster) { + super.apply(target, caster); + this.damagePerTurn = caster.stats.mnt; + return `${target.name} was burned!`; + } + + preTurn(target) { + target.stats.hp.sub(this.damagePerTurn); + const isDead = target.stats.hp.atMin() ? `${target.name} was slain!` : ''; + return `${target.name} took ${this.damagePerTurn} damage due to mild burns! ${isDead}`; + } +} \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006800_jsFunctions.js b/pool/shard001/JavaScript/0006800_jsFunctions.js new file mode 100644 index 0000000000000000000000000000000000000000..237de229c9c662dd7a90a3dd25a61ed0390ce635 --- /dev/null +++ b/pool/shard001/JavaScript/0006800_jsFunctions.js @@ -0,0 +1,62 @@ +'use strict'; +var closeMenu = function () { + jQuery("header .menu-toggle.icon").click(); +}; +//function NavIsClose() { +// jQuery("nav").addClass("is-close"); +// jQuery("nav").css("transform": "perspective(0px) scale(0.2)"); +//} +//jQuery( "div:contains('Ledarskapsdiamanten')").after("®" ); +//STOPS SCROLL WEH ACTION IS MADE +var page = jQuery("html, body"); + +//page.on("scroll mousedown wheel DOMMouseScroll mousewheel keyup touchmove", function () { +// //If mousedown on scroll +// console.log("first page on"); +// page.on("scroll mousedown wheel DOMMouseScroll mousewheel keyup touchmove", function () { +// // if (document.documentMode === undefined) { +// console.log("2nd page on"); +// +// //page.stop(); +// // } +// }); +//}); + + +/** + * This part handles the highlighting functionality. + * We use the scroll functionality again, some array creation and + * manipulation, class adding and class removing, and conditional testing + */ +var aChildren = jQuery("nav li").children(); // find the a children of the list items +var aArray = []; // create the empty aArray +for (var i = 0; i < aChildren.length; i++) { + var aChild = aChildren[i]; + var ahref = jQuery(aChild).attr('href'); + aArray.push(ahref); +} // this for loop fills the aArray with attribute href values + +jQuery(window).scroll(function () { + var windowPos = jQuery(window).scrollTop(); // get the offset of the window from the top of page + var windowHeight = jQuery(window).height(); // get the height of the window + var docHeight = jQuery(document).height(); + + for (var i = 0; i < aArray.length; i++) { + var theID = aArray[i]; + var divPos = jQuery(theID).offset().top; // get the offset of the div from the top of page + var divHeight = jQuery(theID).height(); // get the height of the div in question + if ((windowPos + 62) >= divPos && (windowPos + 62) < (divPos + divHeight)) { + jQuery("a[href='" + theID + "']").addClass("nav-active"); + } else { + jQuery("a[href='" + theID + "']").removeClass("nav-active"); + } + } + + if (windowPos + windowHeight == docHeight) { + if (!jQuery("nav li:last-child a").hasClass("nav-active")) { + var navActiveCurrent = jQuery(".nav-active").attr("href"); + jQuery("a[href='" + navActiveCurrent + "']").removeClass("nav-active"); + jQuery("nav li:last-child a").addClass("nav-active"); + } + } +}); \ No newline at end of file diff --git a/pool/shard001/JavaScript/0006804_AssetsManager.js b/pool/shard001/JavaScript/0006804_AssetsManager.js new file mode 100644 index 0000000000000000000000000000000000000000..d1d8b167678706e10c2cd3beb8dec052be911c15 --- /dev/null +++ b/pool/shard001/JavaScript/0006804_AssetsManager.js @@ -0,0 +1,151 @@ +/** + * Implements Wikia.getMultiTypePackage function for fetching JS/CSS/HTML + * and JS messages in a single request (as JSON object) + * + * @author Macbre + */ +window.Wikia = window.Wikia || {}; + +/** + * request - json of key value pairs + * keys: + * templates - an array of objects with the following fields: controller, method and an optional params (parameters for the controller method) + * styles - comma-separated list of SASS files + * scripts - comma-separated list of AssetsManager groups + * messages - comma-separated list of JSMessages packages (messages are registered automagically) + * mustache - comma-separated list of paths to Mustache-powered templates + * ttl - cache period for both Varnish and Browser (in seconds) + * params - an object with all the additional parameters for the request (e.g. useskin, forceprofile, etc.) + * callback - function to be called with fetched JSON object + * + * Returns object with all requested resources + * + * Example: Wikia.getMultiTypePackage({ + * messages: 'EditPageLayout', + * scripts: 'oasis_jquery,yui', + * styles: 'path/to/style/file' + * mustache: 'extensions/wikia/MyExy/templates/index.mustache', + * templates: [{ + * controller: 'MyController', + * method: 'getPage', + * params: { + * page: 1 + * } + * }], + * params: { + * useskin: 'skinname' + * } + * }); + */ +window.Wikia.getMultiTypePackage = function(options) { + var request = {}, + styles = options.styles, + scripts = options.scripts, + messages = options.messages, + templates = options.templates, + mustache = options.mustache, + callback = options.callback, + params = options.params, + ttl = options.ttl, + send = false; + + if(typeof styles === 'string'){ + request.styles = styles; + send = true; + } + + if(typeof scripts === 'string'){ + request.scripts = scripts; + send = true; + } + + if(typeof messages === 'string'){ + request.messages = messages; + send = true; + } + + if(typeof mustache === 'string'){ + request.mustache = mustache; + send = true; + } + + if(typeof templates != 'undefined'){ + // JSON encode templates entry + request.templates = (typeof templates === 'object') ? JSON.stringify(templates) : templates; + send = true; + } + + if(typeof params === 'object'){ + request = $.extend(request, params); + } + + if(ttl) + request.ttl = ~~ttl; + + if(send){ + // add a cache buster + request.cb = wgStyleVersion; + + // return promise + return $.nirvana.getJson('AssetsManagerController', 'getMultiTypePackage', request, function(resources) { + // "register" JS messages + if (resources.messages) { + wgMessages = $.extend(wgMessages, resources.messages); + } + + if (typeof callback === 'function') { + callback(resources); + } + }); + }else{ + throw 'No resources to load specified'; + } +}; + +/** + * Evaluate given JS code by adding an inline '); + }, + + init : function() { + var f = document.forms[0], ed = tinyMCEPopup.editor, e; + + // Setup browse button + document.getElementById('hrefbrowsercontainer').innerHTML = this.getBrowserHTML('hrefbrowser', 'href', 'page', 'theme_advanced_link'); + if (isVisible('hrefbrowser')) + document.getElementById('href').style.width = '152px'; + + this.fillFileList('link_list', 'tinyMCELinkList'); + this.fillRelList('rel_list'); + this.fillTargetList('target_list'); + this.fillClassList('class_list'); + + if (e = ed.dom.getParent(ed.selection.getNode(), 'A')) { + f.href.value = ed.dom.getAttrib(e, 'href'); + f.linktitle.value = ed.dom.getAttrib(e, 'title'); + f.insert.value = ed.getLang('update'); + selectByValue(f, 'link_list', f.href.value); + selectByValue(f, 'target_list', ed.dom.getAttrib(e, 'target')); + selectByValue(f, 'rel_list', ed.dom.getAttrib(e, 'rel'), true); // PATCH: rel attribute + selectByValue(f, 'class_list', ed.dom.getAttrib(e, 'class'), true); // PATCH: add true to set custom values + } + + TinyMCE_EditableSelects.init(); // PATCH: initialize editable select + }, + + update : function() { + var f = document.forms[0], ed = tinyMCEPopup.editor, e, b, href = f.href.value.replace(/ /g, '%20'); + + tinyMCEPopup.restoreSelection(); + e = ed.dom.getParent(ed.selection.getNode(), 'A'); + + // Remove element if there is no href + if (!f.href.value) { + if (e) { + b = ed.selection.getBookmark(); + ed.dom.remove(e, 1); + ed.selection.moveToBookmark(b); + tinyMCEPopup.execCommand("mceEndUndoLevel"); + tinyMCEPopup.close(); + return; + } + } + + // Create new anchor elements + if (e == null) { + ed.getDoc().execCommand("unlink", false, null); + tinyMCEPopup.execCommand("mceInsertLink", false, "#mce_temp_url#", {skip_undo : 1}); + var t = this; + + tinymce.each(ed.dom.select("a"), function(n) { + if (ed.dom.getAttrib(n, 'href') == '#mce_temp_url#') { + e = n; + + ed.dom.setAttribs(e, { + href : href, + title : f.linktitle.value, + target : f.target_list ? getSelectValue(f, "target_list") : null, + 'rel' : f.rel_list ? getSelectValue(f, "rel_list") : null, + 'class' : f.class_list ? getSelectValue(f, "class_list") : null + }); + + // PATCH: fix issues + t.fixIssues(ed, e, f); + } + }); + } else { + ed.dom.setAttribs(e, { + href : href, + title : f.linktitle.value, + target : f.target_list ? getSelectValue(f, "target_list") : null, + 'rel' : f.rel_list ? getSelectValue(f, "rel_list") : null, + 'class' : f.class_list ? getSelectValue(f, "class_list") : null + }); + + // PATCH: fix issues + this.fixIssues(ed, e, f); + } + + // Don't move caret if selection was image + if (e.childNodes.length != 1 || e.firstChild.nodeName != 'IMG') { + ed.focus(); + ed.selection.select(e); + ed.selection.collapse(0); + tinyMCEPopup.storeSelection(); + } + + tinyMCEPopup.execCommand("mceEndUndoLevel"); + tinyMCEPopup.close(); + }, + + // PATCH: add function fixIssues + fixIssues : function(ed, e, f) { + // Fix relative URLs + if (f.href.value+'/' == ed.settings.document_base_url) { + f.href.value += '/'; + } + if (f.href.value == ed.settings.document_base_url) { + e.setAttribute('mce_href', f.href.value); + } + // Convert / and empty strings to ./ + if (f.href.value == '/' || f.href.value == '') { + ed.dom.setAttrib(e, 'href', './'); + } + }, + // PATCH EOF + + checkPrefix : function(n) { + if (n.value && Validator.isEmail(n) && !/^\s*mailto:/i.test(n.value) && confirm(tinyMCEPopup.getLang('typolinks_dlg.link_is_email'))) + n.value = 'mailto:' + n.value; + + if (/^\s*www\./i.test(n.value) && confirm(tinyMCEPopup.getLang('typolinks_dlg.link_is_external'))) + n.value = 'http://' + n.value; + + if (n.value && /^#/.test(n.value)) + n.value = '{{env::request}}' + n.value; + }, + + fillFileList : function(id, l) { + var dom = tinyMCEPopup.dom, lst = dom.get(id); + + l = window[l]; + + if (l && l.length > 0) { + lst.options[lst.options.length] = new Option('', ''); + + tinymce.each(l, function(o) { + lst.options[lst.options.length] = new Option(o[0], o[1]); + }); + } else + dom.remove(dom.getParent(id, 'tr')); + }, + + fillRelList : function(id) { + var dom = tinyMCEPopup.dom, lst = dom.get(id); + + lst.options[lst.options.length] = new Option(tinyMCEPopup.getLang('not_set'), ''); + lst.options[lst.options.length] = new Option(tinyMCEPopup.getLang('typolinks_dlg.image_rel_single'), 'lightbox'); + lst.options[lst.options.length] = new Option(tinyMCEPopup.getLang('typolinks_dlg.image_rel_multi'), 'lightbox[multi]'); + }, + + fillTargetList : function(id) { + var dom = tinyMCEPopup.dom, lst = dom.get(id), v; + + lst.options[lst.options.length] = new Option(tinyMCEPopup.getLang('not_set'), ''); + //lst.options[lst.options.length] = new Option(tinyMCEPopup.getLang('typolinks_dlg.link_target_same'), '_self'); PATCH: hide + lst.options[lst.options.length] = new Option(tinyMCEPopup.getLang('typolinks_dlg.link_target_blank'), '_blank'); + + if (v = tinyMCEPopup.getParam('theme_advanced_link_targets')) { + tinymce.each(v.split(','), function(v) { + v = v.split('='); + lst.options[lst.options.length] = new Option(v[0], v[1]); + }); + } + }, + + fillClassList : function(id) { + var dom = tinyMCEPopup.dom, lst = dom.get(id), v, cl; + + if (v = tinyMCEPopup.getParam('theme_advanced_styles')) { + cl = []; + + tinymce.each(v.split(';'), function(v) { + var p = v.split('='); + + cl.push({'title' : p[0], 'class' : p[1]}); + }); + } else + cl = tinyMCEPopup.editor.dom.getClasses(); + + // PATCH: always show not_set option + lst.options[lst.options.length] = new Option(tinyMCEPopup.getLang('not_set'), ''); + + if (cl.length > 0) { + tinymce.each(cl, function(o) { + lst.options[lst.options.length] = new Option(o.title || o['class'], o['class']); + }); + }/* else + dom.remove(dom.getParent(id, 'tr')); PATCH: do not remove */ + }, + + + getBrowserHTML : function(id, target_form_element, type, prefix) { + var option = prefix + "_" + type + "_browser_callback", cb, html; + + cb = tinyMCEPopup.getParam(option, tinyMCEPopup.getParam("file_browser_callback")); + + if (!cb) + return ""; + + html = ""; + html += ''; + html += ' '; + + id = "srcbrowser"; + html += ''; + html += ' '; + + return html; + } +}; + +LinkDialog.preInit(); +tinyMCEPopup.onInit.add(LinkDialog.init, LinkDialog); diff --git a/pool/shard001/JavaScript/0007317_static-text.test.js b/pool/shard001/JavaScript/0007317_static-text.test.js new file mode 100644 index 0000000000000000000000000000000000000000..46ff97f5a2883cebee16ef74efde2fdad81e7b17 --- /dev/null +++ b/pool/shard001/JavaScript/0007317_static-text.test.js @@ -0,0 +1,54 @@ +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ + +/* eslint-disable max-nested-callbacks */ +define([ + 'tests/assets/text/config', + 'text' +], function (config, text) { + 'use strict'; + + var local = config.local, + external = config.external; + + describe('extended text module', function () { + + it('exports reference to the module', function () { + expect(text).toBeDefined(); + }); + + it('caches original load method', function () { + expect(text._load).toBeDefined(); + }); + + it('loads external files', function (done) { + spyOn(text, '_load').and.callThrough(); + + require([ + external.path + ], function (data) { + var regExp = /\s+/g; + + expect(text._load).toHaveBeenCalled(); + expect(data.replace(regExp, ' ')).toEqual(external.result.replace(regExp, ' ')); + + done(); + }); + }); + + it('loads internal files', function (done) { + spyOn(text, '_load').and.callThrough(); + + require([ + local.path + ], function (data) { + expect(text._load).not.toHaveBeenCalled(); + expect(data).toEqual(local.result); + + done(); + }); + }); + }); +}); diff --git a/pool/shard001/JavaScript/0007319_example.js b/pool/shard001/JavaScript/0007319_example.js new file mode 100644 index 0000000000000000000000000000000000000000..6e05e76253e40152f54dd77675e185a0b47e7bca --- /dev/null +++ b/pool/shard001/JavaScript/0007319_example.js @@ -0,0 +1,37 @@ +const getMedia = require('getusermedia') +const enumerateDevices = require('enumerate-devices') +const streamToDevice = require('./') + +// get user media +getMedia({video: false, audio: true}, function (err, media) { + if (err) throw err + + //route stream to specified device + var stream = streamToDevice(media, 'default') + + // create dropdown of available hardware devices + enumerateDevices().then(function(devices) { + var select = document.createElement('select'); + + devices.forEach(function(d){ + if(d.kind==='audiooutput' || d.kind==='videooutput') { + var option = document.createElement('option') + option.value = d.deviceId + option.text = d.label; + select.appendChild(option) + } + }) + + document.body.appendChild(select) + + //set device on selection + select.onchange = function(e){ + stream.setDevice(e.target.value) + } + + }).catch(function(err) { + throw(err) + }) + +}) + diff --git a/pool/shard001/JavaScript/0007320_EditPageView.js b/pool/shard001/JavaScript/0007320_EditPageView.js new file mode 100644 index 0000000000000000000000000000000000000000..236e6c9c82e073a160186a85b09482c05a83178b --- /dev/null +++ b/pool/shard001/JavaScript/0007320_EditPageView.js @@ -0,0 +1,75 @@ +import I18n from 'i18n-js'; +import Marionette from 'backbone.marionette'; +import 'jquery-ui'; + +import {ExtendedSelectInputView} from 'pageflow/ui'; + +import {app, editor, failureIndicatingView} from 'pageflow/editor'; + +import template from '../templates/editPage.jst'; + +export const EditPageView = Marionette.Layout.extend({ + template, + className: 'edit_page', + + mixins: [failureIndicatingView], + + regions: { + pageTypeContainer: '.page_type', + configurationContainer: '.configuration_container' + }, + + events: { + 'click a.back': 'goBack', + 'click a.destroy': 'destroy' + }, + + modelEvents: { + 'change:template': 'load' + }, + + onRender: function() { + this.pageTypeContainer.show(new ExtendedSelectInputView({ + model: this.model, + propertyName: 'template', + collection: this.options.api.pageTypes.pluck('seed'), + valueProperty: 'name', + translationKeyProperty: 'translation_key', + groupTranslationKeyProperty: 'category_translation_key', + descriptionTranslationKeyProperty: 'description_translation_key', + + pictogramClass: 'type_pictogram', + + helpLinkClicked: value => { + var pageType = this.options.api.pageTypes.findByName(value); + app.trigger('toggle-help', pageType.seed.help_entry_translation_key); + } + })); + + this.load(); + this.model.trigger('edit', this.model); + }, + + onShow: function() { + this.configurationEditor.refreshScroller(); + }, + + load: function() { + this.configurationEditor = this.options.api.createPageConfigurationEditorView(this.model, { + tab: this.options.tab + }); + + this.configurationContainer.show(this.configurationEditor); + }, + + destroy: function() { + if (confirm(I18n.t('pageflow.editor.views.edit_page_view.confirm_destroy'))) { + this.model.destroy(); + this.goBack(); + } + }, + + goBack: function() { + editor.navigate('/', {trigger: true}); + } +}); diff --git a/pool/shard001/JavaScript/0007326_products.js b/pool/shard001/JavaScript/0007326_products.js new file mode 100644 index 0000000000000000000000000000000000000000..2caf0ce8a3814e242802bdadecae7d2332d15ac8 --- /dev/null +++ b/pool/shard001/JavaScript/0007326_products.js @@ -0,0 +1,227 @@ +jQuery(function($) { + const carbon = window.carbon; + if (typeof carbon.fields === 'undefined') { + return false; + } + + class CarbonView + { + static getContainerView() { + var containerView = null; + + _.each(carbon.views, function(view) { + if(view.model && view.model.attributes && view.model.attributes.title == affProductTranslations.container) { + containerView = view; + } + }); + + return containerView; + } + + static getVariantsView() { + var variantsView = null; + + _.each(carbon.views, function(view) { + if(view.templateVariables && view.templateVariables.base_name == '_affilicious_product_variants') { + variantsView = view; + } + }); + + return variantsView; + } + + static getTypeView() { + var typeView = null; + + _.each(carbon.views, function(view) { + if(view.templateVariables && view.templateVariables.base_name == '_affilicious_product_type') { + typeView = view; + } + }); + + return typeView; + } + + static getEnabledAttributesView() { + var enabledAttributesView = null; + + _.each(carbon.views, function(view) { + if(view.templateVariables && view.templateVariables.base_name == '_affilicious_product_enabled_attributes') { + enabledAttributesView = view; + } + }); + + return enabledAttributesView; + } + + static getVariantEnabledAttributesViews() { + var variantEnabledAttributesViews = []; + + _.each(carbon.views, function(view) { + if(view.templateVariables && view.templateVariables.base_name == 'enabled_attributes') { + variantEnabledAttributesViews.push(view); + } + }); + + return variantEnabledAttributesViews; + } + } + + class AffiliciousProduct { + constructor() { + let typeView = CarbonView.getTypeView(); + let variantsView = CarbonView.getVariantsView(); + let enabledAttributesView = CarbonView.getEnabledAttributesView(); + + if(!!typeView) { + typeView.$el.ready(this.toggleTabs); + typeView.model.on('change:value', this.toggleTabs); + } + + if(!!variantsView) { + variantsView.$el.ready(this.toggleAttributes); + variantsView.model.on('change:value', this.toggleAttributes); + } + + if(!!enabledAttributesView) { + enabledAttributesView.$el.ready(this.toggleAttributes); + enabledAttributesView.model.on('change:value', this.toggleAttributes); + } + } + + toggleTabs() { + // Supports multiple languages + var view = CarbonView.getContainerView(), + typeView = CarbonView.getTypeView(), + productType = typeView.model.get('value'), + variants = view.$el.find('a[data-id="' + affProductTranslations.variants.trim().toLowerCase() + '"]').parent(), + shops = view.$el.find('a[data-id="' + affProductTranslations.shops.trim().toLowerCase() + '"]').parent(); + + if(productType === 'complex') { + variants.show(); + shops.hide(); + } else { + variants.hide(); + shops.show(); + } + } + + toggleAttributes() { + let enabledAttributesView = CarbonView.getEnabledAttributesView(), + attributesViews = CarbonView.getVariantEnabledAttributesViews(), + value = enabledAttributesView.model.get('value'); + + for (let attributesView of attributesViews) { + attributesView.model.set('value', value); + attributesView.$el.find('input').val(value); + } + } + } + + window.affiliciousProduct = new AffiliciousProduct(); +}); + +jQuery(function($) { + // TODO: Remove the code below in the beta + var product_gallery_frame; + var $image_gallery_ids = $( '#product_image_gallery' ); + var $product_images = $( '#product_images_container' ).find( 'ul.product_images' ); + + $( '.add_product_images' ).on( 'click', 'a', function( event ) { + var $el = $( this ); + + event.preventDefault(); + + // If the media frame already exists, reopen it. + if ( product_gallery_frame ) { + product_gallery_frame.open(); + return; + } + + // Create the media frame. + product_gallery_frame = wp.media.frames.product_gallery = wp.media({ + // Set the title of the modal. + title: $el.data( 'choose' ), + button: { + text: $el.data( 'update' ) + }, + states: [ + new wp.media.controller.Library({ + title: $el.data( 'choose' ), + filterable: 'all', + multiple: true + }) + ] + }); + + // When an image is selected, run a callback. + product_gallery_frame.on( 'select', function() { + var selection = product_gallery_frame.state().get( 'selection' ); + var attachment_ids = $image_gallery_ids.val(); + + selection.map( function( attachment ) { + attachment = attachment.toJSON(); + + if ( attachment.id ) { + attachment_ids = attachment_ids ? attachment_ids + ',' + attachment.id : attachment.id; + var attachment_image = attachment.sizes && attachment.sizes.thumbnail ? attachment.sizes.thumbnail.url : attachment.url; + + $product_images.append( '
    • ' ); + } + }); + + $image_gallery_ids.val( attachment_ids ); + }); + + // Finally, open the modal. + product_gallery_frame.open(); + }); + + // Image ordering. + $product_images.sortable({ + items: 'li.image', + cursor: 'move', + scrollSensitivity: 40, + forcePlaceholderSize: true, + forceHelperSize: false, + helper: 'clone', + opacity: 0.65, + placeholder: 'wc-metabox-sortable-placeholder', + start: function( event, ui ) { + ui.item.css( 'background-color', '#f6f6f6' ); + }, + stop: function( event, ui ) { + ui.item.removeAttr( 'style' ); + }, + update: function() { + var attachment_ids = ''; + + $( '#product_images_container' ).find( 'ul li.image' ).css( 'cursor', 'default' ).each( function() { + var attachment_id = $( this ).attr( 'data-attachment_id' ); + attachment_ids = attachment_ids + attachment_id + ','; + }); + + $image_gallery_ids.val( attachment_ids ); + } + }); + + // Remove images. + $( '#product_images_container' ).on( 'click', 'a.delete', function() { + $( this ).closest( 'li.image' ).remove(); + + var attachment_ids = ''; + + $( '#product_images_container' ).find( 'ul li.image' ).css( 'cursor', 'default' ).each( function() { + var attachment_id = $( this ).attr( 'data-attachment_id' ); + attachment_ids = attachment_ids + attachment_id + ','; + }); + + $image_gallery_ids.val( attachment_ids ); + + // Remove any lingering tooltips. + $( '#tiptip_holder' ).removeAttr( 'style' ); + $( '#tiptip_arrow' ).removeAttr( 'style' ); + + return false; + }); +}); diff --git a/pool/shard001/JavaScript/0007329_signup-app.js b/pool/shard001/JavaScript/0007329_signup-app.js new file mode 100644 index 0000000000000000000000000000000000000000..a7043918ad5e52b247c0a3efae4f5067c63ac564 --- /dev/null +++ b/pool/shard001/JavaScript/0007329_signup-app.js @@ -0,0 +1,67 @@ +#!/usr/bin/env node +'use strict'; + +/** + * This file issues the needed requests to set up the gleaner application + * with the roles defined in the 'a-frontend-routes.js' file. + * + */ + +var Path = require('path'); +var request = require('request'); +var config = require(Path.resolve(__dirname, '../config.js')); +var appData = require(Path.resolve(__dirname, '../a-games-routes.js')).app; + +var baseUsersAPI = config.a2.a2ApiPath; + +request.post(baseUsersAPI + 'login', { + form: { + username: config.a2.a2AdminUsername, + password: config.a2.a2AdminPassword + }, + json: true + }, + function (err, httpResponse, body) { + if (err) { + console.error(err); + if (err.errno && err.errno.indexOf('ECONNREFUSED') > -1) { + console.error('Could not connect to A2 to login!'); + return process.exit(-1); + } + console.log('Did not register the games-frontend with A2, continuing anyway!'); + return process.exit(0); + } + + appData.name = config.projectName; + appData.prefix = config.a2.a2Prefix; + appData.host = 'http://' + config.myHost + ':' + config.port; + + request({ + uri: baseUsersAPI + 'applications', + method: 'POST', + body: appData, + json: true, + headers: { + Authorization: 'Bearer ' + body.user.token + } + }, function (err, httpResponse, body) { + if (err) { + console.error(err); + if (err.errno && err.errno.indexOf('ECONNREFUSED') > -1) { + console.error('Could not connect to A2 to register the frontend application!'); + return process.exit(-1); + } + console.log('Did not register the games-frontend with A2, continuing anyway!'); + return process.exit(0); + } + + if (body.message) { + console.error('Error', body.message, + 'Did not register the backend with A2, continuing anyway!'); + } else { + console.log('Application and roles setup complete.'); + } + + process.exit(0); + }); + });