void MozJSImplScope::setNumber(const char* field, double val) { MozJSEntry entry(this); ObjectWrapper(_context, _global).setNumber(field, val); }
static UniValue getblocktemplate(const JSONRPCRequest& request) { if (request.fHelp || request.params.size() > 1) throw std::runtime_error( "getblocktemplate ( TemplateRequest )\n" "\nIf the request parameters include a 'mode' key, that is used to explicitly select between the default 'template' request or a 'proposal'.\n" "It returns data needed to construct a block to work on.\n" "For full specification, see BIPs 22, 23, 9, and 145:\n" " https://github.com/digibyte/bips/blob/master/bip-0022.mediawiki\n" " https://github.com/digibyte/bips/blob/master/bip-0023.mediawiki\n" " https://github.com/digibyte/bips/blob/master/bip-0009.mediawiki#getblocktemplate_changes\n" " https://github.com/digibyte/bips/blob/master/bip-0145.mediawiki\n" "\nArguments:\n" "1. template_request (json object, optional) A json object in the following spec\n" " {\n" " \"mode\":\"template\" (string, optional) This must be set to \"template\", \"proposal\" (see BIP 23), or omitted\n" " \"capabilities\":[ (array, optional) A list of strings\n" " \"support\" (string) client side supported feature, 'longpoll', 'coinbasetxn', 'coinbasevalue', 'proposal', 'serverlist', 'workid'\n" " ,...\n" " ],\n" " \"rules\":[ (array, optional) A list of strings\n" " \"support\" (string) client side supported softfork deployment\n" " ,...\n" " ]\n" " }\n" "\n" "\nResult:\n" "{\n" " \"version\" : n, (numeric) The preferred block version\n" " \"rules\" : [ \"rulename\", ... ], (array of strings) specific block rules that are to be enforced\n" " \"vbavailable\" : { (json object) set of pending, supported versionbit (BIP 9) softfork deployments\n" " \"rulename\" : bitnumber (numeric) identifies the bit number as indicating acceptance and readiness for the named softfork rule\n" " ,...\n" " },\n" " \"vbrequired\" : n, (numeric) bit mask of versionbits the server requires set in submissions\n" " \"previousblockhash\" : \"xxxx\", (string) The hash of current highest block\n" " \"transactions\" : [ (array) contents of non-coinbase transactions that should be included in the next block\n" " {\n" " \"data\" : \"xxxx\", (string) transaction data encoded in hexadecimal (byte-for-byte)\n" " \"txid\" : \"xxxx\", (string) transaction id encoded in little-endian hexadecimal\n" " \"hash\" : \"xxxx\", (string) hash encoded in little-endian hexadecimal (including witness data)\n" " \"depends\" : [ (array) array of numbers \n" " n (numeric) transactions before this one (by 1-based index in 'transactions' list) that must be present in the final block if this one is\n" " ,...\n" " ],\n" " \"fee\": n, (numeric) difference in value between transaction inputs and outputs (in satoshis); for coinbase transactions, this is a negative Number of the total collected block fees (ie, not including the block subsidy); if key is not present, fee is unknown and clients MUST NOT assume there isn't one\n" " \"sigops\" : n, (numeric) total SigOps cost, as counted for purposes of block limits; if key is not present, sigop cost is unknown and clients MUST NOT assume it is zero\n" " \"weight\" : n, (numeric) total transaction weight, as counted for purposes of block limits\n" " }\n" " ,...\n" " ],\n" " \"coinbaseaux\" : { (json object) data that should be included in the coinbase's scriptSig content\n" " \"flags\" : \"xx\" (string) key name is to be ignored, and value included in scriptSig\n" " },\n" " \"coinbasevalue\" : n, (numeric) maximum allowable input to coinbase transaction, including the generation award and transaction fees (in satoshis)\n" " \"coinbasetxn\" : { ... }, (json object) information for coinbase transaction\n" " \"target\" : \"xxxx\", (string) The hash target\n" " \"mintime\" : xxx, (numeric) The minimum timestamp appropriate for next block time in seconds since epoch (Jan 1 1970 GMT)\n" " \"mutable\" : [ (array of string) list of ways the block template may be changed \n" " \"value\" (string) A way the block template may be changed, e.g. 'time', 'transactions', 'prevblock'\n" " ,...\n" " ],\n" " \"noncerange\" : \"00000000ffffffff\",(string) A range of valid nonces\n" " \"sigoplimit\" : n, (numeric) limit of sigops in blocks\n" " \"sizelimit\" : n, (numeric) limit of block size\n" " \"weightlimit\" : n, (numeric) limit of block weight\n" " \"curtime\" : ttt, (numeric) current timestamp in seconds since epoch (Jan 1 1970 GMT)\n" " \"bits\" : \"xxxxxxxx\", (string) compressed target of next block\n" " \"height\" : n (numeric) The height of the next block\n" "}\n" "\nExamples:\n" + HelpExampleCli("getblocktemplate", "") + HelpExampleRpc("getblocktemplate", "") ); LOCK(cs_main); std::string strMode = "template"; UniValue lpval = NullUniValue; std::set<std::string> setClientRules; int64_t nMaxVersionPreVB = -1; if (!request.params[0].isNull()) { const UniValue& oparam = request.params[0].get_obj(); const UniValue& modeval = find_value(oparam, "mode"); if (modeval.isStr()) strMode = modeval.get_str(); else if (modeval.isNull()) { /* Do nothing */ } else throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode"); lpval = find_value(oparam, "longpollid"); if (strMode == "proposal") { const UniValue& dataval = find_value(oparam, "data"); if (!dataval.isStr()) throw JSONRPCError(RPC_TYPE_ERROR, "Missing data String key for proposal"); CBlock block; if (!DecodeHexBlk(block, dataval.get_str())) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed"); uint256 hash = block.GetHash(); const CBlockIndex* pindex = LookupBlockIndex(hash); if (pindex) { if (pindex->IsValid(BLOCK_VALID_SCRIPTS)) return "duplicate"; if (pindex->nStatus & BLOCK_FAILED_MASK) return "duplicate-invalid"; return "duplicate-inconclusive"; } CBlockIndex* const pindexPrev = chainActive.Tip(); // TestBlockValidity only supports blocks built on the current Tip if (block.hashPrevBlock != pindexPrev->GetBlockHash()) return "inconclusive-not-best-prevblk"; CValidationState state; TestBlockValidity(state, Params(), block, pindexPrev, false, true); return BIP22ValidationResult(state); } const UniValue& aClientRules = find_value(oparam, "rules"); if (aClientRules.isArray()) { for (unsigned int i = 0; i < aClientRules.size(); ++i) { const UniValue& v = aClientRules[i]; setClientRules.insert(v.get_str()); } } else { // NOTE: It is important that this NOT be read if versionbits is supported const UniValue& uvMaxVersion = find_value(oparam, "maxversion"); if (uvMaxVersion.isNum()) { nMaxVersionPreVB = uvMaxVersion.get_int64(); } } } if (strMode != "template") throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode"); if(!g_connman) throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled"); if (g_connman->GetNodeCount(CConnman::CONNECTIONS_ALL) == 0) throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "DigiByte is not connected!"); if (IsInitialBlockDownload()) throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "DigiByte is downloading blocks..."); static unsigned int nTransactionsUpdatedLast; if (!lpval.isNull()) { // Wait to respond until either the best block changes, OR a minute has passed and there are more transactions uint256 hashWatchedChain; std::chrono::steady_clock::time_point checktxtime; unsigned int nTransactionsUpdatedLastLP; if (lpval.isStr()) { // Format: <hashBestChain><nTransactionsUpdatedLast> std::string lpstr = lpval.get_str(); hashWatchedChain.SetHex(lpstr.substr(0, 64)); nTransactionsUpdatedLastLP = atoi64(lpstr.substr(64)); } else { // NOTE: Spec does not specify behaviour for non-string longpollid, but this makes testing easier hashWatchedChain = chainActive.Tip()->GetBlockHash(); nTransactionsUpdatedLastLP = nTransactionsUpdatedLast; } // Release the wallet and main lock while waiting LEAVE_CRITICAL_SECTION(cs_main); { checktxtime = std::chrono::steady_clock::now() + std::chrono::minutes(1); WaitableLock lock(g_best_block_mutex); while (g_best_block == hashWatchedChain && IsRPCRunning()) { if (g_best_block_cv.wait_until(lock, checktxtime) == std::cv_status::timeout) { // Timeout: Check transactions for update if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLastLP) break; checktxtime += std::chrono::seconds(10); } } } ENTER_CRITICAL_SECTION(cs_main); if (!IsRPCRunning()) throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Shutting down"); // TODO: Maybe recheck connections/IBD and (if something wrong) send an expires-immediately template to stop miners? } const struct VBDeploymentInfo& segwit_info = VersionBitsDeploymentInfo[Consensus::DEPLOYMENT_SEGWIT]; // If the caller is indicating segwit support, then allow CreateNewBlock() // to select witness transactions, after segwit activates (otherwise // don't). bool fSupportsSegwit = setClientRules.find(segwit_info.name) != setClientRules.end(); // Update block static CBlockIndex* pindexPrev; static int64_t nStart; static std::unique_ptr<CBlockTemplate> pblocktemplate; // Cache whether the last invocation was with segwit support, to avoid returning // a segwit-block to a non-segwit caller. static bool fLastTemplateSupportsSegwit = true; if (pindexPrev != chainActive.Tip() || (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 5) || fLastTemplateSupportsSegwit != fSupportsSegwit) { // Clear pindexPrev so future calls make a new block, despite any failures from here on pindexPrev = nullptr; // Store the pindexBest used before CreateNewBlock, to avoid races nTransactionsUpdatedLast = mempool.GetTransactionsUpdated(); CBlockIndex* pindexPrevNew = chainActive.Tip(); nStart = GetTime(); fLastTemplateSupportsSegwit = fSupportsSegwit; // Create new block CScript scriptDummy = CScript() << OP_TRUE; pblocktemplate = BlockAssembler(Params()).CreateNewBlock(scriptDummy, miningAlgo, fSupportsSegwit); if (!pblocktemplate) throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory"); // Need to update only after we know CreateNewBlock succeeded pindexPrev = pindexPrevNew; } assert(pindexPrev); CBlock* pblock = &pblocktemplate->block; // pointer for convenience const Consensus::Params& consensusParams = Params().GetConsensus(); // Update nTime UpdateTime(pblock, consensusParams, pindexPrev, miningAlgo); pblock->nNonce = 0; // NOTE: If at some point we support pre-segwit miners post-segwit-activation, this needs to take segwit support into consideration const bool fPreSegWit = (ThresholdState::ACTIVE != VersionBitsState(pindexPrev, consensusParams, Consensus::DEPLOYMENT_SEGWIT, versionbitscache)); UniValue aCaps(UniValue::VARR); aCaps.push_back("proposal"); UniValue transactions(UniValue::VARR); std::map<uint256, int64_t> setTxIndex; int i = 0; for (const auto& it : pblock->vtx) { const CTransaction& tx = *it; uint256 txHash = tx.GetHash(); setTxIndex[txHash] = i++; if (tx.IsCoinBase()) continue; UniValue entry(UniValue::VOBJ); entry.pushKV("data", EncodeHexTx(tx)); entry.pushKV("txid", txHash.GetHex()); entry.pushKV("hash", tx.GetWitnessHash().GetHex()); UniValue deps(UniValue::VARR); for (const CTxIn &in : tx.vin) { if (setTxIndex.count(in.prevout.hash)) deps.push_back(setTxIndex[in.prevout.hash]); } entry.pushKV("depends", deps); int index_in_template = i - 1; entry.pushKV("fee", pblocktemplate->vTxFees[index_in_template]); int64_t nTxSigOps = pblocktemplate->vTxSigOpsCost[index_in_template]; if (fPreSegWit) { assert(nTxSigOps % WITNESS_SCALE_FACTOR == 0); nTxSigOps /= WITNESS_SCALE_FACTOR; } entry.pushKV("sigops", nTxSigOps); entry.pushKV("weight", GetTransactionWeight(tx)); transactions.push_back(entry); } UniValue aux(UniValue::VOBJ); aux.pushKV("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())); arith_uint256 hashTarget = arith_uint256().SetCompact(pblock->nBits); UniValue aMutable(UniValue::VARR); aMutable.push_back("time"); aMutable.push_back("transactions"); aMutable.push_back("prevblock"); UniValue result(UniValue::VOBJ); result.pushKV("capabilities", aCaps); UniValue aRules(UniValue::VARR); UniValue vbavailable(UniValue::VOBJ); for (int j = 0; j < (int)Consensus::MAX_VERSION_BITS_DEPLOYMENTS; ++j) { Consensus::DeploymentPos pos = Consensus::DeploymentPos(j); ThresholdState state = VersionBitsState(pindexPrev, consensusParams, pos, versionbitscache); switch (state) { case ThresholdState::DEFINED: case ThresholdState::FAILED: // Not exposed to GBT at all break; case ThresholdState::LOCKED_IN: // Ensure bit is set in block version pblock->nVersion |= VersionBitsMask(consensusParams, pos); // FALL THROUGH to get vbavailable set... case ThresholdState::STARTED: { const struct VBDeploymentInfo& vbinfo = VersionBitsDeploymentInfo[pos]; vbavailable.pushKV(gbt_vb_name(pos), consensusParams.vDeployments[pos].bit); if (setClientRules.find(vbinfo.name) == setClientRules.end()) { if (!vbinfo.gbt_force) { // If the client doesn't support this, don't indicate it in the [default] version pblock->nVersion &= ~VersionBitsMask(consensusParams, pos); } } break; } case ThresholdState::ACTIVE: { // Add to rules only const struct VBDeploymentInfo& vbinfo = VersionBitsDeploymentInfo[pos]; aRules.push_back(gbt_vb_name(pos)); if (setClientRules.find(vbinfo.name) == setClientRules.end()) { // Not supported by the client; make sure it's safe to proceed if (!vbinfo.gbt_force) { // If we do anything other than throw an exception here, be sure version/force isn't sent to old clients throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Support for '%s' rule requires explicit client support", vbinfo.name)); } } break; } } } result.pushKV("version", pblock->nVersion); result.pushKV("rules", aRules); result.pushKV("vbavailable", vbavailable); result.pushKV("vbrequired", int(0)); if (nMaxVersionPreVB >= 2) { // If VB is supported by the client, nMaxVersionPreVB is -1, so we won't get here // Because BIP 34 changed how the generation transaction is serialized, we can only use version/force back to v2 blocks // This is safe to do [otherwise-]unconditionally only because we are throwing an exception above if a non-force deployment gets activated // Note that this can probably also be removed entirely after the first BIP9 non-force deployment (ie, probably segwit) gets activated aMutable.push_back("version/force"); } result.pushKV("previousblockhash", pblock->hashPrevBlock.GetHex()); result.pushKV("transactions", transactions); result.pushKV("coinbaseaux", aux); result.pushKV("coinbasevalue", (int64_t)pblock->vtx[0]->vout[0].nValue); result.pushKV("longpollid", chainActive.Tip()->GetBlockHash().GetHex() + i64tostr(nTransactionsUpdatedLast)); result.pushKV("target", hashTarget.GetHex()); result.pushKV("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1); result.pushKV("mutable", aMutable); result.pushKV("noncerange", "00000000ffffffff"); int64_t nSigOpLimit = MAX_BLOCK_SIGOPS_COST; int64_t nSizeLimit = MAX_BLOCK_SERIALIZED_SIZE; if (fPreSegWit) { assert(nSigOpLimit % WITNESS_SCALE_FACTOR == 0); nSigOpLimit /= WITNESS_SCALE_FACTOR; assert(nSizeLimit % WITNESS_SCALE_FACTOR == 0); nSizeLimit /= WITNESS_SCALE_FACTOR; } result.pushKV("sigoplimit", nSigOpLimit); result.pushKV("sizelimit", nSizeLimit); if (!fPreSegWit) { result.pushKV("weightlimit", (int64_t)MAX_BLOCK_WEIGHT); } result.pushKV("curtime", pblock->GetBlockTime()); result.pushKV("bits", strprintf("%08x", pblock->nBits)); result.pushKV("height", (int64_t)(pindexPrev->nHeight+1)); if (!pblocktemplate->vchCoinbaseCommitment.empty() && fSupportsSegwit) { result.pushKV("default_witness_commitment", HexStr(pblocktemplate->vchCoinbaseCommitment.begin(), pblocktemplate->vchCoinbaseCommitment.end())); } return result; }
void Translation::addPair(const wstring& english, const wstring& translated) // Add a wstring pair to the translation vector. { pair<wstring, wstring> entry (english, translated); m_translation.push_back(entry); }
inline void TwoSidedTrsmUVar2( UnitOrNonUnit diag, Matrix<F>& A, const Matrix<F>& U ) { #ifndef RELEASE CallStackEntry entry("internal::TwoSidedTrsmUVar2"); if( A.Height() != A.Width() ) LogicError("A must be square"); if( U.Height() != U.Width() ) LogicError("Triangular matrices must be square"); if( A.Height() != U.Height() ) LogicError("A and U must be the same size"); #endif // Matrix views Matrix<F> ATL, ATR, A00, A01, A02, ABL, ABR, A10, A11, A12, A20, A21, A22; Matrix<F> UTL, UTR, U00, U01, U02, UBL, UBR, U10, U11, U12, U20, U21, U22; // Temporary products Matrix<F> Y01; PartitionDownDiagonal ( A, ATL, ATR, ABL, ABR, 0 ); LockedPartitionDownDiagonal ( U, UTL, UTR, UBL, UBR, 0 ); while( ATL.Height() < A.Height() ) { RepartitionDownDiagonal ( ATL, /**/ ATR, A00, /**/ A01, A02, /*************/ /******************/ /**/ A10, /**/ A11, A12, ABL, /**/ ABR, A20, /**/ A21, A22 ); LockedRepartitionDownDiagonal ( UTL, /**/ UTR, U00, /**/ U01, U02, /*************/ /******************/ /**/ U10, /**/ U11, U12, UBL, /**/ UBR, U20, /**/ U21, U22 ); //--------------------------------------------------------------------// // Y01 := A00 U01 Zeros( Y01, A01.Height(), A01.Width() ); Hemm( LEFT, UPPER, F(1), A00, U01, F(0), Y01 ); // A01 := A01 - 1/2 Y01 Axpy( F(-1)/F(2), Y01, A01 ); // A11 := A11 - (U01' A01 + A01' U01) Her2k( UPPER, ADJOINT, F(-1), U01, A01, F(1), A11 ); // A11 := inv(U11)' A11 inv(U11) TwoSidedTrsmUUnb( diag, A11, U11 ); // A12 := A12 - A02' U01 Gemm( ADJOINT, NORMAL, F(-1), A02, U01, F(1), A12 ); // A12 := inv(U11)' A12 Trsm( LEFT, UPPER, ADJOINT, diag, F(1), U11, A12 ); // A01 := A01 - 1/2 Y01 Axpy( F(-1)/F(2), Y01, A01 ); // A01 := A01 inv(U11) Trsm( RIGHT, UPPER, NORMAL, diag, F(1), U11, A01 ); //--------------------------------------------------------------------// SlidePartitionDownDiagonal ( ATL, /**/ ATR, A00, A01, /**/ A02, /**/ A10, A11, /**/ A12, /*************/ /******************/ ABL, /**/ ABR, A20, A21, /**/ A22 ); SlideLockedPartitionDownDiagonal ( UTL, /**/ UTR, U00, U01, /**/ U02, /**/ U10, U11, /**/ U12, /*************/ /******************/ UBL, /**/ UBR, U20, U21, /**/ U22 ); } }
status_t FilePlaylistItem::RestoreFromTrash() { if (fNameInTrash.Length() <= 0) { // Not in the trash! return B_ERROR; } char trashPath[B_PATH_NAME_LENGTH]; status_t err = find_directory(B_TRASH_DIRECTORY, fRef.device, false /*create it*/, trashPath, B_PATH_NAME_LENGTH); if (err != B_OK) { fprintf(stderr, "failed to find Trash: %s\n", strerror(err)); return err; } // construct the entry to the file in the trash // TODO: BEntry(const BDirectory* directory, const char* path) is broken! // BEntry entry(trashPath, fNamesInTrash[i].String()); BPath path(trashPath, fNameInTrash.String()); BEntry entry(path.Path()); err = entry.InitCheck(); if (err != B_OK) { fprintf(stderr, "failed to init BEntry for %s: %s\n", fNameInTrash.String(), strerror(err)); return err; } //entry.GetPath(&path); //printf("moving '%s'\n", path.Path()); // construct the folder of the original entry_ref node_ref nodeRef; nodeRef.device = fRef.device; nodeRef.node = fRef.directory; BDirectory originalDir(&nodeRef); err = originalDir.InitCheck(); if (err != B_OK) { fprintf(stderr, "failed to init original BDirectory for " "%s: %s\n", fRef.name, strerror(err)); return err; } //path.SetTo(&originalDir, fItems[i].name); //printf("as '%s'\n", path.Path()); // Reset the name here, the user may have already moved the entry // out of the trash via Tracker for example. fNameInTrash = ""; // Finally, move the entry back into the original folder err = entry.MoveTo(&originalDir, fRef.name); if (err != B_OK) { fprintf(stderr, "failed to restore entry from trash " "%s: %s\n", fRef.name, strerror(err)); return err; } // Remove the attribute that helps Tracker restore the entry. BNode node(&entry); node.RemoveAttr("_trk/original_path"); return err; }
TFilePanel::TFilePanel(file_panel_mode mode, BMessenger* target, const BEntry* startDir, uint32 nodeFlavors, bool multipleSelection, BMessage* message, BRefFilter* filter, uint32 containerWindowFlags, window_look look, window_feel feel, bool hideWhenDone) : BContainerWindow(0, containerWindowFlags, look, feel, 0, B_CURRENT_WORKSPACE, false), fDirMenu(NULL), fDirMenuField(NULL), fTextControl(NULL), fClientObject(NULL), fSelectionIterator(0), fMessage(NULL), fHideWhenDone(hideWhenDone), fIsTrackingMenu(false) { InitIconPreloader(); fIsSavePanel = (mode == B_SAVE_PANEL); BRect windRect(85, 50, 568, 296); MoveTo(windRect.LeftTop()); ResizeTo(windRect.Width(), windRect.Height()); fNodeFlavors = (nodeFlavors == 0) ? B_FILE_NODE : nodeFlavors; if (target) fTarget = *target; else fTarget = BMessenger(be_app); if (message) SetMessage(message); else if (fIsSavePanel) fMessage = new BMessage(B_SAVE_REQUESTED); else fMessage = new BMessage(B_REFS_RECEIVED); gLocalizedNamePreferred = BLocaleRoster::Default()->IsFilesystemTranslationPreferred(); // check for legal starting directory Model* model = new Model(); bool useRoot = true; if (startDir) { if (model->SetTo(startDir) == B_OK && model->IsDirectory()) useRoot = false; else { delete model; model = new Model(); } } if (useRoot) { BPath path; if (find_directory(B_USER_DIRECTORY, &path) == B_OK) { BEntry entry(path.Path(), true); if (entry.InitCheck() == B_OK && model->SetTo(&entry) == B_OK) useRoot = false; } } if (useRoot) { BVolume volume; BDirectory root; BVolumeRoster volumeRoster; volumeRoster.GetBootVolume(&volume); volume.GetRootDirectory(&root); BEntry entry; root.GetEntry(&entry); model->SetTo(&entry); } fTaskLoop = new PiggybackTaskLoop; AutoLock<BWindow> lock(this); fBorderedView = new BorderedView; CreatePoseView(model); fPoseView->SetRefFilter(filter); if (!fIsSavePanel) fPoseView->SetMultipleSelection(multipleSelection); fPoseView->SetFlags(fPoseView->Flags() | B_NAVIGABLE); fPoseView->SetPoseEditing(false); AddCommonFilter(new BMessageFilter(B_KEY_DOWN, key_down_filter)); AddCommonFilter(new BMessageFilter(B_SIMPLE_DATA, TFilePanel::MessageDropFilter)); AddCommonFilter(new BMessageFilter(B_NODE_MONITOR, TFilePanel::FSFilter)); // inter-application observing BMessenger tracker(kTrackerSignature); BHandler::StartWatching(tracker, kDesktopFilePanelRootChanged); Init(); }
void TFilePanel::Init(const BMessage*) { BRect windRect(Bounds()); fBackView = new BView(Bounds(), "View", B_FOLLOW_ALL, 0); fBackView->SetViewColor(ui_color(B_PANEL_BACKGROUND_COLOR)); AddChild(fBackView); // add poseview menu bar fMenuBar = new BMenuBar(BRect(0, 0, windRect.Width(), 1), "MenuBar"); fMenuBar->SetBorder(B_BORDER_FRAME); fBackView->AddChild(fMenuBar); // add directory menu and menufield fDirMenu = new BDirMenu(0, this, kSwitchDirectory, "refs"); font_height ht; be_plain_font->GetHeight(&ht); float f_height = ht.ascent + ht.descent + ht.leading; BRect rect; rect.top = fMenuBar->Bounds().Height() + 8; rect.left = windRect.left + 8; rect.right = rect.left + 300; rect.bottom = rect.top + (f_height > 22 ? f_height : 22); fDirMenuField = new BMenuField(rect, "DirMenuField", "", fDirMenu); fDirMenuField->MenuBar()->SetFont(be_plain_font); fDirMenuField->SetDivider(0); fDirMenuField->MenuBar()->SetMaxContentWidth(rect.Width() - 26.0f); // Make room for the icon fDirMenuField->MenuBar()->RemoveItem((int32)0); fDirMenu->SetMenuBar(fDirMenuField->MenuBar()); // the above is a weird call from BDirMenu // ToDo: clean up BEntry entry(TargetModel()->EntryRef()); if (entry.InitCheck() == B_OK) fDirMenu->Populate(&entry, 0, true, true, false, true); else fDirMenu->Populate(0, 0, true, true, false, true); fBackView->AddChild(fDirMenuField); // add file name text view if (fIsSavePanel) { BRect rect(windRect); rect.top = rect.bottom - 35; rect.left = 8; rect.right = rect.left + 170; rect.bottom = rect.top + 13; fTextControl = new BTextControl(rect, "text view", B_TRANSLATE("save text"), "", NULL, B_FOLLOW_LEFT | B_FOLLOW_BOTTOM); DisallowMetaKeys(fTextControl->TextView()); DisallowFilenameKeys(fTextControl->TextView()); fBackView->AddChild(fTextControl); fTextControl->SetDivider(0.0f); fTextControl->TextView()->SetMaxBytes(B_FILE_NAME_LENGTH - 1); fButtonText.SetTo(B_TRANSLATE("Save")); } else fButtonText.SetTo(B_TRANSLATE("Open")); // Add PoseView fBorderedView->SetName("PoseView"); fBorderedView->SetResizingMode(B_FOLLOW_ALL); fBorderedView->EnableBorderHighlight(true); rect = windRect; rect.OffsetTo(10, fDirMenuField->Frame().bottom + 10); rect.bottom = windRect.bottom - 60; rect.right -= B_V_SCROLL_BAR_WIDTH + 20; fBorderedView->MoveTo(rect.LeftTop()); fBorderedView->ResizeTo(rect.Width(), rect.Height()); PoseView()->AddScrollBars(); PoseView()->SetDragEnabled(false); PoseView()->SetDropEnabled(false); PoseView()->SetSelectionHandler(this); PoseView()->SetSelectionChangedHook(true); PoseView()->DisableSaveLocation(); // horizontal rect = fBorderedView->Frame(); rect.top = rect.bottom; rect.bottom = rect.top + (float)B_H_SCROLL_BAR_HEIGHT; PoseView()->HScrollBar()->MoveTo(rect.LeftTop()); PoseView()->HScrollBar()->ResizeTo(rect.Size()); PoseView()->HScrollBar()->SetResizingMode(B_FOLLOW_LEFT_RIGHT | B_FOLLOW_BOTTOM); fBackView->AddChild(PoseView()->HScrollBar()); // vertical rect = fBorderedView->Frame(); rect.left = rect.right; rect.right = rect.left + (float)B_V_SCROLL_BAR_WIDTH; PoseView()->VScrollBar()->MoveTo(rect.LeftTop()); PoseView()->VScrollBar()->ResizeTo(rect.Size()); PoseView()->VScrollBar()->SetResizingMode(B_FOLLOW_TOP_BOTTOM | B_FOLLOW_RIGHT); fBackView->AddChild(PoseView()->VScrollBar()); if (fIsSavePanel) fBackView->AddChild(fBorderedView, fTextControl); else fBackView->AddChild(fBorderedView); AddShortcut('W', B_COMMAND_KEY, new BMessage(kCancelButton)); AddShortcut('H', B_COMMAND_KEY, new BMessage(kSwitchToHome)); AddShortcut('A', B_COMMAND_KEY | B_SHIFT_KEY, new BMessage(kShowSelectionWindow)); AddShortcut('A', B_COMMAND_KEY, new BMessage(B_SELECT_ALL), PoseView()); AddShortcut('S', B_COMMAND_KEY, new BMessage(kInvertSelection), PoseView()); AddShortcut('Y', B_COMMAND_KEY, new BMessage(kResizeToFit), PoseView()); AddShortcut(B_DOWN_ARROW, B_COMMAND_KEY, new BMessage(kOpenDir)); AddShortcut(B_DOWN_ARROW, B_COMMAND_KEY | B_OPTION_KEY, new BMessage(kOpenDir)); AddShortcut(B_UP_ARROW, B_COMMAND_KEY, new BMessage(kOpenParentDir)); AddShortcut(B_UP_ARROW, B_COMMAND_KEY | B_OPTION_KEY, new BMessage(kOpenParentDir)); // New code to make buttons font sensitive rect = windRect; rect.top = rect.bottom - 35; rect.bottom -= 10; rect.right -= 25; float default_width = be_plain_font->StringWidth(fButtonText.String()) + 20; rect.left = default_width > 75 ? rect.right - default_width : rect.right - 75; BButton* default_button = new BButton(rect, "default button", fButtonText.String(), new BMessage(kDefaultButton), B_FOLLOW_RIGHT + B_FOLLOW_BOTTOM); fBackView->AddChild(default_button); rect.right = rect.left -= 10; float cancel_width = be_plain_font->StringWidth(B_TRANSLATE("Cancel")) + 20; rect.left = cancel_width > 75 ? rect.right - cancel_width : rect.right - 75; BButton* cancel_button = new BButton(rect, "cancel button", B_TRANSLATE("Cancel"), new BMessage(kCancelButton), B_FOLLOW_RIGHT + B_FOLLOW_BOTTOM); fBackView->AddChild(cancel_button); if (!fIsSavePanel) default_button->SetEnabled(false); default_button->MakeDefault(true); RestoreState(); AddMenus(); AddContextMenus(); FavoritesMenu* favorites = new FavoritesMenu(B_TRANSLATE("Favorites"), new BMessage(kSwitchDirectory), new BMessage(B_REFS_RECEIVED), BMessenger(this), IsSavePanel(), fPoseView->RefFilter()); favorites->AddItem(new BMenuItem(B_TRANSLATE("Add current folder"), new BMessage(kAddCurrentDir))); favorites->AddItem(new BMenuItem( B_TRANSLATE("Edit favorites" B_UTF8_ELLIPSIS), new BMessage(kEditFavorites))); fMenuBar->AddItem(favorites); // configure menus BMenuItem* item = fMenuBar->FindItem(B_TRANSLATE("Window")); if (item) { fMenuBar->RemoveItem(item); delete item; } item = fMenuBar->FindItem(B_TRANSLATE("File")); if (item) { BMenu* menu = item->Submenu(); if (menu) { item = menu->FindItem(kOpenSelection); if (item && menu->RemoveItem(item)) delete item; item = menu->FindItem(kDuplicateSelection); if (item && menu->RemoveItem(item)) delete item; // remove add-ons menu, identifier menu, separator item = menu->FindItem(B_TRANSLATE("Add-ons")); if (item) { int32 index = menu->IndexOf(item); delete menu->RemoveItem(index); delete menu->RemoveItem(--index); delete menu->RemoveItem(--index); } // remove separator item = menu->FindItem(B_CUT); if (item) { item = menu->ItemAt(menu->IndexOf(item)-1); if (item && menu->RemoveItem(item)) delete item; } } } PoseView()->ScrollTo(B_ORIGIN); PoseView()->UpdateScrollRange(); PoseView()->ScrollTo(B_ORIGIN); if (fTextControl) { fTextControl->MakeFocus(); fTextControl->TextView()->SelectAll(); } else PoseView()->MakeFocus(); app_info info; BString title; if (be_app->GetAppInfo(&info) == B_OK) { if (!gLocalizedNamePreferred || BLocaleRoster::Default()->GetLocalizedFileName( title, info.ref, false) != B_OK) title = info.ref.name; title << ": "; } title << fButtonText; // Open or Save SetTitle(title.String()); SetSizeLimits(370, 10000, 200, 10000); }
long long MozJSImplScope::getNumberLongLong(const char* field) { MozJSEntry entry(this); return ObjectWrapper(_context, _global).getNumberLongLong(field); }
Decimal128 MozJSImplScope::getNumberDecimal(const char* field) { MozJSEntry entry(this); return ObjectWrapper(_context, _global).getNumberDecimal(field); }
void MozJSImplScope::setObject(const char* field, const BSONObj& obj, bool readOnly) { MozJSEntry entry(this); ObjectWrapper(_context, _global).setBSON(field, obj, readOnly); }
int MozJSImplScope::type(const char* field) { MozJSEntry entry(this); return ObjectWrapper(_context, _global).type(field); }
void MozJSImplScope::setElement(const char* field, const BSONElement& e, const BSONObj& parent) { MozJSEntry entry(this); ObjectWrapper(_context, _global).setBSONElement(field, e, parent, false); }
void MozJSImplScope::setBoolean(const char* field, bool val) { MozJSEntry entry(this); ObjectWrapper(_context, _global).setBoolean(field, val); }
void MozJSImplScope::setString(const char* field, StringData val) { MozJSEntry entry(this); ObjectWrapper(_context, _global).setString(field, val); }
int main(int argc, char** argv) { if (argc == 1) return 1; Path entry(argv[1]); Base* base = new Base(); // fs::canonical(fs::initial_path()); Path exedir = boost::filesystem::system_complete(argv[0]).parent_path(); //std::cout << exedir / "../lib" << std::endl; base->add(exedir / "../lib"); // Library folder if (fs::exists(entry)) { base->add(entry.parent_path()); } else { if (fs::exists(fs::current_path() / entry)) { entry = fs::current_path() / entry; base->add(entry.parent_path()); } else { std::cout << "Can't find entry " << entry << "" << std::endl; return 1; } } Scope context(base); // Primairy types: context->create(Scope(new Primitive("void"))); context->create(Scope(new Primitive("bool"))); context->create(Scope(new Primitive("char"))); context->create(Scope(new Primitive("byte"))); // unsigned char context->create(Scope(new Primitive("int"))); context->create(Scope(new Primitive("uint"))); context->create(Scope(new Primitive("short"))); context->create(Scope(new Primitive("ushort"))); context->create(Scope(new Primitive("float"))); context->create(Scope(new Primitive("double"))); Parser parser(entry, context, entry.stem().string()); try { parser.parse(); if (String(argv[2]) == "info") { std::cout << context->representate() << std::endl; std::cout << "Generating code..." << std::endl; } context->generate(); } catch (p_Error e) { std::cout << context->representate() << std::endl << std::endl; std::cout << "An error occurred in: " << parser.scanner.file.filename() << std::endl << "on line " << parser.scanner.token_line << ", position " <<parser.scanner.token_pos << ":" << std::endl; std::cout << e->what() << std::endl; } catch (...) { std::cout << "Uknown exception occurred..." << std::endl; } return 0; }
std::string MozJSImplScope::getString(const char* field) { MozJSEntry entry(this); return ObjectWrapper(_context, _global).getString(field); }
void TFilePanel::MessageReceived(BMessage* message) { entry_ref ref; switch (message->what) { case B_REFS_RECEIVED: // item was double clicked in file panel (PoseView) if (message->FindRef("refs", &ref) == B_OK) { BEntry entry(&ref, true); if (entry.InitCheck() == B_OK) { // Double-click on dir or link-to-dir ALWAYS opens the // dir. If more than one dir is selected, the first is // entered. if (entry.IsDirectory()) { entry.GetRef(&ref); bool isDesktop = SwitchDirToDesktopIfNeeded(ref); PoseView()->SetIsDesktop(isDesktop); entry.SetTo(&ref); PoseView()->SwitchDir(&ref); SwitchDirMenuTo(&ref); } else { // Otherwise, we have a file or a link to a file. // AdjustButton has already tested the flavor; // all we have to do is see if the button is enabled. BButton* button = dynamic_cast<BButton*>( FindView("default button")); if (button == NULL) break; if (IsSavePanel()) { int32 count = 0; type_code type; message->GetInfo("refs", &type, &count); // Don't allow saves of multiple files if (count > 1) { ShowCenteredAlert( B_TRANSLATE( "Sorry, saving more than one " "item is not allowed."), B_TRANSLATE("Cancel")); } else { // if we are a savepanel, set up the // filepanel correctly then pass control // so we follow the same path as if the user // clicked the save button // set the 'name' fld to the current ref's // name notify the panel that the default // button should be enabled SetSaveText(ref.name); SelectionChanged(); HandleSaveButton(); } break; } // send handler a message and close BMessage openMessage(*fMessage); for (int32 index = 0; ; index++) { if (message->FindRef("refs", index, &ref) != B_OK) break; openMessage.AddRef("refs", &ref); } OpenSelectionCommon(&openMessage); } } } break; case kSwitchDirectory: { entry_ref ref; // this comes from dir menu or nav menu, so switch directories if (message->FindRef("refs", &ref) == B_OK) { BEntry entry(&ref, true); if (entry.GetRef(&ref) == B_OK) SetTo(&ref); } break; } case kSwitchToHome: { BPath homePath; entry_ref ref; if (find_directory(B_USER_DIRECTORY, &homePath) != B_OK || get_ref_for_path(homePath.Path(), &ref) != B_OK) { break; } SetTo(&ref); break; } case kAddCurrentDir: { BPath path; if (find_directory(B_USER_SETTINGS_DIRECTORY, &path, true) != B_OK) { break; } path.Append(kGoDirectory); BDirectory goDirectory(path.Path()); if (goDirectory.InitCheck() == B_OK) { BEntry entry(TargetModel()->EntryRef()); entry.GetPath(&path); BSymLink link; goDirectory.CreateSymLink(TargetModel()->Name(), path.Path(), &link); } break; } case kEditFavorites: { BPath path; if (find_directory (B_USER_SETTINGS_DIRECTORY, &path, true) != B_OK) { break; } path.Append(kGoDirectory); BMessenger msgr(kTrackerSignature); if (msgr.IsValid()) { BMessage message(B_REFS_RECEIVED); entry_ref ref; if (get_ref_for_path(path.Path(), &ref) == B_OK) { message.AddRef("refs", &ref); msgr.SendMessage(&message); } } break; } case kCancelButton: PostMessage(B_QUIT_REQUESTED); break; case kResizeToFit: ResizeToFit(); break; case kOpenDir: OpenDirectory(); break; case kOpenParentDir: OpenParent(); break; case kDefaultButton: if (fIsSavePanel) { if (PoseView()->IsFocus() && PoseView()->SelectionList()->CountItems() == 1) { Model* model = (PoseView()->SelectionList()-> FirstItem())->TargetModel(); if (model->ResolveIfLink()->IsDirectory()) { PoseView()->CommitActivePose(); PoseView()->OpenSelection(); break; } } HandleSaveButton(); } else HandleOpenButton(); break; case B_OBSERVER_NOTICE_CHANGE: { int32 observerWhat; if (message->FindInt32("be:observe_change_what", &observerWhat) == B_OK) { switch (observerWhat) { case kDesktopFilePanelRootChanged: { bool desktopIsRoot = true; if (message->FindBool("DesktopFilePanelRoot", &desktopIsRoot) == B_OK) { TrackerSettings(). SetDesktopFilePanelRoot(desktopIsRoot); } SetTo(TargetModel()->EntryRef()); break; } } } break; } default: _inherited::MessageReceived(message); break; } }
bool MozJSImplScope::getBoolean(const char* field) { MozJSEntry entry(this); return ObjectWrapper(_context, _global).getBoolean(field); }
filter_result TFilePanel::MessageDropFilter(BMessage* message, BHandler**, BMessageFilter* filter) { if (message == NULL || !message->WasDropped()) return B_DISPATCH_MESSAGE; ASSERT(filter != NULL); if (filter == NULL) return B_DISPATCH_MESSAGE; TFilePanel* panel = dynamic_cast<TFilePanel*>(filter->Looper()); ASSERT(panel != NULL); if (panel == NULL) return B_DISPATCH_MESSAGE; uint32 type; int32 count; if (message->GetInfo("refs", &type, &count) != B_OK) return B_SKIP_MESSAGE; if (count != 1) return B_SKIP_MESSAGE; entry_ref ref; if (message->FindRef("refs", &ref) != B_OK) return B_SKIP_MESSAGE; BEntry entry(&ref); if (entry.InitCheck() != B_OK) return B_SKIP_MESSAGE; // if the entry is a symlink // resolve it and see if it is a directory // pass it on if it is if (entry.IsSymLink()) { entry_ref resolvedRef; entry.GetRef(&resolvedRef); BEntry resolvedEntry(&resolvedRef, true); if (resolvedEntry.IsDirectory()) { // both entry and ref need to be the correct locations // for the last setto resolvedEntry.GetRef(&ref); entry.SetTo(&ref); } } // if not a directory, set to the parent, and select the child if (!entry.IsDirectory()) { node_ref child; if (entry.GetNodeRef(&child) != B_OK) return B_SKIP_MESSAGE; BPath path(&entry); if (entry.GetParent(&entry) != B_OK) return B_SKIP_MESSAGE; entry.GetRef(&ref); panel->fTaskLoop->RunLater(NewMemberFunctionObjectWithResult (&TFilePanel::SelectChildInParent, panel, const_cast<const entry_ref*>(&ref), const_cast<const node_ref*>(&child)), ref == *panel->TargetModel()->EntryRef() ? 0 : 100000, 200000, 5000000); // if the target directory is already current, we won't // delay the initial selection try // also set the save name to the dragged in entry if (panel->IsSavePanel()) panel->SetSaveText(path.Leaf()); } panel->SetTo(&ref); return B_SKIP_MESSAGE; }
BSONObj MozJSImplScope::getObject(const char* field) { MozJSEntry entry(this); return ObjectWrapper(_context, _global).getObject(field); }
inline void TwoSidedTrsmUVar2 ( UnitOrNonUnit diag, DistMatrix<F>& A, const DistMatrix<F>& U ) { #ifndef RELEASE CallStackEntry entry("internal::TwoSidedTrsmUVar2"); if( A.Height() != A.Width() ) LogicError("A must be square"); if( U.Height() != U.Width() ) LogicError("Triangular matrices must be square"); if( A.Height() != U.Height() ) LogicError("A and U must be the same size"); #endif const Grid& g = A.Grid(); // Matrix views DistMatrix<F> ATL(g), ATR(g), A00(g), A01(g), A02(g), ABL(g), ABR(g), A10(g), A11(g), A12(g), A20(g), A21(g), A22(g); DistMatrix<F> UTL(g), UTR(g), U00(g), U01(g), U02(g), UBL(g), UBR(g), U10(g), U11(g), U12(g), U20(g), U21(g), U22(g); // Temporary distributions DistMatrix<F,MC, STAR> A01_MC_STAR(g); DistMatrix<F,VC, STAR> A01_VC_STAR(g); DistMatrix<F,STAR,STAR> A11_STAR_STAR(g); DistMatrix<F,STAR,VR > A12_STAR_VR(g); DistMatrix<F,MC, STAR> F01_MC_STAR(g); DistMatrix<F,MC, STAR> U01_MC_STAR(g); DistMatrix<F,VR, STAR> U01_VR_STAR(g); DistMatrix<F,STAR,MR > U01Adj_STAR_MR(g); DistMatrix<F,STAR,STAR> U11_STAR_STAR(g); DistMatrix<F,STAR,MR > X11_STAR_MR(g); DistMatrix<F,MR, STAR> X12Adj_MR_STAR(g); DistMatrix<F,MR, MC > X12Adj_MR_MC(g); DistMatrix<F,MR, MC > Y01_MR_MC(g); DistMatrix<F,MR, STAR> Y01_MR_STAR(g); DistMatrix<F> X11(g); DistMatrix<F> Y01(g); Matrix<F> X12Local; PartitionDownDiagonal ( A, ATL, ATR, ABL, ABR, 0 ); LockedPartitionDownDiagonal ( U, UTL, UTR, UBL, UBR, 0 ); while( ATL.Height() < A.Height() ) { RepartitionDownDiagonal ( ATL, /**/ ATR, A00, /**/ A01, A02, /*************/ /******************/ /**/ A10, /**/ A11, A12, ABL, /**/ ABR, A20, /**/ A21, A22 ); LockedRepartitionDownDiagonal ( UTL, /**/ UTR, U00, /**/ U01, U02, /*************/ /******************/ /**/ U10, /**/ U11, U12, UBL, /**/ UBR, U20, /**/ U21, U22 ); A01_MC_STAR.AlignWith( U01 ); Y01.AlignWith( A01 ); Y01_MR_STAR.AlignWith( A00 ); U01_MC_STAR.AlignWith( A00 ); U01_VR_STAR.AlignWith( A00 ); U01Adj_STAR_MR.AlignWith( A00 ); X11_STAR_MR.AlignWith( U01 ); X11.AlignWith( A11 ); X12Adj_MR_STAR.AlignWith( A02 ); X12Adj_MR_MC.AlignWith( A12 ); F01_MC_STAR.AlignWith( A00 ); //--------------------------------------------------------------------// // Y01 := A00 U01 U01_MC_STAR = U01; U01_VR_STAR = U01_MC_STAR; U01Adj_STAR_MR.AdjointFrom( U01_VR_STAR ); Zeros( Y01_MR_STAR, A01.Height(), A01.Width() ); Zeros( F01_MC_STAR, A01.Height(), A01.Width() ); LocalSymmetricAccumulateLU ( ADJOINT, F(1), A00, U01_MC_STAR, U01Adj_STAR_MR, F01_MC_STAR, Y01_MR_STAR ); Y01_MR_MC.SumScatterFrom( Y01_MR_STAR ); Y01 = Y01_MR_MC; Y01.SumScatterUpdate( F(1), F01_MC_STAR ); // X11 := U01' A01 LocalGemm( ADJOINT, NORMAL, F(1), U01_MC_STAR, A01, X11_STAR_MR ); // A01 := A01 - Y01 Axpy( F(-1), Y01, A01 ); A01_MC_STAR = A01; // A11 := A11 - triu(X11 + A01' U01) = A11 - (U01 A01 + A01' U01) LocalGemm( ADJOINT, NORMAL, F(1), A01_MC_STAR, U01, F(1), X11_STAR_MR ); X11.SumScatterFrom( X11_STAR_MR ); MakeTriangular( UPPER, X11 ); Axpy( F(-1), X11, A11 ); // A01 := A01 inv(U11) U11_STAR_STAR = U11; A01_VC_STAR = A01_MC_STAR; LocalTrsm ( RIGHT, UPPER, NORMAL, diag, F(1), U11_STAR_STAR, A01_VC_STAR ); A01 = A01_VC_STAR; // A11 := inv(U11)' A11 inv(U11) A11_STAR_STAR = A11; LocalTwoSidedTrsm( UPPER, diag, A11_STAR_STAR, U11_STAR_STAR ); A11 = A11_STAR_STAR; // A12 := A12 - A02' U01 LocalGemm( ADJOINT, NORMAL, F(1), A02, U01_MC_STAR, X12Adj_MR_STAR ); X12Adj_MR_MC.SumScatterFrom( X12Adj_MR_STAR ); Adjoint( X12Adj_MR_MC.LockedMatrix(), X12Local ); Axpy( F(-1), X12Local, A12.Matrix() ); // A12 := inv(U11)' A12 A12_STAR_VR = A12; LocalTrsm ( LEFT, UPPER, ADJOINT, diag, F(1), U11_STAR_STAR, A12_STAR_VR ); A12 = A12_STAR_VR; //--------------------------------------------------------------------// SlidePartitionDownDiagonal ( ATL, /**/ ATR, A00, A01, /**/ A02, /**/ A10, A11, /**/ A12, /*************/ /******************/ ABL, /**/ ABR, A20, A21, /**/ A22 ); SlideLockedPartitionDownDiagonal ( UTL, /**/ UTR, U00, U01, /**/ U02, /**/ U10, U11, /**/ U12, /*************/ /******************/ UBL, /**/ UBR, U20, U21, /**/ U22 ); } }
void MozJSImplScope::rename(const char* from, const char* to) { MozJSEntry entry(this); ObjectWrapper(_context, _global).rename(from, to); }
status_t FilePlaylistItem::MoveIntoTrash() { if (fNameInTrash.Length() != 0) { // Already in the trash! return B_ERROR; } char trashPath[B_PATH_NAME_LENGTH]; status_t err = find_directory(B_TRASH_DIRECTORY, fRef.device, true /*create it*/, trashPath, B_PATH_NAME_LENGTH); if (err != B_OK) { fprintf(stderr, "failed to find Trash: %s\n", strerror(err)); return err; } BEntry entry(&fRef); err = entry.InitCheck(); if (err != B_OK) { fprintf(stderr, "failed to init BEntry for %s: %s\n", fRef.name, strerror(err)); return err; } BDirectory trashDir(trashPath); if (err != B_OK) { fprintf(stderr, "failed to init BDirectory for %s: %s\n", trashPath, strerror(err)); return err; } // Find a unique name for the entry in the trash fNameInTrash = fRef.name; int32 uniqueNameIndex = 1; while (true) { BEntry test(&trashDir, fNameInTrash.String()); if (!test.Exists()) break; fNameInTrash = fRef.name; fNameInTrash << ' ' << uniqueNameIndex; uniqueNameIndex++; } // Remember the original path BPath originalPath; entry.GetPath(&originalPath); // Finally, move the entry into the trash err = entry.MoveTo(&trashDir, fNameInTrash.String()); if (err != B_OK) { fprintf(stderr, "failed to move entry into trash %s: %s\n", trashPath, strerror(err)); return err; } // Allow Tracker to restore this entry BNode node(&entry); BString originalPathString(originalPath.Path()); node.WriteAttrString("_trk/original_path", &originalPathString); return err; }
int MozJSImplScope::invoke(ScriptingFunction func, const BSONObj* argsObject, const BSONObj* recv, int timeoutMs, bool ignoreReturn, bool readOnlyArgs, bool readOnlyRecv) { MozJSEntry entry(this); auto funcValue = _funcs[func - 1]; JS::RootedValue result(_context); const int nargs = argsObject ? argsObject->nFields() : 0; JS::AutoValueVector args(_context); if (nargs) { BSONObjIterator it(*argsObject); for (int i = 0; i < nargs; i++) { BSONElement next = it.next(); JS::RootedValue value(_context); ValueReader(_context, &value).fromBSONElement(next, *argsObject, readOnlyArgs); args.append(value); } } JS::RootedValue smrecv(_context); if (recv) ValueReader(_context, &smrecv).fromBSON(*recv, nullptr, readOnlyRecv); else smrecv.setObjectOrNull(_global); if (timeoutMs) _engine->getDeadlineMonitor().startDeadline(this, timeoutMs); JS::RootedValue out(_context); JS::RootedObject obj(_context, smrecv.toObjectOrNull()); bool success = JS::Call(_context, obj, funcValue, args, &out); if (timeoutMs) _engine->getDeadlineMonitor().stopDeadline(this); _checkErrorState(success); if (!ignoreReturn) { // must validate the handle because TerminateExecution may have // been thrown after the above checks if (out.isObject() && _nativeFunctionProto.instanceOf(out)) { warning() << "storing native function as return value"; _lastRetIsNativeCode = true; } else { _lastRetIsNativeCode = false; } ObjectWrapper(_context, _global).setValue(kInvokeResult, out); } return 0; }
void SourceFileC::RemoveObjects(BuildInfo &info) { BEntry entry(GetObjectPath(info).GetFullPath()); entry.Remove(); }
const PString &PIni::entry(const pchar *name) const { return entry(PString(name)); }
void bdecode_recursive(InIt& in, InIt end, entry& ret, bool& err, int depth) { if (depth >= 100) { err = true; return; } if (in == end) { err = true; #ifdef TORRENT_DEBUG ret.m_type_queried = false; #endif return; } switch (*in) { // ---------------------------------------------- // integer case 'i': { ++in; // 'i' std::string val = read_until(in, end, 'e', err); if (err) return; TORRENT_ASSERT(*in == 'e'); ++in; // 'e' ret = entry(entry::int_t); char* end_pointer; ret.integer() = strtoll(val.c_str(), &end_pointer, 10); #ifdef TORRENT_DEBUG ret.m_type_queried = false; #endif if (end_pointer == val.c_str()) { err = true; return; } } break; // ---------------------------------------------- // list case 'l': { ret = entry(entry::list_t); ++in; // 'l' while (*in != 'e') { ret.list().push_back(entry()); entry& e = ret.list().back(); bdecode_recursive(in, end, e, err, depth + 1); if (err) { #ifdef TORRENT_DEBUG ret.m_type_queried = false; #endif return; } if (in == end) { err = true; #ifdef TORRENT_DEBUG ret.m_type_queried = false; #endif return; } } #ifdef TORRENT_DEBUG ret.m_type_queried = false; #endif TORRENT_ASSERT(*in == 'e'); ++in; // 'e' } break; // ---------------------------------------------- // dictionary case 'd': { ret = entry(entry::dictionary_t); ++in; // 'd' while (*in != 'e') { entry key; bdecode_recursive(in, end, key, err, depth + 1); if (err || key.type() != entry::string_t) { #ifdef TORRENT_DEBUG ret.m_type_queried = false; #endif return; } entry& e = ret[key.string()]; bdecode_recursive(in, end, e, err, depth + 1); if (err) { #ifdef TORRENT_DEBUG ret.m_type_queried = false; #endif return; } if (in == end) { err = true; #ifdef TORRENT_DEBUG ret.m_type_queried = false; #endif return; } } #ifdef TORRENT_DEBUG ret.m_type_queried = false; #endif TORRENT_ASSERT(*in == 'e'); ++in; // 'e' } break; // ---------------------------------------------- // string default: if (is_digit((unsigned char)*in)) { std::string len_s = read_until(in, end, ':', err); if (err) { #ifdef TORRENT_DEBUG ret.m_type_queried = false; #endif return; } TORRENT_ASSERT(*in == ':'); ++in; // ':' int len = atoi(len_s.c_str()); ret = entry(entry::string_t); read_string(in, end, len, ret.string(), err); if (err) { #ifdef TORRENT_DEBUG ret.m_type_queried = false; #endif return; } } else { err = true; #ifdef TORRENT_DEBUG ret.m_type_queried = false; #endif return; } #ifdef TORRENT_DEBUG ret.m_type_queried = false; #endif } }
ssize_t StringPool::add(const String16& value, bool mergeDuplicates, const String8* configTypeName, const ResTable_config* config) { ssize_t vidx = mValues.indexOfKey(value); ssize_t pos = vidx >= 0 ? mValues.valueAt(vidx) : -1; ssize_t eidx = pos >= 0 ? mEntryArray.itemAt(pos) : -1; if (eidx < 0) { eidx = mEntries.add(entry(value)); if (eidx < 0) { fprintf(stderr, "Failure adding string %s\n", String8(value).string()); return eidx; } } if (configTypeName != NULL) { entry& ent = mEntries.editItemAt(eidx); NOISY(printf("*** adding config type name %s, was %s\n", configTypeName->string(), ent.configTypeName.string())); if (ent.configTypeName.size() <= 0) { ent.configTypeName = *configTypeName; } else if (ent.configTypeName != *configTypeName) { ent.configTypeName = " "; } } if (config != NULL) { // Add this to the set of configs associated with the string. entry& ent = mEntries.editItemAt(eidx); size_t addPos; for (addPos=0; addPos<ent.configs.size(); addPos++) { int cmp = ent.configs.itemAt(addPos).compareLogical(*config); if (cmp >= 0) { if (cmp > 0) { NOISY(printf("*** inserting config: %s\n", config->toString().string())); ent.configs.insertAt(*config, addPos); } break; } } if (addPos >= ent.configs.size()) { NOISY(printf("*** adding config: %s\n", config->toString().string())); ent.configs.add(*config); } } const bool first = vidx < 0; const bool styled = (pos >= 0 && (size_t)pos < mEntryStyleArray.size()) ? mEntryStyleArray[pos].spans.size() : 0; if (first || styled || !mergeDuplicates) { pos = mEntryArray.add(eidx); if (first) { vidx = mValues.add(value, pos); } entry& ent = mEntries.editItemAt(eidx); ent.indices.add(pos); } NOISY(printf("Adding string %s to pool: pos=%d eidx=%d vidx=%d\n", String8(value).string(), pos, eidx, vidx)); return pos; }
void WebMBufferedParser::Append(const unsigned char* aBuffer, uint32_t aLength, nsTArray<WebMTimeDataOffset>& aMapping, ReentrantMonitor& aReentrantMonitor) { static const uint32_t SEGMENT_ID = 0x18538067; static const uint32_t SEGINFO_ID = 0x1549a966; static const uint32_t TRACKS_ID = 0x1654AE6B; static const uint32_t CLUSTER_ID = 0x1f43b675; static const uint32_t TIMECODESCALE_ID = 0x2ad7b1; static const unsigned char TIMECODE_ID = 0xe7; static const unsigned char BLOCK_ID = 0xa1; static const unsigned char SIMPLEBLOCK_ID = 0xa3; static const uint32_t BLOCK_TIMECODE_LENGTH = 2; static const unsigned char CLUSTER_SYNC_ID[] = { 0x1f, 0x43, 0xb6, 0x75 }; const unsigned char* p = aBuffer; // Parse each byte in aBuffer one-by-one, producing timecodes and updating // aMapping as we go. Parser pauses at end of stream (which may be at any // point within the parse) and resumes parsing the next time Append is // called with new data. while (p < aBuffer + aLength) { switch (mState) { case READ_ELEMENT_ID: mVIntRaw = true; mState = READ_VINT; mNextState = READ_ELEMENT_SIZE; break; case READ_ELEMENT_SIZE: mVIntRaw = false; mElement.mID = mVInt; mState = READ_VINT; mNextState = PARSE_ELEMENT; break; case FIND_CLUSTER_SYNC: if (*p++ == CLUSTER_SYNC_ID[mClusterSyncPos]) { mClusterSyncPos += 1; } else { mClusterSyncPos = 0; } if (mClusterSyncPos == sizeof(CLUSTER_SYNC_ID)) { mVInt.mValue = CLUSTER_ID; mVInt.mLength = sizeof(CLUSTER_SYNC_ID); mState = READ_ELEMENT_SIZE; } break; case PARSE_ELEMENT: mElement.mSize = mVInt; switch (mElement.mID.mValue) { case SEGMENT_ID: mState = READ_ELEMENT_ID; break; case SEGINFO_ID: mGotTimecodeScale = true; mState = READ_ELEMENT_ID; break; case TIMECODE_ID: mVInt = VInt(); mVIntLeft = mElement.mSize.mValue; mState = READ_VINT_REST; mNextState = READ_CLUSTER_TIMECODE; break; case TIMECODESCALE_ID: mVInt = VInt(); mVIntLeft = mElement.mSize.mValue; mState = READ_VINT_REST; mNextState = READ_TIMECODESCALE; break; case CLUSTER_ID: mClusterOffset = mCurrentOffset + (p - aBuffer) - (mElement.mID.mLength + mElement.mSize.mLength); mState = READ_ELEMENT_ID; break; case SIMPLEBLOCK_ID: /* FALLTHROUGH */ case BLOCK_ID: mBlockSize = mElement.mSize.mValue; mBlockTimecode = 0; mBlockTimecodeLength = BLOCK_TIMECODE_LENGTH; mBlockOffset = mCurrentOffset + (p - aBuffer) - (mElement.mID.mLength + mElement.mSize.mLength); mState = READ_VINT; mNextState = READ_BLOCK_TIMECODE; break; case TRACKS_ID: mSkipBytes = mElement.mSize.mValue; mState = CHECK_INIT_FOUND; break; default: mSkipBytes = mElement.mSize.mValue; mState = SKIP_DATA; mNextState = READ_ELEMENT_ID; break; } break; case READ_VINT: { unsigned char c = *p++; uint32_t mask; mVInt.mLength = VIntLength(c, &mask); mVIntLeft = mVInt.mLength - 1; mVInt.mValue = mVIntRaw ? c : c & ~mask; mState = READ_VINT_REST; break; } case READ_VINT_REST: if (mVIntLeft) { mVInt.mValue <<= 8; mVInt.mValue |= *p++; mVIntLeft -= 1; } else { mState = mNextState; } break; case READ_TIMECODESCALE: MOZ_ASSERT(mGotTimecodeScale); mTimecodeScale = mVInt.mValue; mState = READ_ELEMENT_ID; break; case READ_CLUSTER_TIMECODE: mClusterTimecode = mVInt.mValue; mState = READ_ELEMENT_ID; break; case READ_BLOCK_TIMECODE: if (mBlockTimecodeLength) { mBlockTimecode <<= 8; mBlockTimecode |= *p++; mBlockTimecodeLength -= 1; } else { // It's possible we've parsed this data before, so avoid inserting // duplicate WebMTimeDataOffset entries. { ReentrantMonitorAutoEnter mon(aReentrantMonitor); int64_t endOffset = mBlockOffset + mBlockSize + mElement.mID.mLength + mElement.mSize.mLength; uint32_t idx = aMapping.IndexOfFirstElementGt(endOffset); if (idx == 0 || aMapping[idx - 1] != endOffset) { // Don't insert invalid negative timecodes. if (mBlockTimecode >= 0 || mClusterTimecode >= uint16_t(abs(mBlockTimecode))) { MOZ_ASSERT(mGotTimecodeScale); uint64_t absTimecode = mClusterTimecode + mBlockTimecode; absTimecode *= mTimecodeScale; WebMTimeDataOffset entry(endOffset, absTimecode, mClusterOffset); aMapping.InsertElementAt(idx, entry); } } } // Skip rest of block header and the block's payload. mBlockSize -= mVInt.mLength; mBlockSize -= BLOCK_TIMECODE_LENGTH; mSkipBytes = uint32_t(mBlockSize); mState = SKIP_DATA; mNextState = READ_ELEMENT_ID; } break; case SKIP_DATA: if (mSkipBytes) { uint32_t left = aLength - (p - aBuffer); left = std::min(left, mSkipBytes); p += left; mSkipBytes -= left; } else { mState = mNextState; } break; case CHECK_INIT_FOUND: if (mSkipBytes) { uint32_t left = aLength - (p - aBuffer); left = std::min(left, mSkipBytes); p += left; mSkipBytes -= left; } if (!mSkipBytes) { if (mInitEndOffset < 0) { mInitEndOffset = mCurrentOffset + (p - aBuffer); } mState = READ_ELEMENT_ID; } break; } } NS_ASSERTION(p == aBuffer + aLength, "Must have parsed to end of data."); mCurrentOffset += aLength; }
void testApp::loadURL_alphabet(ofHttpResponse &response) { newAlphabet.clear(); int numberOfLettersAdded=0; vector<AlphabetEntry> allLetters; for (int i=0; i<allEntries.size(); i++) { ofStringReplace(allEntries[i], "letter\":\"", ""); vector<string> cutEntries =ofSplitString(allEntries[i], "\",\""); //delete the first parts in all of them ofStringReplace(cutEntries[0], "\"ID\":\"",""); ofStringReplace(cutEntries[0], "\"", ""); ofStringReplace(cutEntries[1], "\"", ""); string letter=cutEntries[1]; if (i>1) { if (allLetters[numberOfLettersAdded-1]._letter!=letter) { AlphabetEntry entry(cutEntries[0], cutEntries[1], numberOfLettersAdded); allLetters.push_back(entry); numberOfLettersAdded++; } } else { AlphabetEntry entry(cutEntries[0], cutEntries[1], i); allLetters.push_back(entry); numberOfLettersAdded++; } } for (int j=0; j<42; j++) { //go through all letters we have for (int i=0; i<allLetters.size(); i++) { if (allLetters[i]._letter==alphabet[j]) { AlphabetEntry entry(ofToString(allLetters[i]._id), allLetters[i]._letter, j); newAlphabet.push_back(entry); break; } else if (i==allLetters.size()-1) { AlphabetEntry entry("0000", alphabet[j], j); newAlphabet.push_back(entry); break; } } } //if first time load > put the letters directly into the alphabet if (allAlphabet.size()<1) { for (int j=0; j<newAlphabet.size(); j++) { allAlphabet.push_back(newAlphabet[j]); if (allAlphabet[j]._id!=0) { allAlphabet[j].loadImage(); } else { //load letter from image directory allAlphabet[j].loadImageDirectory(); } } } else { //if there is already something in the alphabet for (int j=0; j<42; j++) { if (allAlphabet[j]._id!=newAlphabet[j]._id) { allAlphabet[j]=newAlphabet[j]; allAlphabet.push_back(newAlphabet[j]); if (allAlphabet[j]._id!=0) { allAlphabet[j].loadImage(); } else { //load letter from image directory allAlphabet[j].loadImageDirectory(); } } else { allAlphabet[j].reset(); } } } if (response.status==200 && response.request.name=="async_req") { currImgNo1=0; currImgNo2=1; currImgNo3=2; currImgNo4=3; currImgNo5=4; } }