static Variant HHVM_METHOD(Memcache, get, const Variant& key, VRefParam flags /*= null*/) { auto data = Native::data<MemcacheData>(this_); if (key.is(KindOfArray)) { std::vector<const char *> real_keys; std::vector<size_t> key_len; Array keyArr = key.toArray(); real_keys.reserve(keyArr.size()); key_len.reserve(keyArr.size()); for (ArrayIter iter(keyArr); iter; ++iter) { auto key = iter.second().toString(); String serializedKey = memcache_prepare_key(key); real_keys.push_back(const_cast<char *>(serializedKey.c_str())); key_len.push_back(iter.second().toString().length()); } if (!real_keys.empty()) { const char *payload = NULL; size_t payload_len = 0; uint32_t flags = 0; const char *res_key = NULL; size_t res_key_len = 0; memcached_result_st result; memcached_return_t ret = memcached_mget(&data->m_memcache, &real_keys[0], &key_len[0], real_keys.size()); memcached_result_create(&data->m_memcache, &result); Array return_val; while ((memcached_fetch_result(&data->m_memcache, &result, &ret)) != nullptr) { if (ret != MEMCACHED_SUCCESS) { // should probably notify about errors continue; } payload = memcached_result_value(&result); payload_len = memcached_result_length(&result); flags = memcached_result_flags(&result); res_key = memcached_result_key_value(&result); res_key_len = memcached_result_key_length(&result); return_val.set(String(res_key, res_key_len, CopyString), memcache_fetch_from_storage(payload, payload_len, flags)); } memcached_result_free(&result); return return_val; } } else { char *payload = NULL; size_t payload_len = 0; uint32_t flags = 0; memcached_return_t ret; String serializedKey = memcache_prepare_key(key.toString()); if (serializedKey.length() == 0) { return false; } payload = memcached_get(&data->m_memcache, serializedKey.c_str(), serializedKey.length(), &payload_len, &flags, &ret); /* This is for historical reasons from libmemcached*/ if (ret == MEMCACHED_END) { ret = MEMCACHED_NOTFOUND; } if (ret == MEMCACHED_NOTFOUND) { return false; } Variant retval = memcache_fetch_from_storage(payload, payload_len, flags); free(payload); return retval; } return false; }
// DetermineFlags //------------------------------------------------------------------------------ /*static*/ uint32_t LinkerNode::DetermineFlags( const AString & linkerType, const AString & linkerName, const AString & args ) { uint32_t flags = DetermineLinkerTypeFlags( linkerType, linkerName ); if ( flags & LINK_FLAG_MSVC ) { // Parse args for some other flags Array< AString > tokens; args.Tokenize( tokens ); bool debugFlag = false; bool incrementalFlag = false; bool incrementalNoFlag = false; bool optREFFlag = false; bool optICFFlag = false; bool optLBRFlag = false; bool orderFlag = false; const AString * const end = tokens.End(); for ( const AString * it=tokens.Begin(); it!=end; ++it ) { const AString & token = *it; if ( IsLinkerArg_MSVC( token, "DLL" ) ) { flags |= LinkerNode::LINK_FLAG_DLL; continue; } if ( IsLinkerArg_MSVC( token, "DEBUG" ) ) { debugFlag = true; continue; } if ( IsLinkerArg_MSVC( token, "INCREMENTAL" ) ) { incrementalFlag = true; continue; } if ( IsLinkerArg_MSVC( token, "INCREMENTAL:NO" ) ) { incrementalNoFlag = true; continue; } if ( IsStartOfLinkerArg_MSVC( token, "OPT" ) ) { if ( token.FindI( "REF" ) ) { optREFFlag = true; } if ( token.FindI( "ICF" ) ) { optICFFlag = true; } if ( token.FindI( "LBR" ) ) { optLBRFlag = true; } continue; } if ( IsStartOfLinkerArg_MSVC( token, "ORDER" ) ) { orderFlag = true; continue; } } // Determine incremental linking status bool usingIncrementalLinking = false; // false by default // these options enable incremental linking if ( debugFlag || incrementalFlag ) { usingIncrementalLinking = true; } // these options disable incremental linking if ( incrementalNoFlag || optREFFlag || optICFFlag || optLBRFlag || orderFlag ) { usingIncrementalLinking = false; } if ( usingIncrementalLinking ) { flags |= LINK_FLAG_INCREMENTAL; } } else { // Parse args for some other flags Array< AString > tokens; args.Tokenize( tokens ); const AString * const end = tokens.End(); for ( const AString * it=tokens.Begin(); it!=end; ++it ) { const AString & token = *it; if ( ( token == "-shared" ) || ( token == "-dynamiclib" ) || ( token == "--oformat=prx" ) ) { flags |= LinkerNode::LINK_FLAG_DLL; continue; } } } return flags; }
void CommandService::_process_respond(Command* rpc_res){ const int64_t who =static_cast<int64_t>(rpc_res->getWho()); const int64_t rpc_id =static_cast<int64_t>(rpc_res->getSn()); do{ RpcInfo* rpc =_get_rpc(rpc_id); if(rpc == 0){ WARN("service %s(%lld) who %lld rpc %lld respond, not exist", name(), (long long)m_id, (long long)who, (long long)rpc_id); break; } if(Command* cmd=rpc->getCommand()){ // check & prepare command Array* queue =static_cast< Array* >(m_queue_tb->get(who)); if(queue == 0){ WARN("service %s(%lld) who %lld rpc %lld respond, command not exist", name(), (long long)m_id, (long long)who, (long long)rpc_id); break; } Command* front =static_cast< Command* >(queue->front()); if(!front){ WARN("service %s(%lld) who %lld rpc %lld respond, command not exist", name(), (long long)m_id, (long long)who, (long long)rpc_id); break; } if(front != cmd){ WARN("service %s(%lld) who %lld rpc %lld respond, command mismatch", name(), (long long)m_id, (long long)who, (long long)rpc_id); break; } // call rpc m_processing_command =front; const int64_t result =rpc->invoke(rpc_res); m_processing_command =0; // process result const int64_t cmd_id =front->getCommand(); if(result == Command::STATE_COMPLETE){ front->setState(Command::STATE_COMPLETE); queue->pop_front(); INFO("service %s(%lld) who %lld rpc %lld respond, command %lld complete", name(), (long long)m_id, (long long)who, (long long)rpc_id, (long long)cmd_id); } else if(result > 0){ front->setState(Command::STATE_PROCESSING); INFO("service %s(%lld) who %lld rpc %lld respond, command %lld processing", name(), (long long)m_id, (long long)who, (long long)rpc_id, (long long)cmd_id); } else{ front->setState(Command::STATE_ERROR); queue->pop_front(); ERROR("service %s(%lld) who %lld rpc %lld respond, command %lld error %lld", name(), (long long)m_id, (long long)who, (long long)rpc_id, (long long)cmd_id, (long long)result); } // post process if(cmd_id==LOGOUT_REQUEST && queue->empty()){ m_queue_tb->remove(who); } else if(queue->size()){ _process_request(who); } } else{ const int64_t result =rpc->invoke(rpc_res); if(result == Command::STATE_COMPLETE){ INFO("service %s(%lld) who %lld rpc %lld respond, complete", name(), (long long)m_id, (long long)who, (long long)rpc_id); } else if(result > 0){ INFO("service %s(%lld) who %lld rpc %lld respond, processing", name(), (long long)m_id, (long long)who, (long long)rpc_id); } else{ ERROR("service %s(%lld) who %lld rpc %lld respond, error %lld", name(), (long long)m_id, (long long)who, (long long)rpc_id, (long long)result); } } }while(0); // remove rpc info m_rpc_tb->remove(rpc_id); }
Value getworkex(const Array& params, bool fHelp) { if (fHelp || params.size() > 2) throw runtime_error( "getworkex [data, coinbase]\n" "If [data, coinbase] is not specified, returns extended work data.\n" ); if (vNodes.empty()) throw JSONRPCError(-9, "GizmoCoin is not connected!"); if (IsInitialBlockDownload()) throw JSONRPCError(-10, "GizmoCoin is downloading blocks..."); if (pindexBest->nHeight >= LAST_POW_BLOCK) throw JSONRPCError(RPC_MISC_ERROR, "No more PoW blocks"); typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t; static mapNewBlock_t mapNewBlock; static vector<CBlock*> vNewBlock; static CReserveKey reservekey(pwalletMain); if (params.size() == 0) { // Update block static unsigned int nTransactionsUpdatedLast; static CBlockIndex* pindexPrev; static int64_t nStart; static CBlock* pblock; if (pindexPrev != pindexBest || (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)) { if (pindexPrev != pindexBest) { // Deallocate old blocks since they're obsolete now mapNewBlock.clear(); BOOST_FOREACH(CBlock* pblock, vNewBlock) delete pblock; vNewBlock.clear(); } nTransactionsUpdatedLast = nTransactionsUpdated; pindexPrev = pindexBest; nStart = GetTime(); // Create new block pblock = CreateNewBlock(pwalletMain); if (!pblock) throw JSONRPCError(-7, "Out of memory"); vNewBlock.push_back(pblock); } // Update nTime pblock->nTime = max(pindexPrev->GetPastTimeLimit()+1, GetAdjustedTime()); pblock->nNonce = 0; // Update nExtraNonce static unsigned int nExtraNonce = 0; IncrementExtraNonce(pblock, pindexPrev, nExtraNonce); // Save mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig); // Prebuild hash buffers char pmidstate[32]; char pdata[128]; char phash1[64]; FormatHashBuffers(pblock, pmidstate, pdata, phash1); uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); CTransaction coinbaseTx = pblock->vtx[0]; std::vector<uint256> merkle = pblock->GetMerkleBranch(0); Object result; result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata)))); result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget)))); CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); ssTx << coinbaseTx; result.push_back(Pair("coinbase", HexStr(ssTx.begin(), ssTx.end()))); Array merkle_arr; BOOST_FOREACH(uint256 merkleh, merkle) { merkle_arr.push_back(HexStr(BEGIN(merkleh), END(merkleh))); } result.push_back(Pair("merkle", merkle_arr)); return result; }
Value getworkex(const Array& params, bool fHelp) { if (fHelp || params.size() > 2) throw runtime_error( "getworkex [data, coinbase]\n" "If [data, coinbase] is not specified, returns extended work data.\n" ); if (vNodes.empty()) throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Faircoin is not connected!"); if (IsInitialBlockDownload()) throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Faircoin is downloading blocks..."); typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t; static mapNewBlock_t mapNewBlock; // FIXME: thread safety static vector<CBlockTemplate*> vNewBlockTemplate; static CReserveKey reservekey(pwalletMain); if (params.size() == 0) { // Update block static unsigned int nTransactionsUpdatedLast; static CBlockIndex* pindexPrev; static int64 nStart; static CBlockTemplate* pblocktemplate; if (pindexPrev != pindexBest || (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)) { if (pindexPrev != pindexBest) { // Deallocate old blocks since they're obsolete now mapNewBlock.clear(); BOOST_FOREACH(CBlockTemplate* pblocktemplate, vNewBlockTemplate) delete pblocktemplate; vNewBlockTemplate.clear(); } // Clear pindexPrev so future getworks make a new block, despite any failures from here on pindexPrev = NULL; // Store the pindexBest used before CreateNewBlock, to avoid races nTransactionsUpdatedLast = nTransactionsUpdated; CBlockIndex* pindexPrevNew = pindexBest; nStart = GetTime(); // Create new block pblocktemplate = CreateNewBlockWithKey(*pMiningKey); if (!pblocktemplate) throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory"); vNewBlockTemplate.push_back(pblocktemplate); // Need to update only after we know CreateNewBlock succeeded pindexPrev = pindexPrevNew; } CBlock* pblock = &pblocktemplate->block; // pointer for convenience // Update nTime pblock->UpdateTime(pindexPrev); pblock->nNonce = 0; // Update nExtraNonce static unsigned int nExtraNonce = 0; IncrementExtraNonce(pblock, pindexPrev, nExtraNonce); // Save mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig); // Pre-build hash buffers char pmidstate[32]; char pdata[128]; char phash1[64]; FormatHashBuffers(pblock, pmidstate, pdata, phash1); uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); CTransaction coinbaseTx = pblock->vtx[0]; std::vector<uint256> merkle = pblock->GetMerkleBranch(0); Object result; result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata)))); result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget)))); CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); ssTx << coinbaseTx; result.push_back(Pair("coinbase", HexStr(ssTx.begin(), ssTx.end()))); Array merkle_arr; BOOST_FOREACH(uint256 merkleh, merkle) { printf("%s\n", merkleh.ToString().c_str()); merkle_arr.push_back(HexStr(BEGIN(merkleh), END(merkleh))); } result.push_back(Pair("merkle", merkle_arr)); return result; }
void Tessellator::collectTessellation(osg::Geometry &geom, unsigned int originalIndex) { osg::Vec3Array* vertices = dynamic_cast<osg::Vec3Array*>(geom.getVertexArray()); VertexPtrToIndexMap vertexPtrToIndexMap; // populate the VertexPtrToIndexMap. for(unsigned int vi=0;vi<vertices->size();++vi) { vertexPtrToIndexMap[&((*vertices)[vi])] = vi; } handleNewVertices(geom, vertexPtrToIndexMap); // we don't properly handle per primitive and per primitive_set bindings yet // will need to address this soon. Robert Oct 2002. { osg::Vec3Array* normals = NULL; // GWM Sep 2002 - add normals for extra facets int iprim=0; if (geom.getNormalBinding()==osg::Geometry::BIND_PER_PRIMITIVE || geom.getNormalBinding()==osg::Geometry::BIND_PER_PRIMITIVE_SET) { normals = dynamic_cast<osg::Vec3Array*>(geom.getNormalArray()); // GWM Sep 2002 } // GWM Dec 2003 - needed to add colours for extra facets osg::Vec4Array* cols4 = NULL; // GWM Dec 2003 colours are vec4 osg::Vec3Array* cols3 = NULL; // GWM Dec 2003 colours are vec3 if (geom.getColorBinding()==osg::Geometry::BIND_PER_PRIMITIVE || geom.getColorBinding()==osg::Geometry::BIND_PER_PRIMITIVE_SET) { Array* colours = geom.getColorArray(); // GWM Dec 2003 - need to duplicate face colours switch (colours->getType()) { case osg::Array::Vec4ArrayType: cols4=dynamic_cast<osg::Vec4Array *> (colours); break; case osg::Array::Vec3ArrayType: cols3=dynamic_cast<osg::Vec3Array *> (colours); break; default: break; } } // GWM Dec 2003 - these holders need to go outside the loop to // retain the flat shaded colour &/or normal for each tessellated polygon osg::Vec3 norm(0.0f,0.0f,0.0f); osg::Vec4 primCol4(0.0f,0.0f,0.0f,1.0f); osg::Vec3 primCol3(0.0f,0.0f,0.0f); for(PrimList::iterator primItr=_primList.begin(); primItr!=_primList.end(); ++primItr, ++_index) { Prim* prim=primItr->get(); int ntris=0; if(vertexPtrToIndexMap.size() <= 255) { osg::DrawElementsUByte* elements = new osg::DrawElementsUByte(prim->_mode); for(Prim::VecList::iterator vitr=prim->_vertices.begin(); vitr!=prim->_vertices.end(); ++vitr) { elements->push_back(vertexPtrToIndexMap[*vitr]); } // add to the drawn primitive list. geom.addPrimitiveSet(elements); ntris=elements->getNumIndices()/3; } else if(vertexPtrToIndexMap.size() > 255 && vertexPtrToIndexMap.size() <= 65535) { osg::DrawElementsUShort* elements = new osg::DrawElementsUShort(prim->_mode); for(Prim::VecList::iterator vitr=prim->_vertices.begin(); vitr!=prim->_vertices.end(); ++vitr) { elements->push_back(vertexPtrToIndexMap[*vitr]); } // add to the drawn primitive list. geom.addPrimitiveSet(elements); ntris=elements->getNumIndices()/3; } else { osg::DrawElementsUInt* elements = new osg::DrawElementsUInt(prim->_mode); for(Prim::VecList::iterator vitr=prim->_vertices.begin(); vitr!=prim->_vertices.end(); ++vitr) { elements->push_back(vertexPtrToIndexMap[*vitr]); } // add to the drawn primitive list. geom.addPrimitiveSet(elements); ntris=elements->getNumIndices()/3; } if (primItr==_primList.begin()) { // first primitive so collect primitive normal & colour. if (normals) { if (geom.getNormalBinding()==osg::Geometry::BIND_PER_PRIMITIVE) norm=(*normals)[originalIndex + _extraPrimitives]; else norm=(*normals)[iprim]; // GWM Sep 2002 the flat shaded normal } if (cols4) { primCol4=(*cols4)[iprim]; // GWM Dec 2003 the flat shaded rgba colour if (_index>=cols4->size()) { cols4->push_back(primCol4); // GWM Dec 2003 add flat shaded colour for new facet } } if (cols3) { primCol3=(*cols3)[iprim]; // GWM Dec 2003 flat shaded rgb colour if (_index>=cols3->size()) { cols3->push_back(primCol3); // GWM Dec 2003 add flat shaded colour for new facet } } } else { // later primitives use same colour if (normals) { if (geom.getNormalBinding()==osg::Geometry::BIND_PER_PRIMITIVE) { _extraPrimitives++; normals->insert(normals->begin() + originalIndex + _extraPrimitives, norm); } else normals->push_back(norm); // GWM Sep 2002 add flat shaded normal for new facet } if (cols4 && _index>=cols4->size()) { cols4->push_back(primCol4); // GWM Dec 2003 add flat shaded colour for new facet } if (cols3 && _index>=cols3->size()) { if (cols3) cols3->push_back(primCol3); // GWM Dec 2003 add flat shaded colour for new facet } if (prim->_mode==GL_TRIANGLES) { if (geom.getNormalBinding()==osg::Geometry::BIND_PER_PRIMITIVE_SET || geom.getNormalBinding()==osg::Geometry::BIND_PER_PRIMITIVE) { // need one per triangle? Not one per set. for (int ii=1; ii<ntris; ii++) { if (normals) normals->push_back(norm); // GWM Sep 2002 add flat shaded normal for new facet } } if (geom.getColorBinding()==osg::Geometry::BIND_PER_PRIMITIVE_SET || geom.getColorBinding()==osg::Geometry::BIND_PER_PRIMITIVE) { // need one per triangle? Not one per set. for (int ii=1; ii<ntris; ii++) { if (cols3 && _index>=cols3->size()) { if (cols3) cols3->push_back(primCol3); } if (cols4 && _index>=cols4->size()) { if (cols4) cols4->push_back(primCol4); } _index++; } } } // OSG_WARN<<"Add: "<< iprim << std::endl; } iprim++; // GWM Sep 2002 count which normal we should use } } }
void ZPP_GeomPoly_obj::__GetFields(Array< ::String> &outFields) { outFields->push(HX_HCSTRING("outer","\x7b","\xb8","\x28","\x37")); outFields->push(HX_HCSTRING("vertices","\xf9","\xbf","\x15","\x6a")); super::__GetFields(outFields); };
SynthesiserVoice* Synthesiser::findVoiceToSteal (SynthesiserSound* soundToPlay, int /*midiChannel*/, int midiNoteNumber) const { // This voice-stealing algorithm applies the following heuristics: // - Re-use the oldest notes first // - Protect the lowest & topmost notes, even if sustained, but not if they've been released. // apparently you are trying to render audio without having any voices... jassert (voices.size() > 0); // These are the voices we want to protect (ie: only steal if unavoidable) SynthesiserVoice* low = nullptr; // Lowest sounding note, might be sustained, but NOT in release phase SynthesiserVoice* top = nullptr; // Highest sounding note, might be sustained, but NOT in release phase // this is a list of voices we can steal, sorted by how long they've been running Array<SynthesiserVoice*> usableVoices; usableVoices.ensureStorageAllocated (voices.size()); for (int i = 0; i < voices.size(); ++i) { SynthesiserVoice* const voice = voices.getUnchecked (i); if (voice->canPlaySound (soundToPlay)) { jassert (voice->isVoiceActive()); // We wouldn't be here otherwise VoiceAgeSorter sorter; usableVoices.addSorted (sorter, voice); if (! voice->isPlayingButReleased()) // Don't protect released notes { const int note = voice->getCurrentlyPlayingNote(); if (low == nullptr || note < low->getCurrentlyPlayingNote()) low = voice; if (top == nullptr || note > top->getCurrentlyPlayingNote()) top = voice; } } } // Eliminate pathological cases (ie: only 1 note playing): we always give precedence to the lowest note(s) if (top == low) top = nullptr; const int numUsableVoices = usableVoices.size(); // The oldest note that's playing with the target pitch is ideal.. for (int i = 0; i < numUsableVoices; ++i) { SynthesiserVoice* const voice = usableVoices.getUnchecked (i); if (voice->getCurrentlyPlayingNote() == midiNoteNumber) return voice; } // Oldest voice that has been released (no finger on it and not held by sustain pedal) for (int i = 0; i < numUsableVoices; ++i) { SynthesiserVoice* const voice = usableVoices.getUnchecked (i); if (voice != low && voice != top && voice->isPlayingButReleased()) return voice; } // Oldest voice that doesn't have a finger on it: for (int i = 0; i < numUsableVoices; ++i) { SynthesiserVoice* const voice = usableVoices.getUnchecked (i); if (voice != low && voice != top && ! voice->isKeyDown()) return voice; } // Oldest voice that isn't protected for (int i = 0; i < numUsableVoices; ++i) { SynthesiserVoice* const voice = usableVoices.getUnchecked (i); if (voice != low && voice != top) return voice; } // We've only got "protected" voices now: lowest note takes priority jassert (low != nullptr); // Duophonic synth: give priority to the bass note: if (top != nullptr) return top; return low; }
void drive_FromList(QueryContext& _query) { Array<String> alias; Array<CQLIdentifier> classes; alias.append("A"); alias.append("B"); alias.append("C"); alias.append("D"); // alias == identifier, ignore alias alias.append("A"); // dup, should not be inserted classes.append(CQLIdentifier("APPLE")); classes.append(CQLIdentifier("BONGO")); classes.append(CQLIdentifier("CLAVE")); classes.append(CQLIdentifier("D")); // alias == identifier, ignore alias classes.append(CQLIdentifier("APPLE")); // dup, should not be inserted for (Uint32 i = 0; i < alias.size(); i++) { _query.insertClassPath(classes[i],alias[i]); } // // Error inserts. Keep before the from list test below // // empty identifier try { _query.insertClassPath(QueryIdentifier()); PEGASUS_TEST_ASSERT(false); } catch (QueryParseException&) { } // identifier is already an alias try { _query.insertClassPath(CQLIdentifier("A")); PEGASUS_TEST_ASSERT(false); } catch (QueryParseException&) { } // alias is already in the from list try { _query.insertClassPath(CQLIdentifier("NEW"),String("BONGO")); PEGASUS_TEST_ASSERT(false); } catch (QueryParseException&) { } // alias is already used for another from list entry try { _query.insertClassPath(CQLIdentifier("NEW"),String("B")); PEGASUS_TEST_ASSERT(false); } catch (QueryParseException&) { } // check the from list Array<QueryIdentifier> fromList = _query.getFromList(); PEGASUS_TEST_ASSERT(fromList.size() == 4); PEGASUS_TEST_ASSERT(fromList[0].getName() == "APPLE"); PEGASUS_TEST_ASSERT(fromList[1].getName() == "BONGO"); PEGASUS_TEST_ASSERT(fromList[2].getName() == "CLAVE"); PEGASUS_TEST_ASSERT(fromList[3].getName() == "D"); // check the from string String fromString = _query.getFromString(); PEGASUS_TEST_ASSERT( fromString == "FROM APPLE AS A , BONGO AS B , CLAVE AS C , D "); // identifier and alias lookup QueryIdentifier lookup = _query.findClass(String("C")); PEGASUS_TEST_ASSERT(lookup.getName() == "CLAVE"); lookup = _query.findClass(String("BONGO")); PEGASUS_TEST_ASSERT(lookup.getName() == "BONGO"); lookup = _query.findClass(String("D")); PEGASUS_TEST_ASSERT(lookup.getName() == "D"); lookup = _query.findClass(String("notthere")); PEGASUS_TEST_ASSERT(lookup.getName() == CIMName()); }
Value createrawtransaction(const Array& params, bool fHelp) { if (fHelp || (params.size() < 2 || params.size() > 3)) throw runtime_error( "createrawtransaction [{\"txid\":txid,\"vout\":n},...] {address:amount,...} [tx-comment]\n" "Create a transaction spending given inputs\n" "(array of objects containing transaction id and output number),\n" "sending to given address(es).\n" "Returns hex-encoded raw transaction.\n" "Note that the transaction's inputs are not signed, and\n" "it is not stored in the wallet or transmitted to the network."); RPCTypeCheck(params, list_of(array_type)(obj_type)); Array inputs = params[0].get_array(); Object sendTo = params[1].get_obj(); CTransaction rawTx; if (params.size() == 3) { std::string txcomment = params[2].get_str(); if (txcomment.length() > MAX_TX_COMMENT_LEN_V2) { txcomment.resize(MAX_TX_COMMENT_LEN_V2); } rawTx.strTxComment = txcomment; } BOOST_FOREACH(Value& input, inputs) { const Object& o = input.get_obj(); const Value& txid_v = find_value(o, "txid"); if (txid_v.type() != str_type) throw JSONRPCError(-8, "Invalid parameter, missing txid key"); string txid = txid_v.get_str(); if (!IsHex(txid)) throw JSONRPCError(-8, "Invalid parameter, expected hex txid"); const Value& vout_v = find_value(o, "vout"); if (vout_v.type() != int_type) throw JSONRPCError(-8, "Invalid parameter, missing vout key"); int nOutput = vout_v.get_int(); if (nOutput < 0) throw JSONRPCError(-8, "Invalid parameter, vout must be positive"); CTxIn in(COutPoint(uint256(txid), nOutput)); rawTx.vin.push_back(in); } set<CBitcoinAddress> setAddress; BOOST_FOREACH(const Pair& s, sendTo) { CBitcoinAddress address(s.name_); if (!address.IsValid()) throw JSONRPCError(-5, string("Invalid G8coin address:")+s.name_); if (setAddress.count(address)) throw JSONRPCError(-8, string("Invalid parameter, duplicated address: ")+s.name_); setAddress.insert(address); CScript scriptPubKey; scriptPubKey.SetDestination(address.Get()); int64 nAmount = AmountFromValue(s.value_); CTxOut out(nAmount, scriptPubKey); rawTx.vout.push_back(out); }
void TxToJSON(const CTransaction& tx, const uint256 hashBlock, Object& entry) { entry.push_back(Pair("txid", tx.GetHash().GetHex())); entry.push_back(Pair("normtxid", tx.GetNormalizedHash().GetHex())); entry.push_back(Pair("version", tx.nVersion)); entry.push_back(Pair("locktime", (boost::int64_t)tx.nLockTime)); if (tx.nVersion >= 2) { entry.push_back(Pair("tx-comment", tx.strTxComment)); } Array vin; BOOST_FOREACH(const CTxIn& txin, tx.vin) { Object in; if (tx.IsCoinBase()) in.push_back(Pair("coinbase", HexStr(txin.scriptSig.begin(), txin.scriptSig.end()))); else { in.push_back(Pair("txid", txin.prevout.hash.GetHex())); in.push_back(Pair("vout", (boost::int64_t)txin.prevout.n)); Object o; o.push_back(Pair("asm", txin.scriptSig.ToString())); o.push_back(Pair("hex", HexStr(txin.scriptSig.begin(), txin.scriptSig.end()))); in.push_back(Pair("scriptSig", o)); } in.push_back(Pair("sequence", (boost::int64_t)txin.nSequence)); vin.push_back(in); } entry.push_back(Pair("vin", vin)); Array vout; for (unsigned int i = 0; i < tx.vout.size(); i++) { const CTxOut& txout = tx.vout[i]; Object out; out.push_back(Pair("value", ValueFromAmount(txout.nValue))); out.push_back(Pair("n", (boost::int64_t)i)); Object o; ScriptPubKeyToJSON(txout.scriptPubKey, o); out.push_back(Pair("scriptPubKey", o)); vout.push_back(out); } entry.push_back(Pair("vout", vout)); if (hashBlock != 0) { entry.push_back(Pair("blockhash", hashBlock.GetHex())); map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock); if (mi != mapBlockIndex.end() && (*mi).second) { CBlockIndex* pindex = (*mi).second; if (pindex->IsInMainChain()) { entry.push_back(Pair("confirmations", 1 + nBestHeight - pindex->nHeight)); entry.push_back(Pair("time", (boost::int64_t)pindex->nTime)); } else entry.push_back(Pair("confirmations", 0)); } } }
void PNGEncoderOptions_obj::__GetFields(Array< ::String> &outFields) { outFields->push(HX_HCSTRING("fastCompression","\x2a","\x9a","\x82","\x9b")); super::__GetFields(outFields); };
// NOT WORKING YET double getClosestPoint(ClosestPointInfo *inf, const Point3D &pTest, const Surface &s, const SpacialHash &faceHash, float stopBelow){ // get the dimensions and size of the grid int nX = faceHash.getDimX(); int nY = faceHash.getDimY(); int nZ = faceHash.getDimZ(); float cellSize = faceHash.getSize(); // work out the MAX ring number (doesn't really need to be small) int maxRing = nX; if (nY > maxRing) maxRing = nY; if (nZ > maxRing) maxRing = nZ; // get the cell int Cx, Cy, Cz; faceHash.getBoundedIndices(&Cx, &Cy, &Cz, pTest); // flags for used triangles Array<bool> flags(s.triangles.getSize()); flags.clear(); // flags for whether point has been tested Array<bool> vertexFlags(s.vertices.getSize()); vertexFlags.clear(); // initialise the closest point algorithm inf->num = 0; inf->triangle = 0; inf->type = DIST_TYPE_INVALID; double minD = REAL_MAX; double stopBelowSqr = -1; if (stopBelow > 0) stopBelowSqr = stopBelow*stopBelow; // process the first cell Array<int> *cell = faceHash.getCell(Cx, Cy, Cz); if (cell->getSize()) getClosestPointINTERNAL(inf, &minD, pTest, s, stopBelowSqr, cell, &flags, &vertexFlags); #define DOCELL() { \ Array<int> *cell = faceHash.getCell(x, y, z); \ if (cell->getSize() && faceHash.getDistanceSQR(x, y, z, pTest) < minD){ \ getClosestPointINTERNAL(inf, &minD, pTest, s, stopBelowSqr, cell, &flags, &vertexFlags); \ if (minD < stopBelowSqr) \ return sqrt(minD); \ } } \ // process rings int x, y, z; for (int ring = 1; ring <= maxRing; ring++){ // check for terminate of ring double d = (ring-1)*cellSize; if (d*d > minD) return sqrt(minD); // done // get clamped bounds for the ring int minX = Cx - ring; if (minX < 0) minX = 0; int minY = Cy - ring; if (minY < 0) minY = 0; int minZ = Cz - ring; if (minZ < 0) minZ = 0; int maxX = Cx + ring; if (maxX >= nX) maxX = nX-1; int maxY = Cy + ring; if (maxY >= nY) maxY = nY-1; int maxZ = Cz + ring; if (maxZ >= nZ) maxZ = nZ-1; // top y = Cy - ring; if (y >= 0){ for (x = minX; x <= maxX; x++) for (z = minZ; z <= maxZ; z++) DOCELL(); } // bottom y = Cy + ring; if (y < nY){ for (x = minX; x <= maxX; x++) for (z = minZ; z <= maxZ; z++) DOCELL(); } // work out the starting points int localMinY = Cy - ring + 1; // top and bottom already done if (localMinY < minY) localMinY = minY; int localMaxY = Cy + ring - 1; if (localMaxY > maxY) localMaxY = maxY; int localMinZ = Cz - ring; if (localMinZ < minZ) localMinZ = minZ; int localMaxZ = Cz + ring; if (localMaxZ > maxZ) localMaxZ = maxZ; // left x = Cx - ring; if (x >= 0){ for (y = localMinY; y <= localMaxY; y++) for (z = localMinZ; z <= localMaxZ; z++) DOCELL(); } // right x = Cx + ring; if (x < nX){ for (y = localMinY; y <= localMaxY; y++) for (z = localMinZ; z <= localMaxZ; z++) DOCELL(); } // work out the starting points int localMinX = Cx - ring + 1; // left and right already done if (localMinX < minX) localMinX = minX; int localMaxX = Cx + ring - 1; if (localMaxX > maxX) localMaxX = maxX; // front z = Cz - ring; if (z > 0){ for (x = localMinX; x <= localMaxX; x++) for (y = localMinY; y <= localMaxY; y++) DOCELL(); } // back z = Cz + ring; if (z < nZ){ for (x = localMinX; x <= localMaxX; x++) for (y = localMinY; y <= localMaxY; y++) DOCELL(); } } return sqrt(minD); }
//------------------------------------------------------------------------------------- PyObject* Array::__py_append(PyObject* self, PyObject* args, PyObject* kwargs) { Array* ary = static_cast<Array*>(self); uint32 seq_size = ary->length(); return PyBool_FromLong(seq_ass_slice(self, seq_size, seq_size, &*args) == 0); }
dt_t *ArrayInitializer::toDt() { //printf("ArrayInitializer::toDt('%s')\n", toChars()); Type *tb = type->toBasetype(); Type *tn = tb->nextOf()->toBasetype(); Array dts; unsigned size; unsigned length; unsigned i; dt_t *dt; dt_t *d; dt_t **pdtend; //printf("\tdim = %d\n", dim); dts.setDim(dim); dts.zero(); size = tn->size(); length = 0; for (i = 0; i < index.dim; i++) { Expression *idx; Initializer *val; idx = (Expression *)index.data[i]; if (idx) length = idx->toInteger(); //printf("\tindex[%d] = %p, length = %u, dim = %u\n", i, idx, length, dim); assert(length < dim); val = (Initializer *)value.data[i]; dt = val->toDt(); if (dts.data[length]) error(loc, "duplicate initializations for index %d", length); dts.data[length] = (void *)dt; length++; } Expression *edefault = tb->nextOf()->defaultInit(); unsigned n = 1; for (Type *tbn = tn; tbn->ty == Tsarray; tbn = tbn->nextOf()->toBasetype()) { TypeSArray *tsa = (TypeSArray *)tbn; n *= tsa->dim->toInteger(); } d = NULL; pdtend = &d; for (i = 0; i < dim; i++) { dt = (dt_t *)dts.data[i]; if (dt) pdtend = dtcat(pdtend, dt); else { for (int j = 0; j < n; j++) pdtend = edefault->toDt(pdtend); } } switch (tb->ty) { case Tsarray: { unsigned tadim; TypeSArray *ta = (TypeSArray *)tb; tadim = ta->dim->toInteger(); if (dim < tadim) { if (edefault->isBool(FALSE)) // pad out end of array pdtend = dtnzeros(pdtend, size * (tadim - dim)); else { for (i = dim; i < tadim; i++) { for (int j = 0; j < n; j++) pdtend = edefault->toDt(pdtend); } } } else if (dim > tadim) { #ifdef DEBUG printf("1: "); #endif error(loc, "too many initializers, %d, for array[%d]", dim, tadim); } break; } case Tpointer: case Tarray: // Create symbol, and then refer to it Symbol *s; s = static_sym(); s->Sdt = d; outdata(s); d = NULL; if (tb->ty == Tarray) dtdword(&d, dim); dtxoff(&d, s, 0, TYnptr); break; default: assert(0); } return d; }
static Value DeserializeArray( std::string& str, std::stack<StackDepthType>& depth_stack ) { Array a; bool had_error = false; str = Trim( str ); // Arrays begin and end with [], so if we don't find one, it's an error if ( ( str[ 0 ] == '[' ) && ( str[ str.length() - 1 ] == ']' ) ) str = str.substr( 1, str.length() - 2 ); else return Value(); // extract out all values from the array (remember, a value can also be an array or an object) while ( str.length() > 0 ) { std::string tmp; size_t i = 0; for ( ; i < str.length(); i++ ) { // If we get to an object or array, parse it: if ( ( str[ i ] == '{' ) || ( str[ i ] == '[' ) ) { Value v = DeserializeValue( str, &had_error, depth_stack ); if ( had_error ) return Value(); if ( v.GetType() != NULLVal ) a.push_back( v ); break; } bool terminate_parsing = false; if ( ( str[ i ] == ',' ) || ( str[ i ] == ']' ) ) terminate_parsing = true; // hit the end of a value, parse it in the next block else { // keep grabbing chars to build up the value tmp += str[ i ]; if ( i == str.length() - 1 ) terminate_parsing = true; // end of string, finish parsing } if ( terminate_parsing ) { Value v = DeserializeValue( tmp, &had_error, depth_stack ); if ( had_error ) return Value(); if ( v.GetType() != NULLVal ) a.push_back( v ); str = str.substr( i + 1, str.length() ); break; } } } return a; }
dt_t *StructInitializer::toDt() { Array dts; unsigned i; unsigned j; dt_t *dt; dt_t *d; dt_t **pdtend; unsigned offset; //printf("StructInitializer::toDt('%s')\n", toChars()); dts.setDim(ad->fields.dim); dts.zero(); for (i = 0; i < vars.dim; i++) { VarDeclaration *v = (VarDeclaration *)vars.data[i]; Initializer *val = (Initializer *)value.data[i]; //printf("vars[%d] = %s\n", i, v->toChars()); for (j = 0; 1; j++) { assert(j < dts.dim); //printf(" adfield[%d] = %s\n", j, ((VarDeclaration *)ad->fields.data[j])->toChars()); if ((VarDeclaration *)ad->fields.data[j] == v) { if (dts.data[j]) error(loc, "field %s of %s already initialized", v->toChars(), ad->toChars()); dts.data[j] = (void *)val->toDt(); break; } } } dt = NULL; pdtend = &dt; offset = 0; for (j = 0; j < dts.dim; j++) { VarDeclaration *v = (VarDeclaration *)ad->fields.data[j]; d = (dt_t *)dts.data[j]; if (!d) { // An instance specific initializer was not provided. // Look to see if there's a default initializer from the // struct definition VarDeclaration *v = (VarDeclaration *)ad->fields.data[j]; if (v->init) { d = v->init->toDt(); } else if (v->offset >= offset) { unsigned k; unsigned offset2 = v->offset + v->type->size(); // Make sure this field does not overlap any explicitly // initialized field. for (k = j + 1; 1; k++) { if (k == dts.dim) // didn't find any overlap { v->type->toDt(&d); break; } VarDeclaration *v2 = (VarDeclaration *)ad->fields.data[k]; if (v2->offset < offset2 && dts.data[k]) break; // overlap } } } if (d) { if (v->offset < offset) error(loc, "duplicate union initialization for %s", v->toChars()); else { unsigned sz = dt_size(d); unsigned vsz = v->type->size(); unsigned voffset = v->offset; unsigned dim = 1; for (Type *vt = v->type->toBasetype(); vt->ty == Tsarray; vt = vt->nextOf()->toBasetype()) { TypeSArray *tsa = (TypeSArray *)vt; dim *= tsa->dim->toInteger(); } assert(sz == vsz || sz * dim <= vsz); for (size_t i = 0; i < dim; i++) { if (offset < voffset) pdtend = dtnzeros(pdtend, voffset - offset); if (!d) { if (v->init) d = v->init->toDt(); else v->type->toDt(&d); } pdtend = dtcat(pdtend, d); d = NULL; offset = voffset + sz; voffset += vsz / dim; if (sz == vsz) break; } } } } if (offset < ad->structsize) dtnzeros(pdtend, ad->structsize - offset); return dt; }
GameSession& GameSession::operator =(const JsonValue& jsonValue) { if(jsonValue.ValueExists("GameSessionId")) { m_gameSessionId = jsonValue.GetString("GameSessionId"); m_gameSessionIdHasBeenSet = true; } if(jsonValue.ValueExists("Name")) { m_name = jsonValue.GetString("Name"); m_nameHasBeenSet = true; } if(jsonValue.ValueExists("FleetId")) { m_fleetId = jsonValue.GetString("FleetId"); m_fleetIdHasBeenSet = true; } if(jsonValue.ValueExists("CreationTime")) { m_creationTime = jsonValue.GetDouble("CreationTime"); m_creationTimeHasBeenSet = true; } if(jsonValue.ValueExists("TerminationTime")) { m_terminationTime = jsonValue.GetDouble("TerminationTime"); m_terminationTimeHasBeenSet = true; } if(jsonValue.ValueExists("CurrentPlayerSessionCount")) { m_currentPlayerSessionCount = jsonValue.GetInteger("CurrentPlayerSessionCount"); m_currentPlayerSessionCountHasBeenSet = true; } if(jsonValue.ValueExists("MaximumPlayerSessionCount")) { m_maximumPlayerSessionCount = jsonValue.GetInteger("MaximumPlayerSessionCount"); m_maximumPlayerSessionCountHasBeenSet = true; } if(jsonValue.ValueExists("Status")) { m_status = GameSessionStatusMapper::GetGameSessionStatusForName(jsonValue.GetString("Status")); m_statusHasBeenSet = true; } if(jsonValue.ValueExists("GameProperties")) { Array<JsonValue> gamePropertiesJsonList = jsonValue.GetArray("GameProperties"); for(unsigned gamePropertiesIndex = 0; gamePropertiesIndex < gamePropertiesJsonList.GetLength(); ++gamePropertiesIndex) { m_gameProperties.push_back(gamePropertiesJsonList[gamePropertiesIndex].AsObject()); } m_gamePropertiesHasBeenSet = true; } if(jsonValue.ValueExists("IpAddress")) { m_ipAddress = jsonValue.GetString("IpAddress"); m_ipAddressHasBeenSet = true; } if(jsonValue.ValueExists("Port")) { m_port = jsonValue.GetInteger("Port"); m_portHasBeenSet = true; } if(jsonValue.ValueExists("PlayerSessionCreationPolicy")) { m_playerSessionCreationPolicy = PlayerSessionCreationPolicyMapper::GetPlayerSessionCreationPolicyForName(jsonValue.GetString("PlayerSessionCreationPolicy")); m_playerSessionCreationPolicyHasBeenSet = true; } return *this; }
void ScriptDebuggerRemote::debug(ScriptLanguage *p_script,bool p_can_continue) { if (!tcp_client->is_connected()) { ERR_EXPLAIN("Script Debugger failed to connect, but being used anyway."); ERR_FAIL(); } packet_peer_stream->put_var("debug_enter"); packet_peer_stream->put_var(2); packet_peer_stream->put_var(p_can_continue); packet_peer_stream->put_var(p_script->debug_get_error()); while(true) { _get_output(); if (packet_peer_stream->get_available_packet_count()>0) { Variant var; Error err = packet_peer_stream->get_var(var); ERR_CONTINUE( err != OK); ERR_CONTINUE( var.get_type()!=Variant::ARRAY ); Array cmd = var; ERR_CONTINUE( cmd.size()==0); ERR_CONTINUE( cmd[0].get_type()!=Variant::STRING ); String command = cmd[0]; if (command=="get_stack_dump") { packet_peer_stream->put_var("stack_dump"); int slc = p_script->debug_get_stack_level_count(); packet_peer_stream->put_var( slc ); for(int i=0;i<slc;i++) { Dictionary d; d["file"]=p_script->debug_get_stack_level_source(i); d["line"]=p_script->debug_get_stack_level_line(i); d["function"]=p_script->debug_get_stack_level_function(i); //d["id"]=p_script->debug_get_stack_level_ d["id"]=0; packet_peer_stream->put_var( d ); } } else if (command=="get_stack_frame_vars") { cmd.remove(0); ERR_CONTINUE( cmd.size()!=1 ); int lv = cmd[0]; List<String> members; List<Variant> member_vals; p_script->debug_get_stack_level_members(lv,&members,&member_vals); ERR_CONTINUE( members.size() !=member_vals.size() ); List<String> locals; List<Variant> local_vals; p_script->debug_get_stack_level_locals(lv,&locals,&local_vals); ERR_CONTINUE( locals.size() !=local_vals.size() ); packet_peer_stream->put_var("stack_frame_vars"); packet_peer_stream->put_var(2+locals.size()*2+members.size()*2); { //members packet_peer_stream->put_var(members.size()); List<String>::Element *E=members.front(); List<Variant>::Element *F=member_vals.front(); while(E) { if (F->get().get_type()==Variant::OBJECT) { packet_peer_stream->put_var("*"+E->get()); packet_peer_stream->put_var(safe_get_instance_id(F->get())); } else { packet_peer_stream->put_var(E->get()); packet_peer_stream->put_var(F->get()); } E=E->next(); F=F->next(); } } { //locals packet_peer_stream->put_var(locals.size()); List<String>::Element *E=locals.front(); List<Variant>::Element *F=local_vals.front(); while(E) { if (F->get().get_type()==Variant::OBJECT) { packet_peer_stream->put_var("*"+E->get()); packet_peer_stream->put_var(safe_get_instance_id(F->get())); } else { packet_peer_stream->put_var(E->get()); packet_peer_stream->put_var(F->get()); } E=E->next(); F=F->next(); } } } else if (command=="step") { set_depth(-1); set_lines_left(1); break; } else if (command=="next") { set_depth(0); set_lines_left(1); break; } else if (command=="continue") { set_depth(-1); set_lines_left(-1); break; } else if (command=="break") { ERR_PRINT("Got break when already broke!"); break; } else if (command=="request_scene_tree") { if (request_scene_tree) request_scene_tree(request_scene_tree_ud); } else if (command=="request_video_mem") { _send_video_memory(); } else if (command=="breakpoint") { bool set = cmd[3]; if (set) insert_breakpoint(cmd[2],cmd[1]); else remove_breakpoint(cmd[2],cmd[1]); } else { _parse_live_edit(cmd); } } else { OS::get_singleton()->delay_usec(10000); } } packet_peer_stream->put_var("debug_exit"); packet_peer_stream->put_var(0); }
Value getrawtransaction(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "getrawtransaction \"txid\" ( verbose )\n" "\nNOTE: By default this function only works sometimes. This is when the tx is in the mempool\n" "or there is an unspent output in the utxo for this transaction. To make it always work,\n" "you need to maintain a transaction index, using the -txindex command line option.\n" "\nReturn the raw transaction data.\n" "\nIf verbose=0, returns a string that is serialized, hex-encoded data for 'txid'.\n" "If verbose is non-zero, returns an Object with information about 'txid'.\n" "\nArguments:\n" "1. \"txid\" (string, required) The transaction id\n" "2. verbose (numeric, optional, default=0) If 0, return a string, other return a json object\n" "\nResult (if verbose is not set or set to 0):\n" "\"data\" (string) The serialized, hex-encoded data for 'txid'\n" "\nResult (if verbose > 0):\n" "{\n" " \"hex\" : \"data\", (string) The serialized, hex-encoded data for 'txid'\n" " \"txid\" : \"id\", (string) The transaction id (same as provided)\n" " \"version\" : n, (numeric) The version\n" " \"locktime\" : ttt, (numeric) The lock time\n" " \"vin\" : [ (array of json objects)\n" " {\n" " \"txid\": \"id\", (string) The transaction id\n" " \"vout\": n, (numeric) \n" " \"scriptSig\": { (json object) The script\n" " \"asm\": \"asm\", (string) asm\n" " \"hex\": \"hex\" (string) hex\n" " },\n" " \"sequence\": n (numeric) The script sequence number\n" " }\n" " ,...\n" " ],\n" " \"vout\" : [ (array of json objects)\n" " {\n" " \"value\" : x.xxx, (numeric) The value in hdl\n" " \"n\" : n, (numeric) index\n" " \"scriptPubKey\" : { (json object)\n" " \"asm\" : \"asm\", (string) the asm\n" " \"hex\" : \"hex\", (string) the hex\n" " \"reqSigs\" : n, (numeric) The required sigs\n" " \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n" " \"addresses\" : [ (json array of string)\n" " \"bitcoinaddress\" (string) bitcoin address\n" " ,...\n" " ]\n" " }\n" " }\n" " ,...\n" " ],\n" " \"blockhash\" : \"hash\", (string) the block hash\n" " \"confirmations\" : n, (numeric) The confirmations\n" " \"time\" : ttt, (numeric) The transaction time in seconds since epoch (Jan 1 1970 GMT)\n" " \"blocktime\" : ttt (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n" "}\n" "\nExamples:\n" + HelpExampleCli("getrawtransaction", "\"mytxid\"") + HelpExampleCli("getrawtransaction", "\"mytxid\" 1") + HelpExampleRpc("getrawtransaction", "\"mytxid\", 1") ); LOCK(cs_main); uint256 hash = ParseHashV(params[0], "parameter 1"); bool fVerbose = false; if (params.size() > 1) fVerbose = (params[1].get_int() != 0); CTransaction tx; uint256 hashBlock; if (!GetTransaction(hash, tx, hashBlock, true)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available about transaction"); string strHex = EncodeHexTx(tx); if (!fVerbose) return strHex; Object result; result.push_back(Pair("hex", strHex)); TxToJSON(tx, hashBlock, result); return result; }
Array<To> scan(const Array<Ti>& in, const int dim) { dim4 dims = in.dims(); Array<To> out = createValueArray<To>(dims, 0); switch (in.ndims()) { case 1: scan_dim<op, Ti, To, 1>()(out.get(), out.strides(), out.dims(), in.get(), in.strides(), in.dims(), dim); break; case 2: scan_dim<op, Ti, To, 2>()(out.get(), out.strides(), out.dims(), in.get(), in.strides(), in.dims(), dim); break; case 3: scan_dim<op, Ti, To, 3>()(out.get(), out.strides(), out.dims(), in.get(), in.strides(), in.dims(), dim); break; case 4: scan_dim<op, Ti, To, 4>()(out.get(), out.strides(), out.dims(), in.get(), in.strides(), in.dims(), dim); break; } return out; }
Value gettxoutproof(const Array& params, bool fHelp) { if (fHelp || (params.size() != 1 && params.size() != 2)) throw runtime_error( "gettxoutproof [\"txid\",...] ( blockhash )\n" "\nReturns a hex-encoded proof that \"txid\" was included in a block.\n" "\nNOTE: By default this function only works sometimes. This is when there is an\n" "unspent output in the utxo for this transaction. To make it always work,\n" "you need to maintain a transaction index, using the -txindex command line option or\n" "specify the block in which the transaction is included in manually (by blockhash).\n" "\nReturn the raw transaction data.\n" "\nArguments:\n" "1. \"txids\" (string) A json array of txids to filter\n" " [\n" " \"txid\" (string) A transaction hash\n" " ,...\n" " ]\n" "2. \"block hash\" (string, optional) If specified, looks for txid in the block with this hash\n" "\nResult:\n" "\"data\" (string) A string that is a serialized, hex-encoded data for the proof.\n" ); set<uint256> setTxids; uint256 oneTxid; Array txids = params[0].get_array(); BOOST_FOREACH(Value& txid, txids) { if (txid.get_str().length() != 64 || !IsHex(txid.get_str())) throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid txid ")+txid.get_str()); uint256 hash(uint256S(txid.get_str())); if (setTxids.count(hash)) throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated txid: ")+txid.get_str()); setTxids.insert(hash); oneTxid = hash; } LOCK(cs_main); CBlockIndex* pblockindex = NULL; uint256 hashBlock; if (params.size() > 1) { hashBlock = uint256S(params[1].get_str()); if (!mapBlockIndex.count(hashBlock)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); pblockindex = mapBlockIndex[hashBlock]; } else { CCoins coins; if (pcoinsTip->GetCoins(oneTxid, coins) && coins.nHeight > 0 && coins.nHeight <= chainActive.Height()) pblockindex = chainActive[coins.nHeight]; } if (pblockindex == NULL) { CTransaction tx; if (!GetTransaction(oneTxid, tx, hashBlock, false) || hashBlock.IsNull()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not yet in block"); if (!mapBlockIndex.count(hashBlock)) throw JSONRPCError(RPC_INTERNAL_ERROR, "Transaction index corrupt"); pblockindex = mapBlockIndex[hashBlock]; } CBlock block; if(!ReadBlockFromDisk(block, pblockindex)) throw JSONRPCError(RPC_INTERNAL_ERROR, "Can't read block from disk"); unsigned int ntxFound = 0; BOOST_FOREACH(const CTransaction&tx, block.vtx) if (setTxids.count(tx.GetHash())) ntxFound++; if (ntxFound != setTxids.size()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "(Not all) transactions not found in specified block"); CDataStream ssMB(SER_NETWORK, PROTOCOL_VERSION); CMerkleBlock mb(block, setTxids); ssMB << mb; std::string strHex = HexStr(ssMB.begin(), ssMB.end()); return strHex; }
int main() { // The eigen approach ArrayXd n = ArrayXd::LinSpaced(N+1,0,N); double multiplier = M_PI/N; Array<double, 1, N+1> nT = n.transpose(); ArrayXd x = - cos(multiplier*n); ArrayXd xsub = x.middleRows(1, N-1); ArrayXd ysub = (x1-x0)/2*xsub + (x1+x0)/2; ArrayXXd T = cos((acos(x).matrix()*nT.matrix()).array()); ArrayXXd Tsub = cos((acos(xsub).matrix()*nT.matrix()).array()); ArrayXd sqinx = 1/sqrt(1-xsub*xsub); MatrixXd inv1x2 = (sqinx).matrix().asDiagonal(); // Can't use the following to test elements of inv1x2 // std::cout << inv1x2(0,0) << "\n"; MatrixXd Usub = inv1x2 * sin(((acos(xsub).matrix())*nT.matrix()).array()).matrix(); MatrixXd dTsub = Usub*(n.matrix().asDiagonal()); MatrixXd d2Tsub = ((sqinx*sqinx).matrix().asDiagonal())*((xsub.matrix().asDiagonal()) * (dTsub.matrix()) - (Tsub.matrix()) * ((n*n).matrix().asDiagonal())); MatrixXd d2T(N+1, N+1); RowVectorXd a = (pow((-1),nT))*(nT*nT+1)*(nT*nT)/3; RowVectorXd b = (nT*nT+1)*(nT*nT)/3; d2T.middleRows(1,N-1) = d2Tsub; d2T.row(0) = a; d2T.row(N) = b; MatrixXd D2 = d2T.matrix() * ((T.matrix()).inverse()); MatrixXd E2 = D2.middleRows(1,N-1).middleCols(1,N-1); MatrixXd Y = ysub.matrix().asDiagonal(); MatrixXd H = - (4 / ((x1-x0)*(x1-x0))) * E2 + k*Y; Eigen::EigenSolver<Eigen::MatrixXd> HE(H); VectorXcd D = HE.eigenvalues(); MatrixXcd V = HE.eigenvectors(); std::cout << HE.info() << std::endl; // Open ofstream ofstream Dfile; Dfile.open("D-output.txt"); ofstream Vfile; Vfile.open("V-output.txt"); ofstream V544file; V544file.open("V544-output.txt"); Dfile.precision(15); Dfile << D.real() << "\n"; Vfile.precision(15); Vfile << V.real() << "\n"; V544file.precision(15); for(int i = 1; i<N-1; i++) { V544file << ysub[i-1]; V544file << " " << V.col(544).row(i-1).real() << "\n"; } Dfile.close(); Vfile.close(); V544file.close(); system("gnuplot -p plot.gp"); system("rsvg-convert -w 2000 -o V544-plot.png V544-plot.svg"); }
Value createrawtransaction(const Array& params, bool fHelp) { if (fHelp || params.size() != 2) throw runtime_error( "createrawtransaction [{\"txid\":\"id\",\"vout\":n},...] {\"address\":amount,...}\n" "\nCreate a transaction spending the given inputs and sending to the given addresses.\n" "Returns hex-encoded raw transaction.\n" "Note that the transaction's inputs are not signed, and\n" "it is not stored in the wallet or transmitted to the network.\n" "\nArguments:\n" "1. \"transactions\" (string, required) A json array of json objects\n" " [\n" " {\n" " \"txid\":\"id\", (string, required) The transaction id\n" " \"vout\":n (numeric, required) The output number\n" " }\n" " ,...\n" " ]\n" "2. \"addresses\" (string, required) a json object with addresses as keys and amounts as values\n" " {\n" " \"address\": x.xxx (numeric, required) The key is the bitcoin address, the value is the hdl amount\n" " ,...\n" " }\n" "\nResult:\n" "\"transaction\" (string) hex string of the transaction\n" "\nExamples\n" + HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"{\\\"address\\\":0.01}\"") + HelpExampleRpc("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\", \"{\\\"address\\\":0.01}\"") ); LOCK(cs_main); RPCTypeCheck(params, boost::assign::list_of(array_type)(obj_type)); Array inputs = params[0].get_array(); Object sendTo = params[1].get_obj(); CMutableTransaction rawTx; BOOST_FOREACH(const Value& input, inputs) { const Object& o = input.get_obj(); uint256 txid = ParseHashO(o, "txid"); const Value& vout_v = find_value(o, "vout"); if (vout_v.type() != int_type) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing vout key"); int nOutput = vout_v.get_int(); if (nOutput < 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout must be positive"); CTxIn in(COutPoint(txid, nOutput)); rawTx.vin.push_back(in); } set<CBitcoinAddress> setAddress; BOOST_FOREACH(const Pair& s, sendTo) { CBitcoinAddress address(s.name_); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid HOdlcoin address: ")+s.name_); if (setAddress.count(address)) throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+s.name_); setAddress.insert(address); CScript scriptPubKey = GetScriptForDestination(address.Get()); CAmount nAmount = AmountFromValue(s.value_); CTxOut out(nAmount, scriptPubKey); rawTx.vout.push_back(out); }
bool test_28() { OS::get_singleton()->print("\n\nTest 28: sprintf\n"); bool success, state = true; char output_format[] = "\tTest:\t%ls => %ls (%s)\n"; String format, output; Array args; bool error; // %% format = "fish %% frog"; args.clear(); output = format.sprintf(args, &error); success = (output == String("fish % frog") && !error); OS::get_singleton()->print(output_format, format.c_str(), output.c_str(), success ? "OK" : "FAIL"); if (!success) state = false; //////// INTS // Int format = "fish %d frog"; args.clear(); args.push_back(5); output = format.sprintf(args, &error); success = (output == String("fish 5 frog") && !error); OS::get_singleton()->print(output_format, format.c_str(), output.c_str(), success ? "OK" : "FAIL"); if (!success) state = false; // Int left padded with zeroes. format = "fish %05d frog"; args.clear(); args.push_back(5); output = format.sprintf(args, &error); success = (output == String("fish 00005 frog") && !error); OS::get_singleton()->print(output_format, format.c_str(), output.c_str(), success ? "OK" : "FAIL"); if (!success) state = false; // Int left padded with spaces. format = "fish %5d frog"; args.clear(); args.push_back(5); output = format.sprintf(args, &error); success = (output == String("fish 5 frog") && !error); OS::get_singleton()->print(output_format, format.c_str(), output.c_str(), success ? "OK" : "FAIL"); if (!success) state = false; // Int right padded with spaces. format = "fish %-5d frog"; args.clear(); args.push_back(5); output = format.sprintf(args, &error); success = (output == String("fish 5 frog") && !error); OS::get_singleton()->print(output_format, format.c_str(), output.c_str(), success ? "OK" : "FAIL"); if (!success) state = false; // Int with sign (positive). format = "fish %+d frog"; args.clear(); args.push_back(5); output = format.sprintf(args, &error); success = (output == String("fish +5 frog") && !error); OS::get_singleton()->print(output_format, format.c_str(), output.c_str(), success ? "OK" : "FAIL"); if (!success) state = false; // Negative int. format = "fish %d frog"; args.clear(); args.push_back(-5); output = format.sprintf(args, &error); success = (output == String("fish -5 frog") && !error); OS::get_singleton()->print(output_format, format.c_str(), output.c_str(), success ? "OK" : "FAIL"); if (!success) state = false; // Hex (lower) format = "fish %x frog"; args.clear(); args.push_back(45); output = format.sprintf(args, &error); success = (output == String("fish 2d frog") && !error); OS::get_singleton()->print(output_format, format.c_str(), output.c_str(), success ? "OK" : "FAIL"); if (!success) state = false; // Hex (upper) format = "fish %X frog"; args.clear(); args.push_back(45); output = format.sprintf(args, &error); success = (output == String("fish 2D frog") && !error); OS::get_singleton()->print(output_format, format.c_str(), output.c_str(), success ? "OK" : "FAIL"); if (!success) state = false; // Octal format = "fish %o frog"; args.clear(); args.push_back(99); output = format.sprintf(args, &error); success = (output == String("fish 143 frog") && !error); OS::get_singleton()->print(output_format, format.c_str(), output.c_str(), success ? "OK" : "FAIL"); if (!success) state = false; ////// REALS // Real format = "fish %f frog"; args.clear(); args.push_back(99.99); output = format.sprintf(args, &error); success = (output == String("fish 99.990000 frog") && !error); OS::get_singleton()->print(output_format, format.c_str(), output.c_str(), success ? "OK" : "FAIL"); if (!success) state = false; // Real left-padded format = "fish %11f frog"; args.clear(); args.push_back(99.99); output = format.sprintf(args, &error); success = (output == String("fish 99.990000 frog") && !error); OS::get_singleton()->print(output_format, format.c_str(), output.c_str(), success ? "OK" : "FAIL"); if (!success) state = false; // Real right-padded format = "fish %-11f frog"; args.clear(); args.push_back(99.99); output = format.sprintf(args, &error); success = (output == String("fish 99.990000 frog") && !error); OS::get_singleton()->print(output_format, format.c_str(), output.c_str(), success ? "OK" : "FAIL"); if (!success) state = false; // Real given int. format = "fish %f frog"; args.clear(); args.push_back(99); output = format.sprintf(args, &error); success = (output == String("fish 99.000000 frog") && !error); OS::get_singleton()->print(output_format, format.c_str(), output.c_str(), success ? "OK" : "FAIL"); if (!success) state = false; // Real with sign (positive). format = "fish %+f frog"; args.clear(); args.push_back(99.99); output = format.sprintf(args, &error); success = (output == String("fish +99.990000 frog") && !error); OS::get_singleton()->print(output_format, format.c_str(), output.c_str(), success ? "OK" : "FAIL"); if (!success) state = false; // Real with 1 decimals. format = "fish %.1f frog"; args.clear(); args.push_back(99.99); output = format.sprintf(args, &error); success = (output == String("fish 100.0 frog") && !error); OS::get_singleton()->print(output_format, format.c_str(), output.c_str(), success ? "OK" : "FAIL"); if (!success) state = false; // Real with 12 decimals. format = "fish %.12f frog"; args.clear(); args.push_back(99.99); output = format.sprintf(args, &error); success = (output == String("fish 99.990000000000 frog") && !error); OS::get_singleton()->print(output_format, format.c_str(), output.c_str(), success ? "OK" : "FAIL"); if (!success) state = false; // Real with no decimals. format = "fish %.f frog"; args.clear(); args.push_back(99.99); output = format.sprintf(args, &error); success = (output == String("fish 100 frog") && !error); OS::get_singleton()->print(output_format, format.c_str(), output.c_str(), success ? "OK" : "FAIL"); if (!success) state = false; /////// Strings. // String format = "fish %s frog"; args.clear(); args.push_back("cheese"); output = format.sprintf(args, &error); success = (output == String("fish cheese frog") && !error); OS::get_singleton()->print(output_format, format.c_str(), output.c_str(), success ? "OK" : "FAIL"); if (!success) state = false; // String left-padded format = "fish %10s frog"; args.clear(); args.push_back("cheese"); output = format.sprintf(args, &error); success = (output == String("fish cheese frog") && !error); OS::get_singleton()->print(output_format, format.c_str(), output.c_str(), success ? "OK" : "FAIL"); if (!success) state = false; // String right-padded format = "fish %-10s frog"; args.clear(); args.push_back("cheese"); output = format.sprintf(args, &error); success = (output == String("fish cheese frog") && !error); OS::get_singleton()->print(output_format, format.c_str(), output.c_str(), success ? "OK" : "FAIL"); if (!success) state = false; ///// Characters // Character as string. format = "fish %c frog"; args.clear(); args.push_back("A"); output = format.sprintf(args, &error); success = (output == String("fish A frog") && !error); OS::get_singleton()->print(output_format, format.c_str(), output.c_str(), success ? "OK" : "FAIL"); if (!success) state = false; // Character as int. format = "fish %c frog"; args.clear(); args.push_back(65); output = format.sprintf(args, &error); success = (output == String("fish A frog") && !error); OS::get_singleton()->print(output_format, format.c_str(), output.c_str(), success ? "OK" : "FAIL"); if (!success) state = false; ///// Dynamic width // String dynamic width format = "fish %*s frog"; args.clear(); args.push_back(10); args.push_back("cheese"); output = format.sprintf(args, &error); success = (output == String("fish cheese frog") && !error); OS::get_singleton()->print(output_format, format.c_str(), output.c_str(), success ? "OK" : "FAIL"); if (!success) state = false; // Int dynamic width format = "fish %*d frog"; args.clear(); args.push_back(10); args.push_back(99); output = format.sprintf(args, &error); success = (output == String("fish 99 frog") && !error); OS::get_singleton()->print(output_format, format.c_str(), output.c_str(), success ? "OK" : "FAIL"); if (!success) state = false; // Float dynamic width format = "fish %*.*f frog"; args.clear(); args.push_back(10); args.push_back(3); args.push_back(99.99); output = format.sprintf(args, &error); success = (output == String("fish 99.990 frog") && !error); OS::get_singleton()->print(output_format, format.c_str(), output.c_str(), success ? "OK" : "FAIL"); if (!success) state = false; ///// Errors // More formats than arguments. format = "fish %s %s frog"; args.clear(); args.push_back("cheese"); output = format.sprintf(args, &error); success = (output == "not enough arguments for format string" && error); OS::get_singleton()->print(output_format, format.c_str(), output.c_str(), success ? "OK" : "FAIL"); if (!success) state = false; // More arguments than formats. format = "fish %s frog"; args.clear(); args.push_back("hello"); args.push_back("cheese"); output = format.sprintf(args, &error); success = (output == "not all arguments converted during string formatting" && error); OS::get_singleton()->print(output_format, format.c_str(), output.c_str(), success ? "OK" : "FAIL"); if (!success) state = false; // Incomplete format. format = "fish %10"; args.clear(); args.push_back("cheese"); output = format.sprintf(args, &error); success = (output == "incomplete format" && error); OS::get_singleton()->print(output_format, format.c_str(), output.c_str(), success ? "OK" : "FAIL"); if (!success) state = false; // Bad character in format string format = "fish %&f frog"; args.clear(); args.push_back("cheese"); output = format.sprintf(args, &error); success = (output == "unsupported format character" && error); OS::get_singleton()->print(output_format, format.c_str(), output.c_str(), success ? "OK" : "FAIL"); if (!success) state = false; // Too many decimals. format = "fish %2.2.2f frog"; args.clear(); args.push_back(99.99); output = format.sprintf(args, &error); success = (output == "too many decimal points in format" && error); OS::get_singleton()->print(output_format, format.c_str(), output.c_str(), success ? "OK" : "FAIL"); if (!success) state = false; // * not a number format = "fish %*f frog"; args.clear(); args.push_back("cheese"); args.push_back(99.99); output = format.sprintf(args, &error); success = (output == "* wants number" && error); OS::get_singleton()->print(output_format, format.c_str(), output.c_str(), success ? "OK" : "FAIL"); if (!success) state = false; // Character too long. format = "fish %c frog"; args.clear(); args.push_back("sc"); output = format.sprintf(args, &error); success = (output == "%c requires number or single-character string" && error); OS::get_singleton()->print(output_format, format.c_str(), output.c_str(), success ? "OK" : "FAIL"); if (!success) state = false; // Character bad type. format = "fish %c frog"; args.clear(); args.push_back(Array()); output = format.sprintf(args, &error); success = (output == "%c requires number or single-character string" && error); OS::get_singleton()->print(output_format, format.c_str(), output.c_str(), success ? "OK" : "FAIL"); if (!success) state = false; return state; }
void Environment::load_argv(int argc, char** argv) { Array* os_ary = Array::create(state, argc); for(int i = 0; i < argc; i++) { os_ary->set(state, i, String::create(state, argv[i])); } G(rubinius)->set_const(state, "OS_ARGV", os_ary); char buf[MAXPATHLEN]; G(rubinius)->set_const(state, "OS_STARTUP_DIR", String::create(state, getcwd(buf, MAXPATHLEN))); state->vm()->set_const("ARG0", String::create(state, argv[0])); Array* ary = Array::create(state, argc - 1); int which_arg = 0; bool skip_xflags = true; for(int i=1; i < argc; i++) { char* arg = argv[i]; if(strcmp(arg, "--") == 0) { skip_xflags = false; } else if(strncmp(arg, "-X", 2) == 0) { if(skip_xflags) continue; } else if(arg[1] != '-') { skip_xflags = false; } ary->set(state, which_arg++, String::create(state, arg)->taint(state)); } state->vm()->set_const("ARGV", ary); // Now finish up with the config if(config.print_config > 1) { std::cout << "========= Configuration =========\n"; config.print(true); std::cout << "=================================\n"; } else if(config.print_config) { config.print(); } if(config.agent_start > 0) { // if port_ is 1, the user wants to use a randomly assigned local // port which will be written to the temp file for console to pick // up. int port = config.agent_start; if(port == 1) port = 0; start_agent(port); } if(config.report_path.set_p()) { // Test that we can actually use this path int fd = open(config.report_path, O_RDONLY | O_CREAT, 0666); if(!fd) { std::cerr << "Unable to use " << config.report_path << " for crash reports.\n"; std::cerr << "Unable to open path: " << strerror(errno) << "\n"; // Don't use the home dir path even, just use stderr report_path[0] = 0; } else { close(fd); unlink(config.report_path); strncpy(report_path, config.report_path, sizeof(report_path) - 1); } } }
HANDLE PASCAL RAROpenArchiveEx(struct RAROpenArchiveDataEx *r) { try { r->OpenResult=0; DataSet *Data=new DataSet; Data->Cmd.DllError=0; Data->OpenMode=r->OpenMode; Data->Cmd.FileArgs->AddString("*"); char an[NM]; if (r->ArcName==NULL && r->ArcNameW!=NULL) { WideToChar(r->ArcNameW,an,NM); r->ArcName=an; } Data->Cmd.AddArcName(r->ArcName,r->ArcNameW); Data->Cmd.Overwrite=OVERWRITE_ALL; Data->Cmd.VersionControl=1; Data->Cmd.Callback=r->Callback; Data->Cmd.UserData=r->UserData; if (!Data->Arc.Open(r->ArcName,r->ArcNameW)) { r->OpenResult=ERAR_EOPEN; delete Data; return(NULL); } if (!Data->Arc.IsArchive(false)) { r->OpenResult=Data->Cmd.DllError!=0 ? Data->Cmd.DllError:ERAR_BAD_ARCHIVE; delete Data; return(NULL); } r->Flags=Data->Arc.NewMhd.Flags; Array<byte> CmtData; if (r->CmtBufSize!=0 && Data->Arc.GetComment(&CmtData,NULL)) { r->Flags|=2; size_t Size=CmtData.Size()+1; r->CmtState=Size>r->CmtBufSize ? ERAR_SMALL_BUF:1; r->CmtSize=(uint)Min(Size,r->CmtBufSize); memcpy(r->CmtBuf,&CmtData[0],r->CmtSize-1); if (Size<=r->CmtBufSize) r->CmtBuf[r->CmtSize-1]=0; } else r->CmtState=r->CmtSize=0; if (Data->Arc.Signed) r->Flags|=0x20; Data->Extract.ExtractArchiveInit(&Data->Cmd,Data->Arc); return((HANDLE)Data); } catch (int ErrCode) { r->OpenResult=RarErrorToDll(ErrCode); return(NULL); } }
void Earth::setupGeometry() { // TODO: Write your own code here to tesselate and create texture coordinates for the Earth // and then save the data to VertexBuffers, AttributeArrays, and an IndexStream. The tesselation // should be based on the STACKS and SLICES parameters. const int STACKS = 20; const int SLICES = 40; Array<Vector3> cpuVerts, cpuNorms; Array<int> cpuIndices; Array<Vector2> texVerts; double delta_theta, delta_phi, theta, phi; delta_theta = pi() / STACKS; delta_phi = 2*pi() / SLICES; theta = 0; phi = 0; Vector3 first = Vector3(0, 1, 0);// North Pole Vector3 corner,corner2; int x = 0, y = 1, p = 0; for (int vertical = 0; vertical < STACKS; vertical++) { phi = 0; for (int horizontal = 0; horizontal <= SLICES; horizontal++) { corner = getPosition(theta + delta_theta, phi); phi += delta_phi; //corner2 = getPosition(theta+delta_theta, phi); Vector3 last = getPosition(theta, phi); Vector3 cross = (first - corner).cross(last - corner); cpuVerts.append(first, corner); cpuNorms.append(cross, cross); if (horizontal >0){ cpuIndices.append(x-2, y-2, y, y, x, x-2); } texVerts.append(Vector2(((horizontal*1.0))/SLICES, (vertical * 1.0)/STACKS), Vector2((horizontal* 1.0)/SLICES, ((vertical*1.0)+1)/STACKS)); y += 2; x += 2; debugPrintf("%d, corner: %f, %f, %f \n last: %f, %f, %f \n %f, %f \n", p++, corner.x, corner.y, corner.z, last.x, last.y, last.z, phi, theta); if (horizontal == SLICES){ first = corner; } else{ first = last; } } theta += delta_theta; } vbuffer = VertexBuffer::create((sizeof(Vector3) + sizeof(Vector3) + sizeof(Vector2)) * cpuVerts.size() + sizeof(int)*cpuIndices.size()); debugAssertGLOk(); gpuVerts = AttributeArray(cpuVerts, vbuffer); debugAssertGLOk(); gpuNorms = AttributeArray(cpuNorms, vbuffer); debugAssertGLOk(); gpuIndices = IndexStream(cpuIndices, vbuffer); debugAssertGLOk(); gpuTexCoords = AttributeArray(texVerts, vbuffer); debugAssertGLOk(); }
Ref<Mesh> Mesh::create_outline(float p_margin) const { Array arrays; int index_accum=0; for(int i=0;i<get_surface_count();i++) { if (surface_get_primitive_type(i)!=PRIMITIVE_TRIANGLES) continue; Array a = surface_get_arrays(i); int vcount=0; if (i==0) { arrays=a; DVector<Vector3> v=a[ARRAY_VERTEX]; index_accum+=v.size(); } else { for(int j=0;j<arrays.size();j++) { if (arrays[j].get_type()==Variant::NIL || a[j].get_type()==Variant::NIL) { //mismatch, do not use arrays[j]=Variant(); continue; } switch(j) { case ARRAY_VERTEX: case ARRAY_NORMAL: { DVector<Vector3> dst = arrays[j]; DVector<Vector3> src = a[j]; if (j==ARRAY_VERTEX) vcount=src.size(); if (dst.size()==0 || src.size()==0) { arrays[j]=Variant(); continue; } dst.append_array(src); arrays[j]=dst; } break; case ARRAY_TANGENT: case ARRAY_BONES: case ARRAY_WEIGHTS: { DVector<real_t> dst = arrays[j]; DVector<real_t> src = a[j]; if (dst.size()==0 || src.size()==0) { arrays[j]=Variant(); continue; } dst.append_array(src); arrays[j]=dst; } break; case ARRAY_COLOR: { DVector<Color> dst = arrays[j]; DVector<Color> src = a[j]; if (dst.size()==0 || src.size()==0) { arrays[j]=Variant(); continue; } dst.append_array(src); arrays[j]=dst; } break; case ARRAY_TEX_UV: case ARRAY_TEX_UV2: { DVector<Vector2> dst = arrays[j]; DVector<Vector2> src = a[j]; if (dst.size()==0 || src.size()==0) { arrays[j]=Variant(); continue; } dst.append_array(src); arrays[j]=dst; } break; case ARRAY_INDEX: { DVector<int> dst = arrays[j]; DVector<int> src = a[j]; if (dst.size()==0 || src.size()==0) { arrays[j]=Variant(); continue; } { int ss = src.size(); DVector<int>::Write w = src.write(); for(int k=0;k<ss;k++) { w[k]+=index_accum; } } dst.append_array(src); arrays[j]=dst; index_accum+=vcount; } break; } } } } { int tc=0; DVector<int>::Write ir; DVector<int> indices =arrays[ARRAY_INDEX]; bool has_indices=false; DVector<Vector3> vertices =arrays[ARRAY_VERTEX]; int vc = vertices.size(); ERR_FAIL_COND_V(!vc,Ref<Mesh>()); DVector<Vector3>::Write r=vertices.write(); if (indices.size()) { vc=indices.size(); ir=indices.write(); has_indices=true; } Map<Vector3,Vector3> normal_accum; //fill normals with triangle normals for(int i=0;i<vc;i+=3) { Vector3 t[3]; if (has_indices) { t[0]=r[ir[i+0]]; t[1]=r[ir[i+1]]; t[2]=r[ir[i+2]]; } else { t[0]=r[i+0]; t[1]=r[i+1]; t[2]=r[i+2]; } Vector3 n = Plane(t[0],t[1],t[2]).normal; for(int j=0;j<3;j++) { Map<Vector3,Vector3>::Element *E=normal_accum.find(t[j]); if (!E) { normal_accum[t[j]]=n; } else { float d = n.dot(E->get()); if (d<1.0) E->get()+=n*(1.0-d); //E->get()+=n; } } } //normalize for (Map<Vector3,Vector3>::Element *E=normal_accum.front();E;E=E->next()) { E->get().normalize(); } //displace normals int vc2 = vertices.size(); for(int i=0;i<vc2;i++) { Vector3 t=r[i]; Map<Vector3,Vector3>::Element *E=normal_accum.find(t); ERR_CONTINUE(!E); t+=E->get()*p_margin; r[i]=t; } r = DVector<Vector3>::Write(); arrays[ARRAY_VERTEX]=vertices; if (!has_indices) { DVector<int> new_indices; new_indices.resize(vertices.size()); DVector<int>::Write iw = new_indices.write(); for(int j=0;j<vc2;j+=3) { iw[j]=j; iw[j+1]=j+2; iw[j+2]=j+1; } iw=DVector<int>::Write(); arrays[ARRAY_INDEX]=new_indices; } else { for(int j=0;j<vc;j+=3) { SWAP(ir[j+1],ir[j+2]); } ir=DVector<int>::Write(); arrays[ARRAY_INDEX]=indices; } } Ref<Mesh> newmesh = memnew( Mesh ); newmesh->add_surface(PRIMITIVE_TRIANGLES,arrays); return newmesh; }
void refillCache (const int numSamples, double startTime, const double endTime, const double sampleRate, const int numChannels, const int samplesPerThumbSample, LevelDataSource* levelData, const OwnedArray<ThumbData>& channels) { const double timePerPixel = (endTime - startTime) / numSamples; if (numSamples <= 0 || timePerPixel <= 0.0 || sampleRate <= 0) { invalidate(); return; } if (numSamples == numSamplesCached && numChannelsCached == numChannels && startTime == cachedStart && timePerPixel == cachedTimePerPixel && ! cacheNeedsRefilling) { return; } numSamplesCached = numSamples; numChannelsCached = numChannels; cachedStart = startTime; cachedTimePerPixel = timePerPixel; cacheNeedsRefilling = false; ensureSize (numSamples); if (timePerPixel * sampleRate <= samplesPerThumbSample && levelData != nullptr) { int sample = roundToInt (startTime * sampleRate); Array<float> levels; int i; for (i = 0; i < numSamples; ++i) { const int nextSample = roundToInt ((startTime + timePerPixel) * sampleRate); if (sample >= 0) { if (sample >= levelData->lengthInSamples) break; levelData->getLevels (sample, jmax (1, nextSample - sample), levels); const int numChans = jmin (levels.size() / 2, numChannelsCached); for (int chan = 0; chan < numChans; ++chan) getData (chan, i)->setFloat (levels.getUnchecked (chan * 2), levels.getUnchecked (chan * 2 + 1)); } startTime += timePerPixel; sample = nextSample; } numSamplesCached = i; } else { jassert (channels.size() == numChannelsCached); for (int channelNum = 0; channelNum < numChannelsCached; ++channelNum) { ThumbData* channelData = channels.getUnchecked (channelNum); MinMaxValue* cacheData = getData (channelNum, 0); const double timeToThumbSampleFactor = sampleRate / (double) samplesPerThumbSample; startTime = cachedStart; int sample = roundToInt (startTime * timeToThumbSampleFactor); for (int i = numSamples; --i >= 0;) { const int nextSample = roundToInt ((startTime + timePerPixel) * timeToThumbSampleFactor); channelData->getMinMax (sample, nextSample, *cacheData); ++cacheData; startTime += timePerPixel; sample = nextSample; } } } }