text
stringlengths
2
1.04M
meta
dict
namespace Microsoft.Graph { using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Runtime.Serialization; /// <summary> /// The type WorkbookFunctionsLargeRequestBody. /// </summary> [JsonObject(MemberSerialization = MemberSerialization.OptIn)] public partial class WorkbookFunctionsLargeRequestBody { /// <summary> /// Gets or sets Array. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "array", Required = Newtonsoft.Json.Required.Default)] public Newtonsoft.Json.Linq.JToken Array { get; set; } /// <summary> /// Gets or sets K. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "k", Required = Newtonsoft.Json.Required.Default)] public Newtonsoft.Json.Linq.JToken K { get; set; } } }
{ "content_hash": "9156297e1be374d3b5fdeebe5eeaa983", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 137, "avg_line_length": 33.10344827586207, "alnum_prop": 0.65, "repo_name": "ginach/msgraph-sdk-dotnet", "id": "73aeb01b1391977725e4e14e3a8701cde65a2f83", "size": "1431", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Microsoft.Graph/Models/Generated/WorkbookFunctionsLargeRequestBody.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "12839763" }, { "name": "Smalltalk", "bytes": "12638" } ], "symlink_target": "" }
using namespace json_spirit; using namespace std; void ScriptPubKeyToJSON(const CScript& scriptPubKey, Object& out); double GetDifficulty(const CBlockIndex* blockindex) { // Floating point number that is a multiple of the minimum difficulty, // minimum difficulty = 1.0. if (blockindex == NULL) { if (pindexBest == NULL) return 1.0; else blockindex = pindexBest; } int nShift = (blockindex->nBits >> 24) & 0xff; double dDiff = (double)0x0000ffff / (double)(blockindex->nBits & 0x00ffffff); while (nShift < 29) { dDiff *= 256.0; nShift++; } while (nShift > 29) { dDiff /= 256.0; nShift--; } return dDiff; } Object blockToJSON(const CBlock& block, const CBlockIndex* blockindex) { Object result; result.push_back(Pair("hash", block.GetHash().GetHex())); CMerkleTx txGen(block.vtx[0]); txGen.SetMerkleBranch(&block); result.push_back(Pair("confirmations", (int)txGen.GetDepthInMainChain())); result.push_back(Pair("size", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION))); result.push_back(Pair("height", blockindex->nHeight)); result.push_back(Pair("version", block.nVersion)); result.push_back(Pair("merkleroot", block.hashMerkleRoot.GetHex())); Array txs; BOOST_FOREACH(const CTransaction&tx, block.vtx) txs.push_back(tx.GetHash().GetHex()); result.push_back(Pair("tx", txs)); result.push_back(Pair("time", (boost::int64_t)block.GetBlockTime())); result.push_back(Pair("nonce", (boost::uint64_t)block.nNonce)); result.push_back(Pair("bits", HexBits(block.nBits))); result.push_back(Pair("difficulty", GetDifficulty(blockindex))); if (blockindex->pprev) result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex())); if (blockindex->pnext) result.push_back(Pair("nextblockhash", blockindex->pnext->GetBlockHash().GetHex())); return result; } Value getblockcount(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getblockcount\n" "Returns the number of blocks in the longest block chain."); return nBestHeight; } Value getbestblockhash(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getbestblockhash\n" "Returns the hash of the best (tip) block in the longest block chain."); return hashBestChain.GetHex(); } Value getdifficulty(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getdifficulty\n" "Returns the proof-of-work difficulty as a multiple of the minimum difficulty."); return GetDifficulty(); } Value settxfee(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 1) throw runtime_error( "settxfee <amount PECN/KB>\n" "<amount> is a real and is rounded to the nearest 0.00000001 PECN per KB"); // Amount int64 nAmount = 0; if (params[0].get_real() != 0.0) nAmount = AmountFromValue(params[0]); // rejects 0.0 amounts nTransactionFee = nAmount; return true; } Value getrawmempool(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getrawmempool\n" "Returns all transaction ids in memory pool."); vector<uint256> vtxid; mempool.queryHashes(vtxid); Array a; BOOST_FOREACH(const uint256& hash, vtxid) a.push_back(hash.ToString()); return a; } Value getblockhash(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "getblockhash <index>\n" "Returns hash of block in best-block-chain at <index>."); int nHeight = params[0].get_int(); if (nHeight < 0 || nHeight > nBestHeight) throw runtime_error("Block number out of range."); CBlockIndex* pblockindex = FindBlockByHeight(nHeight); return pblockindex->phashBlock->GetHex(); } Value getblock(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "getblock <hash> [verbose=true]\n" "If verbose is false, returns a string that is serialized, hex-encoded data for block <hash>.\n" "If verbose is true, returns an Object with information about block <hash>." ); std::string strHash = params[0].get_str(); uint256 hash(strHash); bool fVerbose = true; if (params.size() > 1) fVerbose = params[1].get_bool(); if (mapBlockIndex.count(hash) == 0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); CBlock block; CBlockIndex* pblockindex = mapBlockIndex[hash]; block.ReadFromDisk(pblockindex); if (!fVerbose) { CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION); ssBlock << block; std::string strHex = HexStr(ssBlock.begin(), ssBlock.end()); return strHex; } return blockToJSON(block, pblockindex); } Value gettxoutsetinfo(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "gettxoutsetinfo\n" "Returns statistics about the unspent transaction output set."); Object ret; CCoinsStats stats; if (pcoinsTip->GetStats(stats)) { ret.push_back(Pair("height", (boost::int64_t)stats.nHeight)); ret.push_back(Pair("bestblock", stats.hashBlock.GetHex())); ret.push_back(Pair("transactions", (boost::int64_t)stats.nTransactions)); ret.push_back(Pair("txouts", (boost::int64_t)stats.nTransactionOutputs)); ret.push_back(Pair("bytes_serialized", (boost::int64_t)stats.nSerializedSize)); ret.push_back(Pair("hash_serialized", stats.hashSerialized.GetHex())); ret.push_back(Pair("total_amount", ValueFromAmount(stats.nTotalAmount))); } return ret; } Value gettxout(const Array& params, bool fHelp) { if (fHelp || params.size() < 2 || params.size() > 3) throw runtime_error( "gettxout <txid> <n> [includemempool=true]\n" "Returns details about an unspent transaction output."); Object ret; std::string strHash = params[0].get_str(); uint256 hash(strHash); int n = params[1].get_int(); bool fMempool = true; if (params.size() > 2) fMempool = params[2].get_bool(); CCoins coins; if (fMempool) { LOCK(mempool.cs); CCoinsViewMemPool view(*pcoinsTip, mempool); if (!view.GetCoins(hash, coins)) return Value::null; mempool.pruneSpent(hash, coins); // TODO: this should be done by the CCoinsViewMemPool } else { if (!pcoinsTip->GetCoins(hash, coins)) return Value::null; } if (n<0 || (unsigned int)n>=coins.vout.size() || coins.vout[n].IsNull()) return Value::null; ret.push_back(Pair("bestblock", pcoinsTip->GetBestBlock()->GetBlockHash().GetHex())); if ((unsigned int)coins.nHeight == MEMPOOL_HEIGHT) ret.push_back(Pair("confirmations", 0)); else ret.push_back(Pair("confirmations", pcoinsTip->GetBestBlock()->nHeight - coins.nHeight + 1)); ret.push_back(Pair("value", ValueFromAmount(coins.vout[n].nValue))); Object o; ScriptPubKeyToJSON(coins.vout[n].scriptPubKey, o); ret.push_back(Pair("scriptPubKey", o)); ret.push_back(Pair("version", coins.nVersion)); ret.push_back(Pair("coinbase", coins.fCoinBase)); return ret; } Value verifychain(const Array& params, bool fHelp) { if (fHelp || params.size() > 2) throw runtime_error( "verifychain [check level] [num blocks]\n" "Verifies blockchain database."); int nCheckLevel = GetArg("-checklevel", 3); int nCheckDepth = GetArg("-checkblocks", 288); if (params.size() > 0) nCheckLevel = params[0].get_int(); if (params.size() > 1) nCheckDepth = params[1].get_int(); return VerifyDB(nCheckLevel, nCheckDepth); }
{ "content_hash": "6ae20739df9ab25639af9ffd72dc98b8", "timestamp": "", "source": "github", "line_count": 262, "max_line_length": 108, "avg_line_length": 31.3206106870229, "alnum_prop": 0.6273458445040214, "repo_name": "youngstorch/pesacoin", "id": "889703bf2673568776ebbc61c125139771b382d4", "size": "8482", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/rpcblockchain.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "32394" }, { "name": "C++", "bytes": "2613220" }, { "name": "CSS", "bytes": "1127" }, { "name": "HTML", "bytes": "50615" }, { "name": "Makefile", "bytes": "13384" }, { "name": "NSIS", "bytes": "6106" }, { "name": "Objective-C", "bytes": "1052" }, { "name": "Objective-C++", "bytes": "5864" }, { "name": "Python", "bytes": "69714" }, { "name": "QMake", "bytes": "14714" }, { "name": "Roff", "bytes": "18284" }, { "name": "Shell", "bytes": "16339" } ], "symlink_target": "" }
# Changelog Shoelace follows [Semantic Versioning](https://semver.org/). Breaking changes in components with the <sl-badge variant="primary" pill>Stable</sl-badge> badge will not be accepted until the next major version. As such, all contributions must consider the project's roadmap and take this into consideration. Features that are deemed no longer necessary will be deprecated but not removed. Components with the <sl-badge variant="warning" pill>Experimental</sl-badge> badge should not be used in production. They are made available as release candidates for development and testing purposes. As such, changes to experimental components will not be subject to semantic versioning. _During the beta period, these restrictions may be relaxed in the event of a mission-critical bug._ 🐛 ## Next - Added `button` part to `<sl-radio-button>` - Added custom validity examples and tests to `<sl-checkbox>`, `<sl-radio>`, and `<sl-radio-button>` - Fixed a bug that prevented `setCustomValidity()` from working with `<sl-radio-button>` - Fixed a bug where the right border of a checked `<sl-radio-button>` was the wrong color - Fixed a bug that prevented a number of properties, methods, etc. from being documented in `<sl-radio>` and `<sl-radio-button>` - Updated `<sl-tab-group>` and `<sl-menu>` to cycle through tabs and menu items instead of stopping at the first/last when using the keyboard - Removed path aliasing (again) because it doesn't work with Web Test Runner's esbuild plugin ## 2.0.0-beta.72 - 🚨 BREAKING: refactored parts in `<sl-input>`, `<sl-range>`, `<sl-select>`, and `<sl-textarea>` to allow you to customize the label and help text position - Added `form-control-input` part - Renamed `label` to `form-control-label` - Renamed `help-text` to `form-control-help-text` - 🚨 BREAKING: removed status from the `sl-error` event payload in `<sl-icon>` - Added the experimental `<sl-radio-button>` component - Added `button-group` and `button-group__base` parts to `<sl-radio-group>` - Added the `label` attribute and slot to `<sl-color-picker>` to improve accessibility with screen readers - Fixed a bug that prevented form submission from working as expected in some cases - Fixed a bug that prevented `<sl-split-panel>` from toggling `vertical` properly [#703](https://github.com/shoelace-style/shoelace/issues/703) - Fixed a bug that prevented `<sl-color-picker>` from rendering a color initially [#704](https://github.com/shoelace-style/shoelace/issues/704) - Fixed a bug that caused focus trapping to fail when used inside a shadow root [#709](https://github.com/shoelace-style/shoelace/issues/709) - Improved accessibility throughout the docs - Improved accessibility of `<sl-dropdown>` so the trigger's expanded state is announced correctly - Improved accessibility of `<sl-format-date>` but rendering a `<time>` element instead of plain text - Improved accessibility of `<sl-select>` so disabled controls announce correct - Improved accessibility in `<sl-tag>` so remove buttons have labels - Refactored `<sl-radio>` to move selection logic into `<sl-radio-group>` - Updated slot detection logic so it ignores visually hidden elements - Upgraded the status of `<sl-visually-hidden>` from experimental to stable ## 2.0.0-beta.71 - 🚨 BREAKING: refactored exported parts to ensure composed components and their parts can be targeted via CSS - Refactored the `eye-dropper-button` part and added `eye-dropper-button__base`, `eye-dropper-button__prefix`, `eye-dropper-button__label`, `eye-dropper-button__suffix`, and `eye-dropper-button__caret` parts to `<sl-color-picker>` - Refactored the `format-button` part and added `format-button__base`, `format-button__prefix`, `format-button__label`, `format-button__suffix`, and `format-button__caret` parts to `<sl-color-picker>` - Moved the `close-button` part in `<sl-alert>` to the internal `<sl-icon-button>` and removed the `<span>` that wrapped it - Moved the `close-button` part in `<sl-dialog>` and `<sl-drawer>` to point to the host element and added the `close-button__base` part - Renamed parts in `<sl-select>` from `tag-base` to `tag__base`, `tag-content` to `tag__content`, and `tag-remove-button` to `tag__remove-button` - Moved the `close-button` part in `<sl-tab>` to the internal `<sl-icon-button>` and added the `close-button__base` part - Moved the `scroll-button` part in `<sl-tab-group>` to the internal `<sl-icon-button>` and added the `scroll-button__base`, `scroll-button--start`, and `scroll-button--end` parts - Moved the `remove-button` part in `<sl-tag>` to the internal `<sl-icon-button>` and added the `remove-button__base` part - 🚨 BREAKING: removed `checked-icon` part from `<sl-menu-item>` in preparation for parts refactor - 🚨 BREAKING: changed the `typeToSelect()` method's argument from `String` to `KeyboardEvent` in `<sl-menu>` to support more advanced key combinations - Added `form`, `formaction`, `formmethod`, `formnovalidate`, and `formtarget` attributes to `<sl-button>` [#699](https://github.com/shoelace-style/shoelace/issues/699) - Added Prettier and ESLint to markdown files - Added background color and border to `<sl-menu>` - Added more tests for `<sl-input>`, `<sl-select>`, and `<sl-textarea>` - Fixed a bug that prevented forms from submitting when pressing <kbd>Enter</kbd> inside of an `<sl-input>` [#700](https://github.com/shoelace-style/shoelace/issues/700) - Fixed a bug in `<sl-input>` that prevented the `valueAsDate` and `valueAsNumber` properties from working when set before the component was initialized - Fixed a bug in `<sl-dropdown>` where pressing <kbd>Home</kbd> or <kbd>End</kbd> wouldn't select the first or last menu items, respectively - Improved `autofocus` behavior in Safari for `<sl-dialog>` and `<sl-drawer>` [#693](https://github.com/shoelace-style/shoelace/issues/693) - Improved type to select logic in `<sl-menu>` so it supports <kbd>Backspace</kbd> and gives users more time before resetting - Improved checkmark size and positioning in `<sl-menu-item>` - Improved accessibility in form controls that have help text so they're announced correctly in various screen readers - Removed feature detection for `focus({ preventScroll })` since it no longer works in Safari - Removed the `--sl-tooltip-arrow-start-end-offset` design token - Removed the `pattern` attribute from `<sl-textarea>` as it was documented incorrectly and never supported - Replaced Popper positioning dependency with Floating UI in `<sl-dropdown>` and `<sl-tooltip>` ## 2.0.0-beta.70 - Added `tag-base`, `tag-content`, and `tag-remove-button` parts to `<sl-select>` [#682](https://github.com/shoelace-style/shoelace/discussions/682) - Added support for focusing elements with `autofocus` when `<sl-dialog>` and `<sl-drawer>` open [#688](https://github.com/shoelace-style/shoelace/issues/688) - Added the `placement` attribute to `<sl-select>` [#687](https://github.com/shoelace-style/shoelace/pull/687) - Added Danish translation [#690](https://github.com/shoelace-style/shoelace/pull/690) - Fixed a bug that allowed `<sl-dropdown>` to go into an incorrect state when activating the trigger while disabled [#684](https://github.com/shoelace-style/shoelace/pull/684) - Fixed a bug where Safari would sometimes not focus after preventing `sl-initial-focus` [#688](https://github.com/shoelace-style/shoelace/issues/688) - Fixed a bug where the active tab indicator in `<sl-tab-group>` would be misaligned when using disabled tabs [#695](https://github.com/shoelace-style/shoelace/pull/695) - Improved the size of the remove button in `<sl-tag>` - Removed Google Analytics from the docs ## 2.0.0-beta.69 - Added `web-types.json` to improve the dev experience for WebStorm/PHPStorm users [#328](https://github.com/shoelace-style/shoelace/issues/328) - Fixed a bug that caused an error when pressing up/down in `<sl-select>` - Fixed a bug that caused `<sl-details>` to not show when double clicking the summary while open [#662](https://github.com/shoelace-style/shoelace/issues/662) - Fixed a bug that prevented the first/last menu item from receiving focus when pressing up/down in `<sl-dropdown>` - Fixed a bug that caused the active tab indicator in `<sl-tab-group>` to render incorrectly when used inside an element that animates [#671](https://github.com/shoelace-style/shoelace/pull/671) - Fixed a bug that allowed values in `<sl-range>` to be invalid according to its `min|max|step` [#674](https://github.com/shoelace-style/shoelace/issues/674) - Updated Lit to 2.1.4 - Updated all other dependencies to latest versions ## 2.0.0-beta.68 - Fixed path aliases in generated files so they're relative again [#669](https://github.com/shoelace-style/shoelace/pull/669) ## 2.0.0-beta.67 - Fixed a TypeScript config regression introduced in [#647](https://github.com/shoelace-style/shoelace/pull/647) that removed the `rootDir`, breaking the expected build output ## 2.0.0-beta.66 - Attempted to fix a bug that prevented types from being generated in the build ## 2.0.0-beta.65 - 🚨 BREAKING: the `unit` property of `<sl-format-bytes>` has changed to `byte | bit` instead of `bytes | bits` - Added `display-label` part to `<sl-select>` [#650](https://github.com/shoelace-style/shoelace/issues/650) - Added `--spacing` CSS custom property to `<sl-divider>` [#664](https://github.com/shoelace-style/shoelace/pull/664) - Added `event.detail.source` to the `sl-request-close` event in `<sl-dialog>` and `<sl-drawer>` - Fixed a bug that caused `<sl-progress-ring>` to render the wrong size when `--track-width` was increased [#656](https://github.com/shoelace-style/shoelace/issues/656) - Fixed a bug that allowed `<sl-details>` to open and close when disabled using a screen reader [#658](https://github.com/shoelace-style/shoelace/issues/658) - Fixed a bug in the FormData event polyfill that threw an error in some environments [#666](https://github.com/shoelace-style/shoelace/issues/666) - Implemented stricter linting to improve consistency and reduce errors, which resulted in many small refactors throughout the codebase [#647](https://github.com/shoelace-style/shoelace/pull/647) - Improved accessibility of `<sl-dialog>` and `<sl-drawer>` by making the title an `<h2>` and adding a label to the close button - Improved search results in the documentation - Refactored `<sl-format-byte>` to use `Intl.NumberFormat` so it supports localization - Refactored themes so utility styles are no longer injected as `<style>` elements to support stricter CSP rules [#571](https://github.com/shoelace-style/shoelace/issues/571) - Restored the nicer animation on `<sl-spinner>` and verified it works in Safari - Updated Feather icon example to use Lucide [#657](https://github.com/shoelace-style/shoelace/issues/657) - Updated minimum Node version to 14.17 - Updated Lit to 2.1.2 - Updated to Bootstrap Icons to 1.8.1 - Updated all other dependencies to latest versions ## 2.0.0-beta.64 - 🚨 BREAKING: removed `<sl-form>` because all form components submit with `<form>` now ([learn more](/getting-started/form-controls)) - 🚨 BREAKING: changed `submit` attribute to `type="submit"` on `<sl-button>` - 🚨 BREAKING: changed the `alt` attribute to `label` in `<sl-avatar>` for consistency with other components - Added `role="status"` to `<sl-spinner>` - Added `valueAsDate` and `valueAsNumber` properties to `<sl-input>` [#570](https://github.com/shoelace-style/shoelace/issues/570) - Added `start`, `end`, and `panel` parts to `<sl-split-panel>` [#639](https://github.com/shoelace-style/shoelace/issues/639) - Fixed broken spinner animation in Safari [#633](https://github.com/shoelace-style/shoelace/issues/633) - Fixed an a11y bug in `<sl-tooltip>` where `aria-describedby` referenced an id in the shadow root - Fixed a bug in `<sl-radio>` where tabbing didn't work properly in Firefox [#596](https://github.com/shoelace-style/shoelace/issues/596) - Fixed a bug in `<sl-input>` where clicking the left/right edge of the control wouldn't focus it - Fixed a bug in `<sl-input>` where autofill had strange styles [#644](https://github.com/shoelace-style/shoelace/pull/644) - Improved `<sl-spinner>` track color when used on various backgrounds - Improved a11y in `<sl-radio>` so VoiceOver announces radios properly in a radio group - Improved the API for the experimental `<sl-split-panel>` component by making `position` accept a percentage and adding the `position-in-pixels` attribute - Refactored `<sl-breadcrumb-item>`, `<sl-button>`, `<sl-card>`, `<sl-dialog>`, `<sl-drawer>`, `<sl-input>`, `<sl-range>`, `<sl-select>`, and `<sl-textarea>` to use a Reactive Controller for slot detection - Refactored internal id usage in `<sl-details>`, `<sl-dialog>`, `<sl-drawer>`, and `<sl-dropdown>` - Removed `position: relative` from the common component stylesheet - Updated Lit to 2.1.0 - Updated all other dependencies to latest versions ## 2.0.0-beta.63 - 🚨 BREAKING: changed the `type` attribute to `variant` in `<sl-alert>`, `<sl-badge>`, `<sl-button>`, and `<sl-tag>` since it's more appropriate and to disambiguate from other `type` attributes - 🚨 BREAKING: removed `base` part from `<sl-divider>` to simplify the styling API - Added the experimental `<sl-split-panel>` component - Added `focus()` and `blur()` methods to `<sl-select>` [#625](https://github.com/shoelace-style/shoelace/pull/625) - Fixed a bug where setting `tooltipFormatter` on `<sl-range>` in JSX causes React@experimental to error out - Fixed a bug where clicking on a slotted icon in `<sl-button>` wouldn't submit forms [#626](https://github.com/shoelace-style/shoelace/issues/626) - Added the `sl-` prefix to generated ids for `<sl-tab>` and `<sl-tab-panel>` - Refactored `<sl-button>` to use Lit's static expressions to reduce code - Simplified `<sl-spinner>` animation ## 2.0.0-beta.62 - 🚨 BREAKING: changed the `locale` attribute to `lang` in `<sl-format-bytes>`, `<sl-format-date>`, `<sl-format-number>`, and `<sl-relative-time>` to be consistent with how localization is handled - Added localization support including translations for English, German, German (Switzerland), Spanish, French, Hebrew, Japanese, Dutch, Polish, Portuguese, and Russian translations [#419](https://github.com/shoelace-style/shoelace/issues/419) - CodePen examples will now open in light or dark depending on your current preference - Fixed a bug where tag names weren't being generated in `vscode.html-custom-data.json` [#593](https://github.com/shoelace-style/shoelace/pull/593) - Fixed a bug in `<sl-tooltip>` where the tooltip wouldn't reposition when content changed - Fixed a bug in `<sl-select>` where focusing on a filled control showed the wrong focus ring - Fixed a bug where setting `value` initially on `<sl-color-picker>` didn't work in React [#602](https://github.com/shoelace-style/shoelace/issues/602) - Updated filled inputs to have the same appearance when focused - Updated `color` dependency from 3.1.3 to 4.0.2 - Updated `<sl-format-bytes>`, `<sl-format-date>`, `<sl-format-number>`, and `<sl-relative-time>` to work like other localized components - Upgraded the status of `<sl-qr-code>` from experimental to stable - Updated to Bootstrap Icons to 1.7.2 - Upgraded color to 4.1.0 ## 2.0.0-beta.61 This release improves the dark theme by shifting luminance in both directions, slightly condensing the spectrum. This results in richer colors in dark mode. It also reduces theme stylesheet sizes by eliminating superfluous gray palette variations. In [beta.48](#_200-beta48), I introduced a change to color tokens that allowed you to access alpha values at the expense of a verbose, non-standard syntax. After considering feedback from the community, I've decided to revert this change so the `rgb()` function is no longer required. Many users reported never using it for alpha, and even more reported having trouble remembering to use `rgb()` and that it was causing more harm than good. Furthermore, both Safari and Firefox have implemented [`color-mix()`](<https://developer.mozilla.org/en-US/docs/Web/CSS/color_value/color-mix()>) behind a flag, so access to alpha channels and other capabilities are coming to the browser soon. If you're using color tokens in your own stylesheet, simply remove the `rgb()` to update to this version. ```css .your-styles { /* change this */ color: rgb(var(--sl-color-primary-500)); /* to this */ color: var(--sl-color-primary-500); } ``` Thank you for your help and patience with testing Shoelace. I promise, we're not far from a stable release! - 🚨 BREAKING: removed blue gray, cool gray, true gray, and warm gray color palettes - 🚨 BREAKING: removed `--sl-focus-ring-color`, and `--sl-focus-ring-alpha` (use `--sl-focus-ring` instead) - 🚨 BREAKING: removed `--sl-surface-base` and `--sl-surface-base-alt` tokens (use the neutral palette instead) - Added experimental `<sl-visually-hidden>` component - Added `clear-icon` slot to `<sl-select>` [#591](https://github.com/shoelace-style/shoelace/issues/591) - Fixed a bug in `<sl-progress-bar>` where the label would show in the default slot - Improved the dark theme palette so colors are bolder and don't appear washed out - Improved a11y of `<sl-avatar>` by representing it as an image with an `alt` [#579](https://github.com/shoelace-style/shoelace/issues/579) - Improved a11y of the scroll buttons in `<sl-tab-group>` - Improved a11y of the close button in `<sl-tab>` - Improved a11y of `<sl-tab-panel>` by removing an invalid `aria-selected` attribute [#579](https://github.com/shoelace-style/shoelace/issues/579) - Improved a11y of `<sl-icon>` by not using a variation of the `name` attribute for labels (use the `label` prop instead) - Moved `role` from the shadow root to the host element in `<sl-menu>` - Removed redundant `role="menu"` in `<sl-dropdown>` - Slightly faster animations for showing and hiding `<sl-dropdown>` - Updated to Bootstrap Icons to 1.7.1 - Upgraded the status of `<sl-mutation-observer>` from experimental to stable ## 2.0.0-beta.60 - Added React examples and CodePen links to all components - Changed the `attr` in experimental `<sl-mutation-observer>` to require `"*"` instead of `""` to target all attributes - Fixed a bug in `<sl-progress-bar>` where the `label` attribute didn't set the label - Fixed a bug in `<sl-rating>` that caused disabled and readonly controls to transition on hover - The `panel` property of `<sl-tab>` is now reflected - The `name` property of `<sl-tab-panel>` is now reflected ## 2.0.0-beta.59 - Added React wrappers as first-class citizens - Added eye dropper to `<sl-color-picker>` when the browser supports the [EyeDropper API](https://wicg.github.io/eyedropper-api/) - Fixed a bug in `<sl-button-group>` where buttons groups with only one button would have an incorrect border radius - Improved the `<sl-color-picker>` trigger's border in dark mode - Switched clearable icon from `x-circle` to `x-circle-fill` to make it easier to recognize - Updated to Bootstrap Icons to 1.7.0 - Updated to Lit 2.0.2 ## 2.0.0-beta.58 This version once again restores the bundled distribution because the unbundled + CDN approach is currently confusing and [not working properly](https://github.com/shoelace-style/shoelace/issues/559#issuecomment-949662331). Unbundling the few dependencies Shoelace has is still a goal of the project, but [this jsDelivr bug](https://github.com/jsdelivr/jsdelivr/issues/18337) needs to be resolved before we can achieve it. I sincerely apologize for the instability of the last few beta releases as a result of this effort. - Added experimental `<sl-animated-image>` component - Added `label` attribute to `<sl-progress-bar>` and `<sl-progress-ring>` to improve a11y - Fixed a bug where the tooltip would show briefly when clicking a disabled `<sl-range>` - Fixed a bug that caused a console error when `<sl-range>` was used - Fixed a bug where the `nav` part in `<sl-tab-group>` was on the incorrect element [#563](https://github.com/shoelace-style/shoelace/pull/563) - Fixed a bug where non-integer aspect ratios were calculated incorrectly in `<sl-responsive-media>` - Fixed a bug in `<sl-range>` where setting `value` wouldn't update the active and inactive portion of the track [#572](https://github.com/shoelace-style/shoelace/pull/572) - Reverted to publishing the bundled dist and removed `/+esm` links from the docs - Updated to Bootstrap Icons to 1.6.1 ## 2.0.0-beta.57 - Fix CodePen links and CDN links ## 2.0.0-beta.56 This release is the second attempt at unbundling dependencies. This will be a breaking change only if your configuration _does not_ support bare module specifiers. CDN users and bundler users will be unaffected, but note the URLs for modules on the CDN must have the `/+esm` now. - Added the `hoist` attribute to `<sl-tooltip>` [#564](https://github.com/shoelace-style/shoelace/issues/564) - Unbundled dependencies and configured external imports to be packaged with bare module specifiers ## 2.0.0-beta.55 - Revert unbundling due to issues with the CDN not handling bare module specifiers as expected ## 2.0.0-beta.54 Shoelace doesn't have a lot of dependencies, but this release unbundles most of them so you can potentially save some extra kilobytes. This will be a breaking change only if your configuration _does not_ support bare module specifiers. CDN users and bundler users will be unaffected. - 🚨 BREAKING: renamed the `sl-clear` event to `sl-remove`, the `clear-button` part to `remove-button`, and the `clearable` property to `removable` in `<sl-tag>` - Added the `disabled` prop to `<sl-resize-observer>` - Fixed a bug in `<sl-mutation-observer>` where setting `disabled` initially didn't work - Unbundled dependencies and configured external imports to be packaged with bare module specifiers ## 2.0.0-beta.53 - 🚨 BREAKING: removed `<sl-menu-divider>` (use `<sl-divider>` instead) - 🚨 BREAKING: removed `percentage` attribute from `<sl-progress-bar>` and `<sl-progress-ring>` (use `value` instead) - 🚨 BREAKING: switched the default `type` of `<sl-tag>` from `primary` to `neutral` - Added the experimental `<sl-mutation-observer>` component - Added the `<sl-divider>` component - Added `--sl-color-neutral-0` and `--sl-color-neutral-50` as early surface tokens to improve the appearance of alert, card, and panels in dark mode - Added the `--sl-panel-border-width` design token - Added missing background color to `<sl-details>` - Added the `--padding` custom property to `<sl-tab-panel>` - Added the `outline` variation to `<sl-button>` [#522](https://github.com/shoelace-style/shoelace/issues/522) - Added the `filled` variation to `<sl-input>`, `<sl-textarea>`, and `<sl-select>` and supporting design tokens - Added the `control` part to `<sl-select>` so you can target the main control with CSS [#538](https://github.com/shoelace-style/shoelace/issues/538) - Added a border to `<sl-badge>` to improve contrast when drawn on various background colors - Added `--track-color-active` and `--track-color-inactive` custom properties to `<sl-range>` [#550](https://github.com/shoelace-style/shoelace/issues/550) - Added the undocumented custom properties `--thumb-size`, `--tooltip-offset`, `--track-height` on `<sl-range>` - Changed the default `distance` in `<sl-dropdown>` from `2` to `0` [#538](https://github.com/shoelace-style/shoelace/issues/538) - Fixed a bug where `<sl-select>` would be larger than the viewport when it had lots of options [#544](https://github.com/shoelace-style/shoelace/issues/544) - Fixed a bug where `<sl-progress-ring>` wouldn't animate in Safari - Updated the default height of `<sl-progress-bar>` from `16px` to `1rem` and added a subtle shadow to indicate depth - Removed the `lit-html` dependency and moved corresponding imports to `lit` [#546](https://github.com/shoelace-style/shoelace/issues/546) ## 2.0.0-beta.52 - 🚨 BREAKING: changed the `--stroke-width` custom property of `<sl-spinner>` to `--track-width` for consistency - 🚨 BREAKING: removed the `size` and `stroke-width` attributes from `<sl-progress-ring>` so it's fully customizable with CSS (use the `--size` and `--track-width` custom properties instead) - Added the `--speed` custom property to `<sl-spinner>` - Added the `--size` and `--track-width` custom properties to `<sl-progress-ring>` - Added tests for `<sl-badge>` [#530](https://github.com/shoelace-style/shoelace/pull/530) - Fixed a bug where `<sl-tab>` wasn't using a border radius token [#523](https://github.com/shoelace-style/shoelace/issues/523) - Fixed a bug in the Remix Icons example where some icons would 404 [#528](https://github.com/shoelace-style/shoelace/issues/528) - Updated `<sl-progress-ring>` to use only CSS for styling - Updated `<sl-spinner>` to use an SVG and improved the indicator animation - Updated to Lit 2.0 and lit-html 2.0 🔥 ## 2.0.0-beta.51 A number of users had trouble counting characters that repeat, so this release improves design token patterns so that "t-shirt sizes" are more accessible. For example, `--sl-font-size-xxx-large` has become `--sl-font-size-3x-large`. This change applies to all design tokens that use this scale. - 🚨 BREAKING: all t-shirt size design tokens now use `2x`, `3x`, `4x` instead of `xx`, `xxx`, `xxxx` - Added missing `--sl-focus-ring-*` tokens to dark theme - Added an "Importing" section to all components with copy/paste code to make cherry picking easier - Improved the documentation search with a custom plugin powered by [Lunr](https://lunrjs.com/) - Improved the `--sl-shadow-x-small` elevation - Improved visibility of elevations and overlays in dark theme - Reduced the size of `<sl-color-picker>` slightly to better accommodate mobile devices - Removed `<sl-icon>` dependency from `<sl-color-picker>` and improved the copy animation ## 2.0.0-beta.50 - Added `<sl-breadcrumb>` and `<sl-breadcrumb-item>` components - Added `--sl-letter-spacing-denser`, `--sl-letter-spacing-looser`, `--sl-line-height-denser`, and `--sl-line-height-looser` design tokens - Fixed a bug where form controls would error out when the value was set to `undefined` [#513](https://github.com/shoelace-style/shoelace/pull/513) ## 2.0.0-beta.49 This release changes the way focus states are applied to elements. In browsers that support [`:focus-visible`](https://developer.mozilla.org/en-US/docs/Web/CSS/:focus-visible), it will be used. In unsupportive browsers ([currently only Safari](https://caniuse.com/mdn-css_selectors_focus-visible)), `:focus` will be used instead. This means the browser will determine whether a focus ring should be shown based on how the user interacts with the page. This release also fixes a critical bug in the color scale where `--sl-color-neutral-0` and `--sl-color-neutral-1000` were reversed. - 🚨 BREAKING: fixed a bug where `--sl-color-neutral-0` and `--sl-color-neutral-1000` were inverted (swap them to update) - 🚨 BREAKING: removed the `no-fieldset` property from `<sl-radio-group>` (fieldsets are now hidden by default; use `fieldset` to show them) - 🚨 BREAKING: removed `--focus-ring` custom property from `<sl-input>`, `<sl-select>`, `<sl-tab>` for consistency with other form controls - Added `--swatch-size` custom property to `<sl-color-picker>` - Added `date` to `<sl-input>` as a supported `type` - Added the `--sl-focus-ring` design token for a more convenient way to apply focus ring styles - Adjusted elevation tokens to use neutral in light mode and black in dark mode - Adjusted `--sl-overlay-background-color` in dark theme to be black instead of gray - Fixed a bug in `<sl-color-picker>` where the opacity slider wasn't showing the current color - Fixed a bug where Edge in Windows would show the native password toggle next to the custom password toggle [#508](https://github.com/shoelace-style/shoelace/issues/508) - Fixed a bug where pressing up/down in `<sl-tab-group>` didn't select the next/previous tab in vertical placements - Improved size of `<sl-color-picker>` - Improved icon contrast in `<sl-input>` - Improved contrast of `<sl-switch>` - Improved `:focus-visible` behavior in many components - Removed elevation from `<sl-color-picker>` when rendered inline - Removed custom `:focus-visible` logic in favor of a directive that outputs `:focus-visible` or `:focus` depending on browser support - Updated to Lit 2.0.0-rc.3 - Updated to lit-html 2.0.0-rc.4 ## 2.0.0-beta.48 This release improves theming by offering both light and dark themes that can be used autonomously. It also improves contrast in most components, adds a variety of new color primitives, and changes the way color tokens are consumed. Previously, color tokens were in hexadecimal format. Now, Shoelace now uses an `R G B` format that requires you to use the `rgb()` function in your CSS. ```css .example { /* rgb() is required now */ color: var(--sl-color-neutral-500); } ``` This is more verbose than previous versions, but it has the advantage of letting you set the alpha channel of any color token. ```css .example-with-alpha { /* easily adjust opacity for any color token */ color: rgb(var(--sl-color-neutral-500) / 50%); } ``` This change applies to all design tokens that implement a color. Refer to the [color tokens](/tokens/color) page for more details. - 🚨 BREAKING: all design tokens that implement colors have been converted to `R G B` and must be used with the `rgb()` function - 🚨 BREAKING: removed `--sl-color-black|white` color tokens (use `--sl-color-neutral-0|1000` instead) - 🚨 BREAKING: removed `--sl-color-primary|success|warning|info|danger-text` design tokens (use theme or primitive colors instead) - 🚨 BREAKING: removed `info` variant from `<sl-alert>`, `<sl-badge>`, `<sl-button>`, and `<sl-tag>` (use `neutral` instead) - 🚨 BREAKING: removed `--sl-color-info-*` design token (use `--sl-color-neutral-*` instead) - 🚨 BREAKING: renamed `dist/themes/base.css` to `dist/themes/light.css` - 🚨 BREAKING: removed `--sl-focus-ring-color-primary` tokens (use color tokens and `--sl-focus-ring-width|alpha` instead) - 🚨 BREAKING: removed `--tabs-border-color` from `<sl-tab-group>` (use `--track-color` instead) - 🚨 BREAKING: changed the default value for `effect` to `none` in `<sl-skeleton>` (use `sheen` to restore the original behavior) - Added new color primitives to the base set of design tokens - Added `--sl-color-*-950` swatches to all color palettes - Added a console error that appears when menu items have duplicate values in `<sl-select>` - Added CodePen link to code examples - Added `prefix` and `suffix` slots to `<sl-select>` [#501](https://github.com/shoelace-style/shoelace/pull/501) - Added `--indicator-color` custom property to `<sl-tab-group>` - Exposed base and dark stylesheets so they can be imported via JavaScript [#438](https://github.com/shoelace-style/shoelace/issues/438) - Fixed a bug in `<sl-menu>` where pressing <kbd>Enter</kbd> after using type to select would result in the wrong value - Fixed a bug in `<sl-radio-group>` where clicking a radio button would cause the wrong control to be focused - Fixed a bug in `<sl-button>` and `<sl-icon-button>` where an unintended `ref` attribute was present - Fixed a bug in the focus-visible utility that failed to respond to mouseup events - Fixed a bug where clicking on a menu item would persist its hover/focus state - Fixed a bug in `<sl-select>` where it would erroneously intercept important keyboard shortcuts [#504](https://github.com/shoelace-style/shoelace/issues/504) - Improved contrast throughout all components [#128](https://github.com/shoelace-style/shoelace/issues/128) - Refactored thumb position logic in `<sl-switch>` [#490](https://github.com/shoelace-style/shoelace/pull/490) - Reworked the dark theme to use an inverted + shifted design token approach instead of component-specific selectors ## 2.0.0-beta.47 This release improves how component dependencies are imported. If you've been cherry picking, you no longer need to import component dependencies manually. This significantly improves developer experience, making Shoelace even easier to use. For transparency, component dependencies will continue to be listed in the docs. - Added "Reflects" column to the properties table - Dependencies are now automatically imported for all components - Fixed a bug where tabbing into `<sl-radio-group>` would not always focus the checked radio - Fixed a bug in component styles that prevented the box sizing reset from being applied - Fixed a regression in `<sl-color-picker>` where dragging the grid handle wasn't smooth - Fixed a bug where slot detection could incorrectly match against slots of child elements [#481](https://github.com/shoelace-style/shoelace/pull/481) - Fixed a bug in `<sl-input>` where focus would move to the end of the input when typing in Safari [#480](https://github.com/shoelace-style/shoelace/issues/480) - Improved base path utility logic ## 2.0.0-beta.46 This release improves the developer experience of `<sl-animation>`. Previously, an animation was assumed to be playing unless the `pause` attribute was set. This behavior has been reversed and `pause` has been removed. Now, animations will not play until the new `play` attribute is applied. This is a lot more intuitive and makes it easier to activate animations imperatively. In addition, the `play` attribute is automatically removed automatically when the animation finishes or cancels, making it easier to restart finite animations. Lastly, the animation's timing is now accessible through the new `currentTime` property instead of `getCurrentTime()` and `setCurrentTime()`. In addition, Shoelace no longer uses Sass. Component styles now use Lit's template literal styles and theme files use pure CSS. - 🚨 BREAKING: removed the `pause` attribute from `<sl-animation>` (use `play` to start and stop the animation instead) - 🚨 BREAKING: removed `getCurrentTime()` and `setCurrentTime()` from `<sl-animation>` (use the `currentTime` property instead) - 🚨 BREAKING: removed the `close-on-select` attribute from `<sl-dropdown>` (use `stay-open-on-select` instead) - Added the `currentTime` property to `<sl-animation>` to control the current time without methods - Fixed a bug in `<sl-range>` where the tooltip wasn't showing in Safari [#477](https://github.com/shoelace-style/shoelace/issues/477) - Fixed a bug in `<sl-menu>` where pressing <kbd>Enter</kbd> in a menu didn't work with click handlers - Reworked `<sl-menu>` and `<sl-menu-item>` to use a roving tab index and improve keyboard accessibility - Reworked tabbable logic to be more performant [#466](https://github.com/shoelace-style/shoelace/issues/466) - Switched component stylesheets from Sass to Lit's template literal styles - Switched theme stylesheets from Sass to CSS ## 2.0.0-beta.45 This release changes the way component metadata is generated. Previously, the project used TypeDoc to analyze components and generate a very large file with type data. The data was then parsed and converted to an easier-to-consume file called `metadata.json`. Alas, TypeDoc is expensive to run and the metadata format wasn't standard. Thanks to an amazing effort by [Pascal Schilp](https://twitter.com/passle_), the world has a simpler, faster way to gather metadata using the [Custom Elements Manifest Analyzer](https://github.com/open-wc/custom-elements-manifest). Not only is this tool faster, but the data follows the evolving `custom-elements.json` format. This is exciting because a standard format for custom elements opens the door for many potential uses, including documentation generation, framework adapters, IDE integrations, third-party uses, and more. [Check out Pascal's great article](https://dev.to/open-wc/introducing-custom-elements-manifest-gkk) for more info about `custom-elements.json` and the new analyzer. The docs have been updated to use the new `custom-elements.json` file. If you're relying on the old `metadata.json` file for any purpose, this will be a breaking change for you. - 🚨 BREAKING: removed the `sl-overlay-click` event from `<sl-dialog>` and `<sl-drawer>` (use `sl-request-close` instead) [#471](https://github.com/shoelace-style/shoelace/discussions/471) - 🚨 BREAKING: removed `metadata.json` (use `custom-elements.json` instead) - Added `custom-elements.json` for component metadata - Added `sl-request-close` event to `<sl-dialog>` and `<sl-drawer>` - Added `dialog.denyClose` and `drawer.denyClose` animations - Fixed a bug in `<sl-color-picker>` where setting `value` immediately wouldn't trigger an update - Fixed a bug in `<sl-dialog>` and `<sl-drawer>` where setting `open` initially didn't set a focus trap - Fixed a bug that resulted in form controls having incorrect validity when `disabled` was initially set [#473](https://github.com/shoelace-style/shoelace/issues/473) - Fixed a bug in the docs that caused the metadata file to be requested twice - Fixed a bug where tabbing out of a modal would cause the browser to lag [#466](https://github.com/shoelace-style/shoelace/issues/466) - Updated the docs to use the new `custom-elements.json` for component metadata ## 2.0.0-beta.44 - 🚨 BREAKING: all `invalid` props on form controls now reflect validity before interaction [#455](https://github.com/shoelace-style/shoelace/issues/455) - Allow `null` to be passed to disable animations in `setDefaultAnimation()` and `setAnimation()` - Converted build scripts to ESM - Fixed a bug in `<sl-checkbox>` where `invalid` did not update properly - Fixed a bug in `<sl-dropdown>` where a `keydown` listener wasn't cleaned up properly - Fixed a bug in `<sl-select>` where `sl-blur` was emitted prematurely [#456](https://github.com/shoelace-style/shoelace/issues/456) - Fixed a bug in `<sl-select>` where no selection with `multiple` resulted in an incorrect value [#457](https://github.com/shoelace-style/shoelace/issues/457) - Fixed a bug in `<sl-select>` where `sl-change` was emitted immediately after connecting to the DOM [#458](https://github.com/shoelace-style/shoelace/issues/458) - Fixed a bug in `<sl-select>` where non-printable keys would cause the menu to open - Fixed a bug in `<sl-select>` where `invalid` was not always updated properly - Reworked the `@watch` decorator to use `update` instead of `updated` resulting in better performance and flexibility ## 2.0.0-beta.43 - Added `?` to optional arguments in methods tables in the docs - Added the `scrollPosition()` method to `<sl-textarea>` to get/set scroll position - Added initial tests for `<sl-dialog>`, `<sl-drawer>`, `<sl-dropdown>`, and `<sl-tooltip>` - Fixed a bug in `<sl-tab-group>` where scrollable tab icons were not displaying correctly - Fixed a bug in `<sl-dialog>` and `<sl-drawer>` where preventing clicks on the overlay no longer worked as described [#452](https://github.com/shoelace-style/shoelace/issues/452) - Fixed a bug in `<sl-dialog>` and `<sl-drawer>` where setting initial focus no longer worked as described [#453](https://github.com/shoelace-style/shoelace/issues/453) - Fixed a bug in `<sl-card>` where the `slotchange` listener wasn't attached correctly [#454](https://github.com/shoelace-style/shoelace/issues/454) - Fixed lifecycle bugs in a number of components [#451](https://github.com/shoelace-style/shoelace/issues/451) - Removed `fill: both` from internal animate utility so styles won't "stick" by default [#450](https://github.com/shoelace-style/shoelace/issues/450) ## 2.0.0-beta.42 This release addresses an issue with the `open` attribute no longer working in a number of components, as a result of the changes in beta.41. It also removes a small but controversial feature that complicated show/hide logic and led to a poor experience for developers and end users. There are two ways to show/hide affected components: by calling `show() | hide()` and by toggling the `open` prop. Previously, it was possible to call `event.preventDefault()` in an `sl-show | sl-hide ` handler to stop the component from showing/hiding. The problem becomes obvious when you set `el.open = false`, the event gets canceled, and in the next cycle `el.open` has reverted to `true`. Not only is this unexpected, but it also doesn't play nicely with frameworks. Additionally, this made it impossible to await `show() | hide()` since there was a chance they'd never resolve. Technical reasons aside, canceling these events seldom led to a good user experience, so the decision was made to no longer allow `sl-show | sl-hide` to be cancelable. - 🚨 BREAKING: `sl-show` and `sl-hide` events are no longer cancelable - Added Iconoir example to the icon docs - Added Web Test Runner - Added initial tests for `<sl-alert>` and `<sl-details>` - Changed the `cancelable` default to `false` for the internal `@event` decorator - Fixed a bug where toggling `open` stopped working in `<sl-alert>`, `<sl-dialog>`, `<sl-drawer>`, `<sl-dropdown>`, and `<sl-tooltip>` - Fixed a bug in `<sl-range>` where setting a value outside the default `min` or `max` would clamp the value [#448](https://github.com/shoelace-style/shoelace/issues/448) - Fixed a bug in `<sl-dropdown>` where placement wouldn't adjust properly when shown [#447](https://github.com/shoelace-style/shoelace/issues/447) - Fixed a bug in the internal `shimKeyframesHeightAuto` utility that caused `<sl-details>` to measure heights incorrectly [#445](https://github.com/shoelace-style/shoelace/issues/445) - Fixed a number of imports that should have been type imports - Updated Lit to 2.0.0-rc.2 - Updated esbuild to 0.12.4 ## 2.0.0-beta.41 This release changes how components animate. In previous versions, CSS transitions were used for most show/hide animations. Transitions are problematic due to the way `transitionend` works. This event fires once _per transition_, and it's impossible to know which transition to look for when users can customize any possible CSS property. Because of this, components previously required the `opacity` property to transition. If a user were to prevent `opacity` from transitioning, the component wouldn't hide properly and the `sl-after-show|hide` events would never emit. CSS animations, on the other hand, have a more reliable `animationend` event. Alas, `@keyframes` don't cascade and can't be injected into a shadow DOM via CSS, so there would be no good way to customize them. The most elegant solution I found was to use the [Web Animations API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Animations_API), which offers more control over animations at the expense of customizations being done in JavaScript. Fortunately, through the [Animation Registry](/getting-started/customizing#animations), you can customize animations globally and/or per component with a minimal amount of code. - 🚨 BREAKING: changed `left` and `right` placements to `start` and `end` in `<sl-drawer>` - 🚨 BREAKING: changed `left` and `right` placements to `start` and `end` in `<sl-tab-group>` - 🚨 BREAKING: removed `--hide-duration`, `--hide-timing-function`, `--show-duration`, and `--show-timing-function` custom properties from `<sl-tooltip>` (use the Animation Registry instead) - Added the Animation Registry - Fixed a bug where removing `<sl-dropdown>` from the DOM and adding it back destroyed the popover reference [#443](https://github.com/shoelace-style/shoelace/issues/443) - Updated animations for `<sl-alert>`, `<sl-dialog>`, `<sl-drawer>`, `<sl-dropdown>`, and `<sl-tooltip>` to use the Animation Registry instead of CSS transitions - Improved a11y by respecting `prefers-reduced-motion` for all show/hide animations - Improved `--show-delay` and `--hide-delay` behavior in `<sl-tooltip>` so they only apply on hover - Removed the internal popover utility ## 2.0.0-beta.40 - 🚨 BREAKING: renamed `<sl-responsive-embed>` to `<sl-responsive-media>` and added support for images and videos [#436](https://github.com/shoelace-style/shoelace/issues/436) - Fixed a bug where setting properties before an element was defined would render incorrectly [#425](https://github.com/shoelace-style/shoelace/issues/425) - Fixed a bug that caused all modules to be imported when cherry picking certain components [#439](https://github.com/shoelace-style/shoelace/issues/439) - Fixed a bug where the scrollbar would reposition `<sl-dialog>` on hide causing it to jump [#424](https://github.com/shoelace-style/shoelace/issues/424) - Fixed a bug that prevented the project from being built in a Windows environment - Improved a11y in `<sl-progress-ring>` - Removed `src/utilities/index.ts` to prevent tree-shaking confusion (please import utilities directly from their respective modules) - Removed global `[hidden]` styles so they don't affect anything outside of components - Updated to Bootstrap Icons 1.5.0 - Updated React docs to use [`@shoelace-style/react`](https://github.com/shoelace-style/react) - Updated NextJS docs [#434](https://github.com/shoelace-style/shoelace/pull/434) - Updated TypeScript to 4.2.4 ## 2.0.0-beta.39 - Added experimental `<sl-qr-code>` component - Added `system` icon library and updated all components to use this instead of the default icon library [#420](https://github.com/shoelace-style/shoelace/issues/420) - Updated to esbuild 0.8.57 - Updated to Lit 2.0.0-rc.1 and lit-html 2.0.0-rc.2 ## 2.0.0-beta.38 - 🚨 BREAKING: `<sl-radio>` components must be located inside an `<sl-radio-group>` for proper accessibility [#218](https://github.com/shoelace-style/shoelace/issues/218) - Added `<sl-radio-group>` component [#218](https://github.com/shoelace-style/shoelace/issues/218) - Added `--header-spacing`, `--body-spacing`, and `--footer-spacing` custom properties to `<sl-drawer>` and `<sl-dialog>` [#409](https://github.com/shoelace-style/shoelace/issues/409) - Fixed a bug where `<sl-menu-item>` prefix and suffix slots wouldn't always receive the correct spacing - Fixed a bug where `<sl-badge>` used `--sl-color-white` instead of the correct design tokens [#407](https://github.com/shoelace-style/shoelace/issues/407) - Fixed a bug in `<sl-dialog>` and `<sl-drawer>` where the escape key would cause parent components to close - Fixed a race condition bug in `<sl-icon>` [#410](https://github.com/shoelace-style/shoelace/issues/410) - Improved focus trap behavior in `<sl-dialog>` and `<sl-drawer>` - Improved a11y in `<sl-dialog>` and `<sl-drawer>` by restoring focus to trigger on close - Improved a11y in `<sl-radio>` with Windows high contrast mode [#215](https://github.com/shoelace-style/shoelace/issues/215) - Improved a11y in `<sl-select>` by preventing the chevron icon from being announced - Internal: removed the `options` argument from the modal utility as focus trapping is now handled internally ## 2.0.0-beta.37 - Added `click()` method to `<sl-checkbox>`, `<sl-radio>`, and `<sl-switch>` - Added the `activation` attribute to `<sl-tab-group>` to allow for automatic and manual tab activation - Added `npm run create <tag>` script to scaffold new components faster - Fixed a bug in `<sl-tooltip>` where events weren't properly cleaned up on disconnect - Fixed a bug in `<sl-tooltip>` where they wouldn't display after toggling `disabled` off and on again [#391](https://github.com/shoelace-style/shoelace/issues/391) - Fixed a bug in `<sl-details>` where `show()` and `hide()` would toggle the control when disabled - Fixed a bug in `<sl-color-picker>` where setting `value` wouldn't update the control - Fixed a bug in `<sl-tab-group>` where tabs that are initially disabled wouldn't receive the indicator on activation [#403](https://github.com/shoelace-style/shoelace/issues/403) - Fixed incorrect event names for `sl-after-show` and `sl-after-hide` in `<sl-details>` - Improved a11y for disabled buttons that are rendered as links - Improved a11y for `<sl-button-group>` by adding the correct `role` attribute - Improved a11y for `<sl-input>`, `<sl-range>`, `<sl-select>`, and `<sl-textarea>` so labels and helper text are read properly by screen readers - Removed `sl-show`, `sl-hide`, `sl-after-show`, `sl-after-hide` events from `<sl-color-picker>` (the color picker's visibility cannot be controlled programmatically so these shouldn't have been exposed; the dropdown events now bubble up so you can listen for those instead) - Reworked `<sl-button-group>` so it doesn't require light DOM styles ## 2.0.0-beta.36 - 🚨 BREAKING: renamed `setFocus()` to `focus()` in button, checkbox, input, menu item, radio, range, rating, select, switch, and tab - 🚨 BREAKING: renamed `removeFocus()` to `blur()` in button, checkbox, input, menu item, radio, range, rating, select, switch, and tab - Added `click()` method to `<sl-button>` - Fixed a bug where toggling `open` on `<sl-drawer>` would skip the transition - Fixed a bug where `<sl-color-picker>` could be opened when disabled - Fixed a bug in `<sl-color-picker>` that caused erratic slider behaviors [#388](https://github.com/shoelace-style/shoelace/issues/388) [#389](https://github.com/shoelace-style/shoelace/issues/389) - Fixed a bug where `<sl-details>` wouldn't always render the correct height when open initially [#357](https://github.com/shoelace-style/shoelace/issues/357) - Renamed `components.json` to `metadata.json` - Updated to the prerelease versions of LitElement and lit-html - Updated to Bootstrap Icons 1.4.1 ## 2.0.0-beta.35 - Fixed a bug in `<sl-animation>` where `sl-cancel` and `sl-finish` events would never fire - Fixed a bug where `<sl-alert>` wouldn't always transition properly - Fixed a bug where using `<sl-menu>` inside a shadow root would break keyboard selections [#382](https://github.com/shoelace-style/shoelace/issues/382) - Fixed a bug where toggling `multiple` in `<sl-select>` would lead to a stale display label - Fixed a bug in `<sl-tab-group>` where changing `placement` could result in the active tab indicator being drawn a few pixels off - Fixed a bug in `<sl-button>` where link buttons threw an error on focus, blur, and click - Improved `@watch` decorator to run after update instead of during - Updated `<sl-menu-item>` checked icon to `check` instead of `check2` - Upgraded the status of `<sl-resize-observer>` from experimental to stable ## 2.0.0-beta.34 This release changes the way components are registered if you're [cherry picking](/getting-started/installation?id=cherry-picking) or [using a bundler](/getting-started/installation?id=bundling). This recommendation came from the LitElement team and simplifies Shoelace's dependency graph. It also eliminates the need to call a `register()` function before using each component. From now on, importing a component will register it automatically. The caveat is that bundlers may not tree shake the library properly if you import from `@shoelace-style/shoelace`, so the recommendation is to import components and utilities from their corresponding files instead. - 🚨 BREAKING: removed `all.shoelace.js` (use `shoelace.js` instead) - 🚨 BREAKING: component modules now have a side effect, so bundlers may not tree shake properly when importing from `@shoelace-style/shoelace` (see the [installation page](/getting-started/installation?id=bundling) for more details and how to update) - Added `sl-clear` event to `<sl-select>` - Fixed a bug where dynamically changing menu items in `<sl-select>` would cause the display label to be blank [#374](https://github.com/shoelace-style/shoelace/discussions/374) - Fixed a bug where setting the `value` attribute or property on `<sl-input>` and `<sl-textarea>` would trigger validation too soon - Fixed the margin in `<sl-menu-label>` to align with menu items - Fixed `autofocus` attributes in `<sl-input>` and `<sl-textarea>` - Improved types for `autocapitalize` in `<sl-input>` and `<sl-textarea>` - Reverted the custom `@tag` decorator in favor of `@customElement` to enable auto-registration ## 2.0.0-beta.33 - Fixed a bug where link buttons could have incorrect `target`, `download`, and `rel` props - Fixed `aria-label` and `aria-labelledby` props in `<sl-dialog>` and `<sl-drawer>` - Fixed `tabindex` attribute in `<sl-menu>` - Fixed a bug in `<sl-select>` where tags would always render as pills - Fixed a bug in `<sl-button>` where calling `setFocus()` would throw an error ## 2.0.0-beta.32 - Added tag name maps so TypeScript can identify Shoelace elements [#371](https://github.com/shoelace-style/shoelace/pull/371) - Fixed a bug where the active tab indicator wouldn't render properly on tabs styled with `flex-end` [#355](https://github.com/shoelace-style/shoelace/issues/355) - Fixed a bug where `sl-change` wasn't emitted by `<sl-checkbox>` or `<sl-switch>` [#370](https://github.com/shoelace-style/shoelace/issues/370) - Fixed a bug where some props weren't being watched correctly in `<sl-alert>` and `<sl-color-picker>` - Improved `@watch` decorator so watch handlers don't run before the first render - Removed guards that were added due to previous watch handler behavior ## 2.0.0-beta.31 - Add touch support to `<sl-rating>` [#362](https://github.com/shoelace-style/shoelace/pull/362) - Fixed a bug where the `open` attribute on `<sl-details>` would prevent it from opening [#357](https://github.com/shoelace-style/shoelace/issues/357) - Fixed event detail type parsing so component class names are shown instead of `default` ## 2.0.0-beta.30 - Fix default exports for all components so cherry picking works again [#365](https://github.com/shoelace-style/shoelace/issues/365) - Revert FOUC base style because it interferes with some framework and custom element use cases ## 2.0.0-beta.29 **This release migrates component implementations from Shoemaker to LitElement.** Due to feedback from the community, Shoelace will rely on a more heavily tested library for component implementations. This gives you a more solid foundation and reduces my maintenance burden. Thank you for all your comments, concerns, and encouragement! Aside from that, everything else from beta.28 still applies plus the following. - 🚨 BREAKING: removed the `symbol` property from `<sl-rating>` and reverted to `getSymbol` for optimal flexibility - Added `vscode.html-custom-data.json` to the build to support IntelliSense (see [the usage section](/getting-started/usage#code-completion) for details) - Added a base style to prevent FOUC before components are defined - Fixed bug where TypeScript types weren't being generated [#364](https://github.com/shoelace-style/shoelace/pull/364) - Improved vertical padding in `<sl-tooltip>` - Moved chunk files into a separate folder - Reverted menu item active styles - Updated esbuild to 0.8.54 ## 2.0.0-beta.28 **This release includes a major under the hood overhaul of the library and how it's distributed.** Until now, Shoelace was developed with Stencil. This release moves to a lightweight tool called Shoemaker, a homegrown utility that provides declarative templating and data binding while reducing the boilerplate required for said features. This change in tooling addresses a number of longstanding bugs and limitations. It also gives us more control over the library and build process while streamlining development and maintenance. Instead of two different distributions, Shoelace now offers a single, standards-compliant collection of ES modules. This may affect how you install and use the library, so please refer to the [installation page](/getting-started/installation) for details. !> Due to the large number of internal changes, I would consider this update to be less stable than previous ones. If you're using Shoelace in a production app, consider holding off until the next beta to allow for more exhaustive testing from the community. Please report any bugs you find on the [issue tracker](https://github.com/shoelace-style/shoelace/issues). The component API remains the same except for the changes noted below. Thanks for your patience as I work diligently to make Shoelace more stable and future-proof. 🙌 - 🚨 BREAKING: removed the custom elements bundle (you can import ES modules directly) - 🚨 BREAKING: removed `getAnimationNames()` and `getEasingNames()` methods from `<sl-animation>` (you can import them from `utilities/animation.js` instead) - 🚨 BREAKING: removed the `<sl-icon-library>` component since it required imperative initialization (you can import the `registerIconLibrary()` function from `utilities/icon-library.js` instead) - 🚨 BREAKING: removed the experimental `<sl-theme>` component due to technical limitations (you should set the `sl-theme-{name}` class on the `<body>` instead) - 🚨 BREAKING: moved the base stylesheet from `dist/shoelace.css` to `dist/themes/base.css` - 🚨 BREAKING: moved `icons` into `assets/icons` to make future assets easier to colocate - 🚨 BREAKING: changed `getSymbol` property in `<sl-rating>` to `symbol` (it now accepts a string or a function that returns an icon name) - 🚨 BREAKING: renamed `setAssetPath()` to `setBasePath()` and added the ability to set the library's base path with a `data-shoelace` attribute (`setBasePath()` is exported from `utilities/base-path.js`) - Fixed `min` and `max` types in `<sl-input>` to allow numbers and strings [#330](https://github.com/shoelace-style/shoelace/issues/330) - Fixed a bug where `<sl-checkbox>`, `<sl-radio>`, and `<sl-switch>` controls would shrink with long labels [#325](https://github.com/shoelace-style/shoelace/issues/325) - Fixed a bug in `<sl-select>` where the dropdown menu wouldn't reposition when the box resized [#340](https://github.com/shoelace-style/shoelace/issues/340) - Fixed a bug where ignoring clicks and clicking the overlay would prevent the escape key from closing the dialog/drawer [#344](https://github.com/shoelace-style/shoelace/pull/344) - Removed the lazy loading dist (importing `shoelace.js` will load and register all components now) - Switched from Stencil to Shoemaker - Switched to a custom build powered by [esbuild](https://esbuild.github.io/) - Updated to Bootstrap Icons 1.4.0 ## 2.0.0-beta.27 - Added `handle-icon` slot to `<sl-image-comparer>` [#311](https://github.com/shoelace-style/shoelace/issues/311) - Added `label` and `helpText` props and slots to `<sl-range>` [#318](https://github.com/shoelace-style/shoelace/issues/318) - Added "Integrating with NextJS" tutorial to the docs, courtesy of [crutchcorn](https://github.com/crutchcorn) - Added `content` slot to `<sl-tooltip>` [#322](https://github.com/shoelace-style/shoelace/pull/322) - Fixed a bug in `<sl-select>` where removing a tag would toggle the dropdown - Fixed a bug in `<sl-input>` and `<sl-textarea>` where the input might not exist when the value watcher is called [#313](https://github.com/shoelace-style/shoelace/issues/313) - Fixed a bug in `<sl-details>` where hidden elements would receive focus when tabbing [#323](https://github.com/shoelace-style/shoelace/issues/323) - Fixed a bug in `<sl-icon>` where `sl-error` would only be emitted for network failures [#326](https://github.com/shoelace-style/shoelace/pull/326) - Reduced the default line-height for `<sl-tooltip>` - Updated `<sl-menu-item>` focus styles - Updated `<sl-select>` so tags will wrap when `multiple` is true - Updated to Stencil 2.4.0 ## 2.0.0-beta.26 - 🚨 BREAKING: Fixed animations bloat - Removed ~400 baked-in Animista animations because they were causing ~200KB of bloat (they can still be used with custom keyframes) - Reworked animations into a separate module ([`@shoelace-style/animations`](https://github.com/shoelace-style/animations)) so it's more maintainable and animations are sync with the latest version of animate.css - Animation and easing names are now camelCase (e.g. `easeInOut` instead of `ease-in-out`) - Added initial E2E tests [#169](https://github.com/shoelace-style/shoelace/pull/169) - Added the `FocusOptions` argument to all components that have a `setFocus()` method - Added `sl-initial-focus` event to `<sl-dialog>` and `<sl-drawer>` so focus can be customized to a specific element - Added `close-button` part to `<sl-tab>` so the close button can be customized - Added `scroll-button` part to `<sl-tab-group>` so the scroll buttons can be customized - Fixed a bug where `sl-hide` would be emitted twice when closing an alert with `hide()` - Fixed a bug in `<sl-color-picker>` where the toggle button was smaller than the preview button in Safari - Fixed a bug in `<sl-tab-group>` where activating a nested tab group didn't work properly [#299](https://github.com/shoelace-style/shoelace/issues/299) - Fixed a bug in `<sl-tab-group>` where removing tabs would throw an error - Fixed a bug in `<sl-alert>`, `<sl-dialog>`, `<sl-drawer>`, `<sl-select>`, and `<sl-tag>` where the close button's base wasn't exported so it couldn't be styled - Removed `text` type from `<sl-badge>` as it was erroneously copied and never had styles - Updated `<sl-tab-group>` so the `active` property is reflected to its attribute - Updated the docs to show dependencies instead of dependents which is much more useful when working with the custom elements bundle - Updated to Bootstrap Icons 1.3.0 ## 2.0.0-beta.25 - 🚨 BREAKING: Reworked color tokens - Theme colors are now inspired by Tailwind's professionally-designed color palette - Color token variations now range from 50, 100, 200, 300, 400, 500, 600, 700, 800, 900, 950 - Color token variations were inverted, e.g. 50 is lightest and 950 is darkest - All component styles were adapted to use the new color tokens, but visual changes are subtle - The dark theme was adapted use the new color tokens - HSL is no longer used because it is not perceptually uniform (this may be revisited when all browsers support [LCH colors](https://lea.verou.me/2020/04/lch-colors-in-css-what-why-and-how/)) - 🚨 BREAKING: Refactored `<sl-select>` to improve accessibility [#216](https://github.com/shoelace-style/shoelace/issues/216) - Removed the internal `<sl-input>` because it was causing problems with a11y and virtual keyboards - Removed `input`, `prefix` and `suffix` parts - 🚨 BREAKING: Removed `copy-button` part from `<sl-color-picker>` since copying is now done by clicking the preview - Added `getFormattedValue()` method to `<sl-color-picker>` so you can retrieve the current value in any format - Added visual separators between solid buttons in `<sl-button-group>` - Added `help-text` attribute to `<sl-input>`, `<sl-textarea>`, and `<sl-select>` - Fixed a bug where moving the mouse while `<sl-dropdown>` is closing would remove focus from the trigger - Fixed a bug where `<sl-menu-item>` didn't set a default color in the dark theme - Fixed a bug where `<sl-color-picker>` preview wouldn't update in Safari - Fixed a bug where removing an icon's `name` or `src` wouldn't remove the previously rendered SVG [#285](https://github.com/shoelace-style/shoelace/issues/285) - Fixed a bug where disabled link buttons didn't appear disabled - Improved button spacings and added split button example - Improved elevation tokens in dark theme - Improved accessibility in `<sl-tooltip>` by allowing escape to dismiss it [#219](https://github.com/shoelace-style/shoelace/issues/219) - Improved slot detection in `<sl-card>`, `<sl-dialog>`, and `<sl-drawer>` - Made `@types/resize-observer-browser` a dependency so users don't have to install it manually - Refactored internal label + help text logic into a functional component used by `<sl-input>`, `<sl-textarea>`, and `<sl-select>` - Removed `sl-blur` and `sl-focus` events from `<sl-menu>` since menus can't have focus as of 2.0.0-beta.22 - Updated `<sl-spinner>` so the indicator is more obvious - Updated to Bootstrap Icons 1.2.2 ## 2.0.0-beta.24 - Added `<sl-format-date>` component - Added `indeterminate` state to `<sl-progress-bar>` [#274](https://github.com/shoelace-style/shoelace/issues/274) - Added `--track-color`, `--indicator-color`, and `--label-color` to `<sl-progress-bar>` [#276](https://github.com/shoelace-style/shoelace/issues/276) - Added `allow-scripts` attribute to `<sl-include>` [#280](https://github.com/shoelace-style/shoelace/issues/280) - Fixed a bug where `<sl-menu-item>` color variable was incorrect [#272](https://github.com/shoelace-style/shoelace/issues/272) - Fixed a bug where `<sl-dialog>` and `<sl-drawer>` would emit the `sl-hide` event twice [#275](https://github.com/shoelace-style/shoelace/issues/275) - Fixed a bug where calling `event.preventDefault()` on certain form elements wouldn't prevent `<sl-form>` from submitting [#277](https://github.com/shoelace-style/shoelace/issues/277) - Fixed drag handle orientation in `<sl-image-comparer>` - Restyled `<sl-spinner>` so the track is visible and the indicator is smaller. - Removed `resize-observer-polyfill` in favor of `@types/resize-observer-browser` since all target browsers support `ResizeObserver` - Upgraded the status of `<sl-form>`, `<sl-image-comparer>`, and `<sl-include>` from experimental to stable ## 2.0.0-beta.23 - Added `<sl-format-number>` component - Added `<sl-relative-time>` component - Added `closable` attribute to `<sl-tab>` - Added experimental `<sl-resize-observer>` utility - Added experimental `<sl-theme>` utility and updated theming documentation - Fixed a bug where `<sl-menu-item>` wouldn't render properly in the dark theme - Fixed a bug where `<sl-select>` would show an autocomplete menu - Improved placeholder contrast in dark theme - Updated to Bootstrap Icons 1.1.0 - Updated to Stencil 2.3.0 ## 2.0.0-beta.22 - 🚨 BREAKING: Refactored `<sl-menu>` and `<sl-menu-item>` to improve accessibility by using proper focus states [#217](https://github.com/shoelace-style/shoelace/issues/217) - Moved `tabindex` from `<sl-menu>` to `<sl-menu-item>` - Removed the `active` attribute from `<sl-menu-item>` because synthetic focus states are bad for accessibility - Removed the `sl-activate` and `sl-deactivate` events from `<sl-menu-item>` (listen for `focus` and `blur` instead) - Updated `<sl-select>` so keyboard navigation still works - Added `no-scroll-controls` attribute to `<sl-tab-group>` [#253](https://github.com/shoelace-style/shoelace/issues/253) - Fixed a bug where setting `open` initially wouldn't show `<sl-dialog>` or `<sl-drawer>` [#255](https://github.com/shoelace-style/shoelace/issues/255) - Fixed a bug where `disabled` could be set when buttons are rendered as links - Fixed a bug where hoisted dropdowns would render in the wrong position when placed inside `<sl-dialog>` [#252](https://github.com/shoelace-style/shoelace/issues/252) - Fixed a bug where boolean aria attributes didn't explicitly set `true|false` string values in the DOM - Fixed a bug where `aria-describedby` was never set on tooltip targets in `<sl-tooltip>` - Fixed a bug where setting `position` on `<sl-image-comparer>` wouldn't update the divider's position - Fixed a bug where the check icon was announced to screen readers in `<sl-menu-item>` - Improved `<sl-icon-button>` accessibility by encouraging proper use of `label` and hiding the internal icon from screen readers [#220](https://github.com/shoelace-style/shoelace/issues/220) - Improved `<sl-dropdown>` accessibility by attaching `aria-haspopup` and `aria-expanded` to the slotted trigger - Refactored position logic to remove an unnecessary state variable in `<sl-image-comparer>` - Refactored design tokens to use `rem` instead of `px` for input height and spacing [#221](https://github.com/shoelace-style/shoelace/issues/221) - Removed `console.log` from modal utility - Updated to Stencil 2.2.0 ## 2.0.0-beta.21 - Added `label` slot to `<sl-input>`, `<sl-select>`, and `<sl-textarea>` [#248](https://github.com/shoelace-style/shoelace/issues/248) - Added `label` slot to `<sl-dialog>` and `<sl-drawer>` - Added experimental `<sl-include>` component - Added status code to the `sl-error` event in `<sl-icon>` - Fixed a bug where initial transitions didn't show in `<sl-dialog>` and `<sl-drawer>` [#247](https://github.com/shoelace-style/shoelace/issues/247) - Fixed a bug where indeterminate checkboxes would maintain the indeterminate state when toggled - Fixed a bug where concurrent active modals (i.e. dialog, drawer) would try to steal focus from each other - Improved `<sl-color-picker>` grid and slider handles [#246](https://github.com/shoelace-style/shoelace/issues/246) - Refactored `<sl-icon>` request logic and removed unused cache map - Reworked show/hide logic in `<sl-alert>`, `<sl-dialog>`, and `<sl-drawer>` to not use reflow hacks and the `hidden` attribute - Reworked slot logic in `<sl-card>`, `<sl-dialog>`, and `<sl-drawer>` - Updated to Popper 2.5.3 to address a fixed position bug in Firefox ## 2.0.0-beta.20 - 🚨 BREAKING: Transformed all Shoelace events to lowercase ([details](#why-did-event-names-change)) - Added support for dropdowns and non-icon elements to `<sl-input>` - Added `spellcheck` attribute to `<sl-input>` - Added `<sl-icon-library>` to allow custom icon library registration - Added `library` attribute to `<sl-icon>` and `<sl-icon-button>` - Added "Integrating with Rails" tutorial to the docs, courtesy of [ParamagicDev](https://github.com/ParamagicDev) - Fixed a bug where `<sl-progress-ring>` rendered incorrectly when zoomed in Safari [#227](https://github.com/shoelace-style/shoelace/issues/227>) - Fixed a bug where tabbing into slotted elements closes `<sl-dropdown>` when used in a shadow root [#223](https://github.com/shoelace-style/shoelace/issues/223) - Fixed a bug where scroll anchoring caused undesirable scrolling when `<sl-details>` are grouped ### Why did event names change? Shoelace events were updated to use a lowercase, kebab-style naming convention. Instead of event names such as `slChange` and `slAfterShow`, you'll need to use `sl-change` and `sl-after-show` now. This change was necessary to address a critical issue in frameworks that use DOM templates with declarative event bindings such as `<sl-button @slChange="handler">`. Due to HTML's case-insensitivity, browsers translate attribute names to lowercase, turning `@slChange` into `@slchange`, making it impossible to listen to `slChange`. While declarative event binding is a non-standard feature, not supporting it would make Shoelace much harder to use in popular frameworks. To accommodate those users and provide a better developer experience, we decided to change the naming convention while Shoelace is still in beta. The following pages demonstrate why this change was necessary. - [This Polymer FAQ from Custom Elements Everywhere](https://custom-elements-everywhere.com/#faq-polymer) - [Vue's Event Names documentation](https://vuejs.org/v2/guide/components-custom-events.html#Event-Names) ## 2.0.0-beta.19 - Added `input`, `label`, `prefix`, `clear-button`, `suffix`, `help-text` exported parts to `<sl-select>` to make the input customizable - Added toast notifications through the `toast()` method on `<sl-alert>` - Fixed a bug where mouse events would bubble up when `<sl-button>` was disabled, causing tooltips to erroneously appear - Fixed a bug where pressing space would open and immediately close `<sl-dropdown>` panels in Firefox - Fixed a bug where `<sl-tooltip>` would throw an error on init - Fixed a bug in custom keyframes animation example - Refactored clear logic in `<sl-input>` ## 2.0.0-beta.18 - Added `name` and `invalid` attribute to `<sl-color-picker>` - Added support for form submission and validation to `<sl-color-picker>` - Added touch support to demo resizers in the docs - Added `<sl-responsive-embed>` component - Fixed a bug where swapping an animated element wouldn't restart the animation in `<sl-animation>` - Fixed a bug where the cursor was incorrect when `<sl-select>` was disabled - Fixed a bug where `slblur` and `slfocus` were emitted twice in `<sl-select>` - Fixed a bug where clicking on `<sl-menu>` wouldn't focus it - Fixed a bug in the popover utility where `onAfterShow` would fire too soon - Fixed a bug where `bottom` and `right` placements didn't render properly in `<sl-tab-group>` - Improved keyboard logic in `<sl-dropdown>`, `<sl-menu>`, and `<sl-select>` - Updated `<sl-animation>` to stable - Updated to Stencil 2.0 (you may need to purge `node_modules` and run `npm install` after pulling) - Updated entry points in `package.json` to reflect new filenames generated by Stencil 2 ## 2.0.0-beta.17 - Added `minlength` and `spellcheck` attributes to `<sl-textarea>` - Fixed a bug where clicking a tag in `<sl-select>` wouldn't toggle the menu - Fixed a bug where options where `<sl-select>` options weren't always visible or scrollable - Fixed a bug where setting `null` on `<sl-input>`, `<sl-textarea>`, or `<sl-select>` would throw an error - Fixed a bug where `role` was on the wrong element and aria attribute weren't explicit in `<sl-checkbox>`, `<sl-switch>`, and `<sl-radio>` - Fixed a bug where dynamically adding/removing a slot wouldn't work as expected in `<sl-card>`, `<sl-dialog>`, and `<sl-drawer>` - Fixed a bug where the value wasn't updated and events weren't emitted when using `setRangeText` in `<sl-input>` and `<sl-textarea>` - Optimized `hasSlot` utility by using a simpler selector - Updated Bootstrap Icons to 1.0.0 with many icons redrawn and improved - Updated contribution guidelines **Form validation has been reworked and is much more powerful now!** - The `invalid` attribute now reflects the control's validity as determined by the browser's constraint validation API - Added `required` to `<sl-checkbox>`, `<sl-select>`, and `<sl-switch>` - Added `reportValidity()` and `setCustomValidity()` methods to all form controls - Added validation checking for custom and native form controls to `<sl-form>` - Added `novalidate` attribute to `<sl-form>` to disable validation - Removed the `valid` attribute from all form controls - Removed valid and invalid design tokens and related styles (you can use your own custom styles to achieve this) ## 2.0.0-beta.16 - Added `hoist` attribute to `<sl-color-picker>`, `<sl-dropdown>`, and `<sl-select>` to work around panel clipping - Added `<sl-format-bytes>` utility component - Added `clearable` and `required` props to `<sl-select>` - Added `slclear` event to `<sl-input>` - Added keyboard support to the preview resizer in the docs - Fixed a bug where the `aria-selected` state was incorrect in `<sl-menu-item>` - Fixed a bug where custom properties applied to `<sl-tooltip>` didn't affect show/hide transitions - Fixed a bug where `--sl-input-color-*` custom properties had no effect on `<sl-input>` and `<sl-textarea>` - Refactored `<sl-dropdown>` and `<sl-tooltip>` to use positioner elements so panels/tooltips can be customized easier ## 2.0.0-beta.15 - Added `image-comparer` component - Added `--width`, `--height`, and `--thumb-size` custom props to `<sl-switch>` - Fixed an `aria-labelledby` attribute typo in a number of components - Fixed a bug where the `change` event wasn't updating the value in `<sl-input>` - Fixed a bug where `<sl-color-picker>` had the wrong border color in the dark theme - Fixed a bug where `<sl-menu-item>` had the wrong color in dark mode when disabled - Fixed a bug where WebKit's autocomplete styles made inputs looks broken - Fixed a bug where aria labels were wrong in `<sl-select>` - Fixed a bug where clicking the label wouldn't focus the control in `<sl-select>` ## 2.0.0-beta.14 - Added dark theme - Added `--sl-panel-background-color` and `--sl-panel-border-color` tokens - Added `--tabs-border-color` custom property to `<sl-tab-group>` - Added `--track-color` custom property to `<sl-range>` - Added `tag` part to `<sl-select>` - Updated `package.json` so custom elements imports can be consumed from the root - Fixed a bug where scrolling dialogs didn't resize properly in Safari - Fixed a bug where `slshow` and `slhide` would be emitted twice in some components - Fixed a bug where `custom-elements/index.d.ts` was broken due to an unclosed comment (fixed in Stencil 1.17.3) - Fixed bug where inputs were not using border radius tokens - Fixed a bug where the text color was being erroneously set in `<sl-progress-ring>` - Fixed a bug where `<sl-progress-bar>` used the wrong part name internally for `indicator` - Removed background color from `<sl-menu>` - Updated to Stencil 1.17.3 ## 2.0.0-beta.13 - Added `slactivate` and `sldeactivate` events to `<sl-menu-item>` - Added experimental `<sl-animation>` component - Added shields to documentation - Fixed a bug where link buttons would have `type="button"` - Fixed a bug where button groups with tooltips experienced an odd spacing issue in Safari - Fixed a bug where scrolling in dropdowns/selects didn't work properly on Windows (special thanks to [Trendy](http://github.com/trendy) for helping troubleshoot!) - Fixed a bug where selecting a menu item in a dropdown would cause Safari to scroll - Fixed a bug where type to select wouldn't accept symbols - Moved scrolling logic from `<sl-menu>` to `<sl-dropdown>` ## 2.0.0-beta.12 - Added support for `href`, `target`, and `download` to buttons - Fixed a bug where buttons would have horizontal spacing in Safari - Fixed a bug that caused an import resolution error when using Shoelace in a Stencil app ## 2.0.0-beta.11 - Added button group component - Fixed icon button alignment - Fixed a bug where focus visible observer wasn't removed from `<sl-details>` - Replaced the deprecated `componentDidUnload` lifecycle method with `disconnectedCallback` to prevent issues with frameworks ## 2.0.0-beta.10 - Added community page to the docs - Fixed a bug where many components would erroneously receive an `id` when using the custom elements bundle - Fixed a bug where tab groups weren't scrollable with the mouse ## 2.0.0-beta.9 - Added the icon button component - Added the skeleton component - Added the `typeToSelect` method to menu so type-to-select behavior can be controlled externally - Added the `pulse` attribute to badge - Fixed a bug where hovering over select showed the wrong cursor - Fixed a bug where tabbing into a select control would highlight the label - Fixed a bug where tabbing out of a select control wouldn't close it - Fixed a bug where closing dropdowns wouldn't give focus back to the trigger - Fixed a bug where type-to-select wasn't working after the first letter - Fixed a bug where clicking on menu items and dividers would steal focus from the menu - Fixed a bug where the color picker wouldn't parse uppercase values - Removed the `no-footer` attribute from dialog and drawer (slot detection is automatic, so the attribute is not required) - Removed `close-icon` slot from alert - Replaced make-shift icon buttons with `<sl-icon-button>` in alert, dialog, drawer, and tag - Updated Stencil to 1.17.1 - Switched to jsDelivr for better CDN performance ## 2.0.0-beta.8 - Added the card component - Added `--focus-ring` custom property to tab - Fixed a bug where range tooltips didn't appear on iOS - Fixed constructor bindings so they don't break the custom elements bundle - Fixed tag color contrast to be AA compliant - Fixed a bug that made it difficult to vertically align rating - Fixed a bug where dropdowns would always close on mousedown when inside a shadow root - Made tag text colors AA compliant - Promoted badge to stable - Refactored `:host` variables and moved non-display props to base elements - Refactored event handler bindings to occur in `connectedCallback` instead of the constructor - Refactored scroll locking logic to use `Set` instead of an array - Updated the custom elements bundle documentation and added bundler examples - Upgraded Stencil to 1.17.0-0 (next) to fix custom elements bundle ## 2.0.0-beta.7 - Added links to version 1 resources to the docs - Added rating component - Fixed a bug where some build files were missing - Fixed clearable tags demo - Fixed touch icon size in docs ## 2.0.0-beta.6 - Enabled the `dist-custom-elements-bundle` output target - Fixed a bug where nested form controls were ignored in `<sl-form>` ## 2.0.0-beta.5 - Fixed bug where `npm install` would fail due to postinstall script - Removed unused dependency ## 2.0.0-beta.4 - Added `pill` variation to badges - Fixed a bug where all badges had `pointer-events: none` - Fixed `@since` props to show 2.0 instead of 1.0 - Fixed giant cursors in inputs in Safari - Fixed color picker input width in Safari - Fixed initial transitions for drawer, dialog, and popover consumers - Fixed a bug where dialog, dropdown, and drawer would sometimes not transition in on the first open - Fixed various documentation typos ## 2.0.0-beta.3 - Fix version in docs - Remove custom elements bundle ## 2.0.0-beta.2 - Fix quick start and installation URLs - Switch Docsify theme - Update line heights tokens ## 2.0.0-beta.1 - Initial release
{ "content_hash": "80ca32d4b010025dca38e48272eda077", "timestamp": "", "source": "github", "line_count": 1043, "max_line_length": 696, "avg_line_length": 77.25790987535954, "alnum_prop": 0.7505832712831968, "repo_name": "claviska/shoelace-css", "id": "1ab113c0b8b687bb89004abd1749956c2384fa7e", "size": "80784", "binary": false, "copies": "1", "ref": "refs/heads/next", "path": "docs/resources/changelog.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "108964" }, { "name": "HTML", "bytes": "8830" }, { "name": "JavaScript", "bytes": "15288" } ], "symlink_target": "" }
.. currentmodule:: machine class Timer -- control hardware timers ====================================== Hardware timers deal with timing of periods and events. Timers are perhaps the most flexible and heterogeneous kind of hardware in MCUs and SoCs, differently greatly from a model to a model. MicroPython's Timer class defines a baseline operation of executing a callback with a given period (or once after some delay), and allow specific boards to define more non-standard behavior (which thus won't be portable to other boards). See discussion of :ref:`important constraints <machine_callbacks>` on Timer callbacks. .. note:: Memory can't be allocated inside irq handlers (an interrupt) and so exceptions raised within a handler don't give much information. See :func:`micropython.alloc_emergency_exception_buf` for how to get around this limitation. Constructors ------------ .. class:: Timer(id, ...) Construct a new timer object of the given id. Id of -1 constructs a virtual timer (if supported by a board). Methods ------- .. only:: port_wipy .. method:: Timer.init(mode, \*, width=16) Initialise the timer. Example:: tim.init(Timer.PERIODIC) # periodic 16-bit timer tim.init(Timer.ONE_SHOT, width=32) # one shot 32-bit timer Keyword arguments: - ``mode`` can be one of: - ``Timer.ONE_SHOT`` - The timer runs once until the configured period of the channel expires. - ``Timer.PERIODIC`` - The timer runs periodically at the configured frequency of the channel. - ``Timer.PWM`` - Output a PWM signal on a pin. - ``width`` must be either 16 or 32 (bits). For really low frequencies < 5Hz (or large periods), 32-bit timers should be used. 32-bit mode is only available for ``ONE_SHOT`` AND ``PERIODIC`` modes. .. method:: Timer.deinit() Deinitialises the timer. Stops the timer, and disables the timer peripheral. .. only:: port_wipy .. method:: Timer.channel(channel, \**, freq, period, polarity=Timer.POSITIVE, duty_cycle=0) If only a channel identifier passed, then a previously initialized channel object is returned (or ``None`` if there is no previous channel). Otherwise, a TimerChannel object is initialized and returned. The operating mode is is the one configured to the Timer object that was used to create the channel. - ``channel`` if the width of the timer is 16-bit, then must be either ``TIMER.A``, ``TIMER.B``. If the width is 32-bit then it **must be** ``TIMER.A | TIMER.B``. Keyword only arguments: - ``freq`` sets the frequency in Hz. - ``period`` sets the period in microseconds. .. note:: Either ``freq`` or ``period`` must be given, never both. - ``polarity`` this is applicable for ``PWM``, and defines the polarity of the duty cycle - ``duty_cycle`` only applicable to ``PWM``. It's a percentage (0.00-100.00). Since the WiPy doesn't support floating point numbers the duty cycle must be specified in the range 0-10000, where 10000 would represent 100.00, 5050 represents 50.50, and so on. .. note:: When the channel is in PWM mode, the corresponding pin is assigned automatically, therefore there's no need to assign the alternate function of the pin via the ``Pin`` class. The pins which support PWM functionality are the following: - ``GP24`` on Timer 0 channel A. - ``GP25`` on Timer 1 channel A. - ``GP9`` on Timer 2 channel B. - ``GP10`` on Timer 3 channel A. - ``GP11`` on Timer 3 channel B. .. only:: port_wipy class TimerChannel --- setup a channel for a timer ================================================== Timer channels are used to generate/capture a signal using a timer. TimerChannel objects are created using the Timer.channel() method. Methods ------- .. method:: timerchannel.irq(\*, trigger, priority=1, handler=None) The behavior of this callback is heavily dependent on the operating mode of the timer channel: - If mode is ``Timer.PERIODIC`` the callback is executed periodically with the configured frequency or period. - If mode is ``Timer.ONE_SHOT`` the callback is executed once when the configured timer expires. - If mode is ``Timer.PWM`` the callback is executed when reaching the duty cycle value. The accepted params are: - ``priority`` level of the interrupt. Can take values in the range 1-7. Higher values represent higher priorities. - ``handler`` is an optional function to be called when the interrupt is triggered. - ``trigger`` must be ``Timer.TIMEOUT`` when the operating mode is either ``Timer.PERIODIC`` or ``Timer.ONE_SHOT``. In the case that mode is ``Timer.PWM`` then trigger must be equal to ``Timer.MATCH``. Returns a callback object. .. only:: port_wipy .. method:: timerchannel.freq([value]) Get or set the timer channel frequency (in Hz). .. method:: timerchannel.period([value]) Get or set the timer channel period (in microseconds). .. method:: timerchannel.duty_cycle([value]) Get or set the duty cycle of the PWM signal. It's a percentage (0.00-100.00). Since the WiPy doesn't support floating point numbers the duty cycle must be specified in the range 0-10000, where 10000 would represent 100.00, 5050 represents 50.50, and so on. Constants --------- .. data:: Timer.ONE_SHOT .. data:: Timer.PERIODIC Timer operating mode.
{ "content_hash": "257428e8b05e31070a5f2a7dccce0a6e", "timestamp": "", "source": "github", "line_count": 159, "max_line_length": 107, "avg_line_length": 36.9622641509434, "alnum_prop": 0.6336566275310532, "repo_name": "mhoffma/micropython", "id": "eddb2ce78014be5a21bf55cda3be934637d8aadd", "size": "5877", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "docs/library/machine.Timer.rst", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "55392" }, { "name": "C", "bytes": "34522526" }, { "name": "C++", "bytes": "1017455" }, { "name": "HTML", "bytes": "84456" }, { "name": "Makefile", "bytes": "77733" }, { "name": "Objective-C", "bytes": "391937" }, { "name": "Python", "bytes": "626212" }, { "name": "Shell", "bytes": "4829" } ], "symlink_target": "" }
"""Information about mxnet.""" from __future__ import absolute_import import os import platform import logging def find_lib_path(): """Find MXNet dynamic library files. Returns ------- lib_path : list(string) List of all found path to the libraries. """ lib_from_env = os.environ.get('MXNET_LIBRARY_PATH') if lib_from_env: if os.path.isfile(lib_from_env): if not os.path.isabs(lib_from_env): logging.warning("MXNET_LIBRARY_PATH should be an absolute path, instead of: %s", lib_from_env) else: if os.name == 'nt': os.environ['PATH'] = os.environ['PATH'] + ';' + os.path.dirname(lib_from_env) return [lib_from_env] else: logging.warning("MXNET_LIBRARY_PATH '%s' doesn't exist", lib_from_env) curr_path = os.path.dirname(os.path.abspath(os.path.expanduser(__file__))) api_path = os.path.join(curr_path, '../../lib/') cmake_build_path = os.path.join(curr_path, '../../build/') dll_path = [curr_path, api_path, cmake_build_path] if os.name == 'nt': dll_path.append(os.path.join(curr_path, '../../build')) vs_configuration = 'Release' if platform.architecture()[0] == '64bit': dll_path.append(os.path.join(curr_path, '../../build', vs_configuration)) dll_path.append(os.path.join(curr_path, '../../windows/x64', vs_configuration)) else: dll_path.append(os.path.join(curr_path, '../../build', vs_configuration)) dll_path.append(os.path.join(curr_path, '../../windows', vs_configuration)) elif os.name == "posix" and os.environ.get('LD_LIBRARY_PATH', None): dll_path[0:0] = [p.strip() for p in os.environ['LD_LIBRARY_PATH'].split(":")] if os.name == 'nt': os.environ['PATH'] = os.path.dirname(__file__) + ';' + os.environ['PATH'] dll_path = [os.path.join(p, 'libmxnet.dll') for p in dll_path] elif platform.system() == 'Darwin': dll_path = [os.path.join(p, 'libmxnet.dylib') for p in dll_path] + \ [os.path.join(p, 'libmxnet.so') for p in dll_path] else: dll_path.append('../../../') dll_path = [os.path.join(p, 'libmxnet.so') for p in dll_path] lib_path = [p for p in dll_path if os.path.exists(p) and os.path.isfile(p)] if len(lib_path) == 0: raise RuntimeError('Cannot find the MXNet library.\n' + 'List of candidates:\n' + str('\n'.join(dll_path))) if os.name == 'nt': os.environ['PATH'] = os.environ['PATH'] + ';' + os.path.dirname(lib_path[0]) return lib_path # current version __version__ = "1.3.1"
{ "content_hash": "8bf6787fef71490ea03a884300c95cf6", "timestamp": "", "source": "github", "line_count": 63, "max_line_length": 97, "avg_line_length": 43.3968253968254, "alnum_prop": 0.563643013899049, "repo_name": "mbaijal/incubator-mxnet", "id": "b4450510a4c4dfc94d1b2401029ba93b44569037", "size": "3536", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "python/mxnet/libinfo.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "1731" }, { "name": "Batchfile", "bytes": "13130" }, { "name": "C", "bytes": "173224" }, { "name": "C++", "bytes": "6116511" }, { "name": "CMake", "bytes": "86446" }, { "name": "Clojure", "bytes": "389028" }, { "name": "Cuda", "bytes": "813783" }, { "name": "Dockerfile", "bytes": "43395" }, { "name": "Groovy", "bytes": "22850" }, { "name": "Java", "bytes": "128595" }, { "name": "Julia", "bytes": "408765" }, { "name": "Jupyter Notebook", "bytes": "1657933" }, { "name": "MATLAB", "bytes": "34903" }, { "name": "Makefile", "bytes": "70735" }, { "name": "Perl", "bytes": "1535873" }, { "name": "Perl 6", "bytes": "7280" }, { "name": "PowerShell", "bytes": "6150" }, { "name": "Python", "bytes": "6206547" }, { "name": "R", "bytes": "351354" }, { "name": "Scala", "bytes": "1102749" }, { "name": "Shell", "bytes": "305673" }, { "name": "Smalltalk", "bytes": "43774" } ], "symlink_target": "" }
<?php /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */ /** * Random Number Generator * * PHP versions 4 and 5 * * Here's a short example of how to use this library: * <code> * <?php * include('Crypt/Random.php'); * * echo crypt_random(); * ?> * </code> * * LICENSE: This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * @category Crypt * @package Crypt_Random * @author Jim Wigginton <terrafrost@php.net> * @copyright MMVII Jim Wigginton * @license http://www.gnu.org/licenses/lgpl.txt * @version $Id: Random.php,v 1.9 2010/04/24 06:40:48 terrafrost Exp $ * @link http://phpseclib.sourceforge.net */ /** * Generate a random value. * * On 32-bit machines, the largest distance that can exist between $min and $max is 2**31. * If $min and $max are farther apart than that then the last ($max - range) numbers. * * Depending on how this is being used, it may be worth while to write a replacement. For example, * a PHP-based web app that stores its data in an SQL database can collect more entropy than this function * can. * * @param optional Integer $min * @param optional Integer $max * @return Integer * @access public */ function crypt_random($min = 0, $max = 0x7FFFFFFF) { if ($min == $max) { return $min; } // see http://en.wikipedia.org/wiki//dev/random // if open_basedir is enabled file_exists() will ouput an "open_basedir restriction in effect" warning, // so we suppress it. if (@file_exists('/dev/urandom')) { static $fp; if (!$fp) { $fp = fopen('/dev/urandom', 'rb'); } extract(unpack('Nrandom', fread($fp, 4))); // say $min = 0 and $max = 3. if we didn't do abs() then we could have stuff like this: // -4 % 3 + 0 = -1, even though -1 < $min return abs($random) % ($max - $min) + $min; } /* Prior to PHP 4.2.0, mt_srand() had to be called before mt_rand() could be called. Prior to PHP 5.2.6, mt_rand()'s automatic seeding was subpar, as elaborated here: http://www.suspekt.org/2008/08/17/mt_srand-and-not-so-random-numbers/ The seeding routine is pretty much ripped from PHP's own internal GENERATE_SEED() macro: http://svn.php.net/viewvc/php/php-src/branches/PHP_5_3_2/ext/standard/php_rand.h?view=markup */ if (version_compare(PHP_VERSION, '5.2.5', '<=')) { static $seeded; if (!isset($seeded)) { $seeded = true; mt_srand(fmod(time() * getmypid(), 0x7FFFFFFF) ^ fmod(1000000 * lcg_value(), 0x7FFFFFFF)); } } static $crypto; // The CSPRNG's Yarrow and Fortuna periodically reseed. This function can be reseeded by hitting F5 // in the browser and reloading the page. if (!isset($crypto)) { $key = $iv = ''; for ($i = 0; $i < 8; $i++) { $key.= pack('n', mt_rand(0, 0xFFFF)); $iv .= pack('n', mt_rand(0, 0xFFFF)); } switch (true) { case class_exists('Crypt_AES'): $crypto = new Crypt_AES(CRYPT_AES_MODE_CTR); break; case class_exists('Crypt_TripleDES'): $crypto = new Crypt_TripleDES(CRYPT_DES_MODE_CTR); break; case class_exists('Crypt_DES'): $crypto = new Crypt_DES(CRYPT_DES_MODE_CTR); break; case class_exists('Crypt_RC4'): $crypto = new Crypt_RC4(); break; default: extract(unpack('Nrandom', pack('H*', sha1(mt_rand(0, 0x7FFFFFFF))))); return abs($random) % ($max - $min) + $min; } $crypto->setKey($key); $crypto->setIV($iv); $crypto->enableContinuousBuffer(); } extract(unpack('Nrandom', $crypto->encrypt("\0\0\0\0"))); return abs($random) % ($max - $min) + $min; } ?>
{ "content_hash": "6b79009c288d2a735d12ba6d1c4e7697", "timestamp": "", "source": "github", "line_count": 130, "max_line_length": 107, "avg_line_length": 35.353846153846156, "alnum_prop": 0.5985639686684073, "repo_name": "Numerico-Informatic-Systems-Pvt-Ltd/gsmpoly", "id": "221cba53375639cc45369989a535775cf1f7af2a", "size": "4596", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "app/webroot/payment/Sfa/phpseclib/Crypt/Random.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "1111" }, { "name": "Batchfile", "bytes": "2888" }, { "name": "CSS", "bytes": "104301" }, { "name": "HTML", "bytes": "4567" }, { "name": "JavaScript", "bytes": "28277" }, { "name": "PHP", "bytes": "15497518" }, { "name": "Shell", "bytes": "4170" } ], "symlink_target": "" }
using System; using System.Data.SqlClient; using Graphite.DependencyInjection; using Graphite.Reflection; using NUnit.Framework; using Should; namespace Tests.Unit.DependencyInjection { [TestFixture] public class RegistryTests { [Test] public void Should_generate_friendly_string_displaying_registrations() { var result = new Registry(new TypeCache()) .Register<IDisposable>(typeof(SqlConnection)) .Register(new object()) .ToString(); result.ShouldEqual( "Plugin Type······· Plugin Assembly· Singleton Instance Concrete Type······················ Concrete Assembly··\r\n" + "System.IDisposable mscorlib 4.0.0.0 False System.Data.SqlClient.SqlConnection System.Data 4.0.0.0\r\n" + "object············ mscorlib 4.0.0.0 False···· object·· object····························· mscorlib 4.0.0.0···"); } } }
{ "content_hash": "876873de08d547b50b1ac5f6ae3c4859", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 134, "avg_line_length": 37.48148148148148, "alnum_prop": 0.5622529644268774, "repo_name": "mikeobrien/graphite", "id": "0c2398929d97ab3a42ecafbef82bec8114824a94", "size": "1096", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Tests/Unit/DependencyInjection/RegistryTests.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "102" }, { "name": "C#", "bytes": "1680458" }, { "name": "CSS", "bytes": "3042" }, { "name": "HTML", "bytes": "27041" }, { "name": "JavaScript", "bytes": "5212" } ], "symlink_target": "" }
namespace swift { class SourceLoc; class ReturnStmt; class BraceStmt; class AbstractClosureExpr; class AbstractFunctionDecl; /// This is a pointer to the AST node that a SIL instruction was /// derived from. This may be null if AST information is unavailable or /// stripped. /// /// FIXME: This should eventually include inlining history, generics /// instantiation info, etc (when we get to it). /// class SILLocation { private: template <class T, class Enable = void> struct base_type; template <class T> struct base_type<T, typename std::enable_if<std::is_base_of<Decl, T>::value>::type> { using type = Decl; }; template <class T> struct base_type<T, typename std::enable_if<std::is_base_of<Expr, T>::value>::type> { using type = Expr; }; template <class T> struct base_type<T, typename std::enable_if<std::is_base_of<Stmt, T>::value>::type> { using type = Stmt; }; template <class T> struct base_type<T, typename std::enable_if<std::is_base_of<Pattern, T>::value>::type> { using type = Pattern; }; using ASTNodeTy = llvm::PointerUnion4<Stmt *, Expr *, Decl *, Pattern *>; public: enum LocationKind : unsigned { RegularKind = 1, ReturnKind = 2, ImplicitReturnKind = 3, InlinedKind = 4, MandatoryInlinedKind = 5, CleanupKind = 6, ArtificialUnreachableKind = 7 }; enum StorageKind : unsigned { UnknownKind = 0, ASTNodeKind = 1 << 3, SILFileKind = 1 << 4, DebugInfoKind = 1 << 3 | 1 << 4 }; struct DebugLoc { unsigned Line; unsigned Column; StringRef Filename; DebugLoc(unsigned Line = 0, unsigned Column = 0, StringRef Filename = StringRef()) : Line(Line), Column(Column), Filename(Filename) {} inline bool operator==(const DebugLoc &R) const { return Line == R.Line && Column == R.Column && Filename.equals(R.Filename); } }; protected: union UnderlyingLocation { UnderlyingLocation() : DebugInfoLoc({}) {} UnderlyingLocation(ASTNodeTy N) : ASTNode(N) {} UnderlyingLocation(SourceLoc L) : SILFileLoc(L) {} UnderlyingLocation(DebugLoc D) : DebugInfoLoc({D.Filename.data(), D.Line, D.Column}) {} struct ASTNodeLoc { ASTNodeLoc(ASTNodeTy N) : Primary(N) {} /// Primary AST location, always used for diagnostics. ASTNodeTy Primary; /// Sometimes the location for diagnostics needs to be /// different than the one used to emit the line table. If /// HasDebugLoc is set, this is used for the debug info. ASTNodeTy ForDebugger; } ASTNode; /// A location inside a textual .sil file. SourceLoc SILFileLoc; /// A deserialized source location. /// /// This represents \e most of the information in a SILLocation::DebugLoc, /// but for bit-packing purposes the length of the filename is stored in /// the SILLocation's ExtraStorageData instead of here. /// /// \sa SILLocation::getDebugInfoLoc struct CompactDebugLoc { const char *FilenameData; unsigned Line; unsigned Column; } DebugInfoLoc; } Loc; /// The kind of this SIL location. unsigned KindData; /// Extra data that's not in UnderlyingLocation to keep the size of /// SILLocation down. unsigned ExtraStorageData = 0; enum { LocationKindBits = 3, LocationKindMask = 7, StorageKindBits = 2, StorageKindMask = (1 << 3) | (1 << 4), SpecialFlagsMask = ~ (LocationKindMask | StorageKindMask), /// Used to mark this instruction as part of auto-generated /// code block. AutoGeneratedBit = 5, /// Used to redefine the default source location used to /// represent this SILLocation. For example, when the host instruction /// is known to correspond to the beginning or the end of the source /// range of the ASTNode. PointsToStartBit = 6, PointsToEndBit = 7, /// Used to notify that this instruction belongs to the top- /// level (module) scope. /// /// FIXME: If Module becomes a Decl, this could be removed. IsInTopLevel = 8, /// Marks this instruction as belonging to the function prologue. IsInPrologue = 9 }; template <typename T> T *getNodeAs(ASTNodeTy Node) const { using base = typename base_type<T>::type*; return dyn_cast_or_null<T>(Node.dyn_cast<base>()); } template <typename T> bool isNode(ASTNodeTy Node) const { assert(isASTNode()); if (Loc.ASTNode.Primary.is<typename base_type<T>::type*>()) return isa<T>(Node.get<typename base_type<T>::type*>()); return false; } template <typename T> T *castNodeTo(ASTNodeTy Node) const { return cast<T>(Node.get<typename base_type<T>::type*>()); } /// \defgroup SILLocation constructors. /// @{ /// This constructor is used to support getAs operation. SILLocation() { assert(Loc.DebugInfoLoc.Line == 0); } SILLocation(LocationKind K, unsigned Flags = 0) : KindData(K | Flags) { assert(Loc.DebugInfoLoc.Line == 0); } SILLocation(Stmt *S, LocationKind K, unsigned Flags = 0) : Loc(S), KindData(K | Flags) { setStorageKind(ASTNodeKind); assert(isASTNode()); } SILLocation(Expr *E, LocationKind K, unsigned Flags = 0) : Loc(E), KindData(K | Flags) { setStorageKind(ASTNodeKind); assert(isASTNode()); } SILLocation(Decl *D, LocationKind K, unsigned Flags = 0) : Loc(D), KindData(K | Flags) { setStorageKind(ASTNodeKind); assert(isASTNode()); } SILLocation(Pattern *P, LocationKind K, unsigned Flags = 0) : Loc(P), KindData(K | Flags) { setStorageKind(ASTNodeKind); assert(isASTNode()); } SILLocation(SourceLoc L, LocationKind K, unsigned Flags = 0) : Loc(L), KindData(K | Flags) { setStorageKind(SILFileKind); assert(isSILFile()); } SILLocation(DebugLoc L, LocationKind K, unsigned Flags = 0) : KindData(K | Flags) { setDebugInfoLoc(L); } /// @} private: friend class ImplicitReturnLocation; friend class MandatoryInlinedLocation; friend class InlinedLocation; friend class CleanupLocation; void setLocationKind(LocationKind K) { KindData |= (K & LocationKindMask); } void setStorageKind(StorageKind K) { KindData |= (K & StorageKindMask); } unsigned getSpecialFlags() const { return KindData & SpecialFlagsMask; } void setSpecialFlags(unsigned Flags) { KindData |= (Flags & SpecialFlagsMask); } SourceLoc getSourceLoc(ASTNodeTy N) const; SourceLoc getStartSourceLoc(ASTNodeTy N) const; SourceLoc getEndSourceLoc(ASTNodeTy N) const; public: /// When an ASTNode gets implicitly converted into a SILLocation we /// construct a RegularLocation. Since RegularLocations represent the majority /// of locations, this greatly simplifies the user code. SILLocation(Stmt *S) : Loc(S), KindData(RegularKind) { setStorageKind(ASTNodeKind); assert(isASTNode()); } SILLocation(Expr *E) : Loc(E), KindData(RegularKind) { setStorageKind(ASTNodeKind); assert(isASTNode()); } SILLocation(Decl *D) : Loc(D), KindData(RegularKind) { setStorageKind(ASTNodeKind); assert(isASTNode()); } SILLocation(Pattern *P) : Loc(P), KindData(RegularKind) { setStorageKind(ASTNodeKind); assert(isASTNode()); } static SILLocation invalid() { return SILLocation(); } /// Check if the location wraps an AST node or a valid SIL file /// location. /// /// Artificial locations and the top-level module locations will be null. bool isNull() const { switch (getStorageKind()) { case ASTNodeKind: return Loc.ASTNode.Primary.isNull(); case DebugInfoKind: return ExtraStorageData == 0; case SILFileKind: return Loc.SILFileLoc.isInvalid(); default: return true; } } explicit operator bool() const { return !isNull(); } /// Return whether this location is backed by an AST node. bool isASTNode() const { return getStorageKind() == ASTNodeKind; } /// Return whether this location came from a SIL file. bool isSILFile() const { return getStorageKind() == SILFileKind; } /// Return whether this location came from a textual SIL file. bool isDebugInfoLoc() const { return getStorageKind() == DebugInfoKind; } /// Marks the location as coming from auto-generated body. void markAutoGenerated() { KindData |= (1 << AutoGeneratedBit); } /// Returns true if the location represents an artificially generated /// body, such as thunks or default destructors. /// /// These locations should not be included in the debug line table. /// These might also need special handling by the debugger since they might /// contain calls, which the debugger could be able to step into. bool isAutoGenerated() const { return KindData & (1 << AutoGeneratedBit); } /// Returns true if the line number of this location is zero. bool isLineZero(const SourceManager &SM) const { return decodeDebugLoc(SM).Line == 0; } /// Changes the default source location position to point to start of /// the AST node. void pointToStart() { KindData |= (1 << PointsToStartBit); } /// Changes the default source location position to point to the end of /// the AST node. void pointToEnd() { KindData |= (1 << PointsToEndBit); } /// Mark this location as the location corresponding to the top-level /// (module-level) code. void markAsInTopLevel() { KindData |= (1 << IsInTopLevel); } /// Check is this location is associated with the top level/module. bool isInTopLevel() const { return KindData & (1 << IsInTopLevel); } /// Mark this location as being part of the function /// prologue, which means that it deals with setting up the stack /// frame. The first breakpoint location in a function is at the end /// of the prologue. void markAsPrologue() { KindData |= (1 << IsInPrologue); } /// Check is this location is part of a function's implicit prologue. bool isInPrologue() const { return KindData & (1 << IsInPrologue); } /// Add an ASTNode to use as the location for debugging /// purposes if this location is different from the location used /// for diagnostics. template <typename T> void setDebugLoc(T *ASTNodeForDebugging) { assert(!hasDebugLoc() && "DebugLoc already present"); assert(isASTNode() && "not an AST location"); Loc.ASTNode.ForDebugger = ASTNodeForDebugging; } bool hasDebugLoc() const { return isASTNode() && !Loc.ASTNode.ForDebugger.isNull(); } /// Populate this empty SILLocation with a DebugLoc. void setDebugInfoLoc(DebugLoc L) { ExtraStorageData = L.Filename.size(); assert(ExtraStorageData == L.Filename.size() && "file name is longer than 32 bits"); Loc = L; setStorageKind(DebugInfoKind); } /// Check if the corresponding source code location definitely points /// to the start of the AST node. bool alwaysPointsToStart() const { return KindData & (1 << PointsToStartBit);} /// Check if the corresponding source code location definitely points /// to the end of the AST node. bool alwaysPointsToEnd() const { return KindData & (1 << PointsToEndBit); } LocationKind getKind() const { return LocationKind(KindData & LocationKindMask); } StorageKind getStorageKind() const { return StorageKind(KindData & StorageKindMask); } template <typename T> bool is() const { return T::isKind(*this); } template <typename T> T castTo() const { assert(T::isKind(*this)); T t; SILLocation& tr = t; tr = *this; return t; } template <typename T> Optional<T> getAs() const { if (!T::isKind(*this)) return Optional<T>(); T t; SILLocation& tr = t; tr = *this; return t; } /// If the current value is of the specified AST unit type T, /// return it, otherwise return null. template <typename T> T *getAsASTNode() const { return isASTNode() ? getNodeAs<T>(Loc.ASTNode.Primary) : nullptr; } /// Returns true if the Location currently points to the AST node /// matching type T. template <typename T> bool isASTNode() const { return isASTNode() && isNode<T>(Loc.ASTNode.Primary); } /// Returns the primary value as the specified AST node type. If the /// specified type is incorrect, asserts. template <typename T> T *castToASTNode() const { assert(isASTNode()); return castNodeTo<T>(Loc.ASTNode.Primary); } /// If the DebugLoc is of the specified AST unit type T, /// return it, otherwise return null. template <typename T> T *getDebugLocAsASTNode() const { assert(hasDebugLoc() && "no debug location"); return getNodeAs<T>(Loc.ASTNode.ForDebugger); } /// Return the location as a DeclContext or null. DeclContext *getAsDeclContext() const; /// Convert a specialized location kind into a regular location. SILLocation getAsRegularLocation() { SILLocation RegularLoc = *this; RegularLoc.setLocationKind(RegularKind); return RegularLoc; } SourceLoc getDebugSourceLoc() const; SourceLoc getSourceLoc() const; SourceLoc getStartSourceLoc() const; SourceLoc getEndSourceLoc() const; SourceRange getSourceRange() const { return {getStartSourceLoc(), getEndSourceLoc()}; } DebugLoc getDebugInfoLoc() const { assert(isDebugInfoLoc()); return DebugLoc(Loc.DebugInfoLoc.Line, Loc.DebugInfoLoc.Column, StringRef(Loc.DebugInfoLoc.FilenameData, ExtraStorageData)); } /// Fingerprint a DebugLoc for use in a DenseMap. using DebugLocKey = std::pair<std::pair<unsigned, unsigned>, StringRef>; struct DebugLocHash : public DebugLocKey { DebugLocHash(DebugLoc L) : DebugLocKey({{L.Line, L.Column}, L.Filename}) {} }; /// Extract the line, column, and filename. static DebugLoc decode(SourceLoc Loc, const SourceManager &SM); /// Return the decoded debug location. LLVM_NODISCARD DebugLoc decodeDebugLoc(const SourceManager &SM) const { return isDebugInfoLoc() ? getDebugInfoLoc() : decode(getDebugSourceLoc(), SM); } /// Compiler-generated locations may be applied to instructions without any /// clear correspondence to an AST node in an otherwise normal function. static DebugLoc getCompilerGeneratedDebugLoc() { return {0, 0, "<compiler-generated>"}; } /// Pretty-print the value. void dump(const SourceManager &SM) const; void print(raw_ostream &OS, const SourceManager &SM) const; /// Returns an opaque pointer value for the debug location that may /// be used to unique debug locations. const void *getOpaquePointerValue() const { if (isSILFile()) return Loc.SILFileLoc.getOpaquePointerValue(); if (isASTNode()) return Loc.ASTNode.Primary.getOpaqueValue(); else return 0; } unsigned getOpaqueKind() const { return KindData; } inline bool operator==(const SILLocation& R) const { return KindData == R.KindData && Loc.ASTNode.Primary.getOpaqueValue() == R.Loc.ASTNode.Primary.getOpaqueValue() && Loc.ASTNode.ForDebugger.getOpaqueValue() == R.Loc.ASTNode.ForDebugger.getOpaqueValue(); } inline bool operator!=(const SILLocation &R) const { return !(*this == R); } }; /// Allowed on any instruction. class RegularLocation : public SILLocation { public: RegularLocation(Stmt *S) : SILLocation(S, RegularKind) {} RegularLocation(Expr *E) : SILLocation(E, RegularKind) {} RegularLocation(Decl *D) : SILLocation(D, RegularKind) {} RegularLocation(Pattern *P) : SILLocation(P, RegularKind) {} RegularLocation(SourceLoc L) : SILLocation(L, RegularKind) {} RegularLocation(DebugLoc L) : SILLocation(L, RegularKind) {} /// Returns a location representing the module. static RegularLocation getModuleLocation() { RegularLocation Loc; Loc.markAsInTopLevel(); return Loc; } /// If the current value is of the specified AST unit type T, /// return it, otherwise return null. template <typename T> T *getAs() const { return getNodeAs<T>(Loc.ASTNode); } /// Returns true if the Location currently points to the AST node /// matching type T. template <typename T> bool is() const { return isNode<T>(Loc.ASTNode); } /// Returns the primary value as the specified AST node type. If the /// specified type is incorrect, asserts. template <typename T> T *castTo() const { return castNodeTo<T>(Loc.ASTNode); } /// Compiler-generated locations may be applied to instructions without any /// clear correspondence to an AST node in an otherwise normal function. /// The auto-generated bit also turns off certain diagnostics passes such. static RegularLocation getAutoGeneratedLocation() { RegularLocation AL(getCompilerGeneratedDebugLoc()); AL.markAutoGenerated(); return AL; } /// Returns a location that is compiler-generated, but with a hint as to where /// it may have been generated from. These locations will have an artificial /// line location of zero in DWARF, but in CodeView we want to use the given /// line since line zero does not represent an artificial line in CodeView. static RegularLocation getAutoGeneratedLocation(SourceLoc L) { RegularLocation AL(L); AL.markAutoGenerated(); return AL; } private: RegularLocation() : SILLocation(RegularKind) {} friend class SILLocation; static bool isKind(const SILLocation& L) { return L.getKind() == RegularKind; } }; /// Used to represent a return instruction in user code. /// /// Allowed on an BranchInst, ReturnInst. class ReturnLocation : public SILLocation { public: ReturnLocation(ReturnStmt *RS); /// Construct the return location for a constructor or a destructor. ReturnLocation(BraceStmt *BS); ReturnStmt *get(); private: friend class SILLocation; static bool isKind(const SILLocation& L) { return L.getKind() == ReturnKind; } }; /// Used on the instruction that was generated to represent an implicit /// return from a function. /// /// Allowed on an BranchInst, ReturnInst. class ImplicitReturnLocation : public SILLocation { public: ImplicitReturnLocation(AbstractClosureExpr *E); ImplicitReturnLocation(ReturnStmt *S); ImplicitReturnLocation(AbstractFunctionDecl *AFD); /// Construct from a RegularLocation; preserve all special bits. /// /// Note, this can construct an implicit return for an arbitrary expression /// (specifically, in case of auto-generated bodies). static SILLocation getImplicitReturnLoc(SILLocation L); AbstractClosureExpr *get(); private: friend class SILLocation; static bool isKind(const SILLocation& L) { return L.getKind() == ImplicitReturnKind; } ImplicitReturnLocation() : SILLocation(ImplicitReturnKind) {} }; /// Marks instructions that correspond to inlined function body and /// setup code. This location should not be used for inlined transparent /// bodies, see MandatoryInlinedLocation. /// /// This location wraps the call site ASTNode. /// /// Allowed on any instruction except for ReturnInst. class InlinedLocation : public SILLocation { public: InlinedLocation(Expr *CallSite) : SILLocation(CallSite, InlinedKind) {} InlinedLocation(Stmt *S) : SILLocation(S, InlinedKind) {} InlinedLocation(Pattern *P) : SILLocation(P, InlinedKind) {} InlinedLocation(Decl *D) : SILLocation(D, InlinedKind) {} /// Constructs an inlined location when the call site is represented by a /// SILFile location. InlinedLocation(SourceLoc L) : SILLocation(InlinedKind) { setStorageKind(SILFileKind); Loc.SILFileLoc = L; } static InlinedLocation getInlinedLocation(SILLocation L); private: friend class SILLocation; static bool isKind(const SILLocation& L) { return L.getKind() == InlinedKind; } InlinedLocation() : SILLocation(InlinedKind) {} InlinedLocation(Expr *E, unsigned F) : SILLocation(E, InlinedKind, F) {} InlinedLocation(Stmt *S, unsigned F) : SILLocation(S, InlinedKind, F) {} InlinedLocation(Pattern *P, unsigned F) : SILLocation(P, InlinedKind, F) {} InlinedLocation(Decl *D, unsigned F) : SILLocation(D, InlinedKind, F) {} InlinedLocation(SourceLoc L, unsigned F) : SILLocation(L, InlinedKind, F) {} static InlinedLocation getModuleLocation(unsigned Flags) { auto L = InlinedLocation(); L.setSpecialFlags(Flags); return L; } }; /// Marks instructions that correspond to inlined function body and /// setup code for transparent functions, inlined as part of mandatory inlining /// pass. /// /// This location wraps the call site ASTNode. /// /// Allowed on any instruction except for ReturnInst. class MandatoryInlinedLocation : public SILLocation { public: MandatoryInlinedLocation(Expr *CallSite) : SILLocation(CallSite, MandatoryInlinedKind) {} MandatoryInlinedLocation(Stmt *S) : SILLocation(S, MandatoryInlinedKind) {} MandatoryInlinedLocation(Pattern *P) : SILLocation(P, MandatoryInlinedKind) {} MandatoryInlinedLocation(Decl *D) : SILLocation(D, MandatoryInlinedKind) {} /// Constructs an inlined location when the call site is represented by a /// SILFile location. MandatoryInlinedLocation(SourceLoc L) : SILLocation(L, MandatoryInlinedKind) {} static MandatoryInlinedLocation getMandatoryInlinedLocation(SILLocation L); static MandatoryInlinedLocation getAutoGeneratedLocation(); static MandatoryInlinedLocation getModuleLocation(unsigned Flags) { auto L = MandatoryInlinedLocation(); L.setSpecialFlags(Flags); return L; } private: friend class SILLocation; static bool isKind(const SILLocation& L) { return L.getKind() == MandatoryInlinedKind; } MandatoryInlinedLocation() : SILLocation(MandatoryInlinedKind) {} MandatoryInlinedLocation(Expr *E, unsigned F) : SILLocation(E, MandatoryInlinedKind, F) {} MandatoryInlinedLocation(Stmt *S, unsigned F) : SILLocation(S, MandatoryInlinedKind, F) {} MandatoryInlinedLocation(Pattern *P, unsigned F) : SILLocation(P, MandatoryInlinedKind, F) {} MandatoryInlinedLocation(Decl *D, unsigned F) : SILLocation(D, MandatoryInlinedKind, F) {} MandatoryInlinedLocation(SourceLoc L, unsigned F) : SILLocation(L, MandatoryInlinedKind, F) {} MandatoryInlinedLocation(DebugLoc L, unsigned F) : SILLocation(L, MandatoryInlinedKind, F) {} }; /// Used on the instruction performing auto-generated cleanup such as /// deallocs, destructor calls. /// /// The cleanups are performed after completing the evaluation of the AST Node /// wrapped inside the SILLocation. This location wraps the statement /// representing the enclosing scope, for example, FuncDecl, ParenExpr. The /// scope's end location points to the SourceLoc that shows when the operation /// is performed at runtime. /// /// Allowed on any instruction except for ReturnInst. /// Locations of an inlined destructor should also be represented by this. class CleanupLocation : public SILLocation { public: CleanupLocation(Expr *E) : SILLocation(E, CleanupKind) {} CleanupLocation(Stmt *S) : SILLocation(S, CleanupKind) {} CleanupLocation(Pattern *P) : SILLocation(P, CleanupKind) {} CleanupLocation(Decl *D) : SILLocation(D, CleanupKind) {} static CleanupLocation get(SILLocation L); /// Returns a location representing a cleanup on the module level. static CleanupLocation getModuleCleanupLocation() { CleanupLocation Loc; Loc.markAsInTopLevel(); return Loc; } private: friend class SILLocation; static bool isKind(const SILLocation& L) { return L.getKind() == CleanupKind; } CleanupLocation() : SILLocation(CleanupKind) {} CleanupLocation(Expr *E, unsigned F) : SILLocation(E, CleanupKind, F) {} CleanupLocation(Stmt *S, unsigned F) : SILLocation(S, CleanupKind, F) {} CleanupLocation(Pattern *P, unsigned F) : SILLocation(P, CleanupKind, F) {} CleanupLocation(Decl *D, unsigned F) : SILLocation(D, CleanupKind, F) {} }; /// Used to represent an unreachable location that was /// auto-generated and has no correspondence to user code. It should /// not be used in diagnostics or for debugging. /// /// Differentiates an unreachable instruction, which is generated by /// DCE, from an unreachable instruction in user code (output of SILGen). /// Allowed on an unreachable instruction. class ArtificialUnreachableLocation : public SILLocation { public: ArtificialUnreachableLocation() : SILLocation(ArtificialUnreachableKind) {} private: friend class SILLocation; static bool isKind(const SILLocation& L) { return (L.getKind() == ArtificialUnreachableKind); } }; class SILDebugScope; /// A SILLocation paired with a SILDebugScope. class SILDebugLocation { const SILDebugScope *Scope = nullptr; SILLocation Location; public: SILDebugLocation() : Scope(nullptr), Location(RegularLocation::getAutoGeneratedLocation()) {} SILDebugLocation(SILLocation Loc, const SILDebugScope *DS) : Scope(DS), Location(Loc) {} SILLocation getLocation() const { return Location; } const SILDebugScope *getScope() const { return Scope; } }; } // end swift namespace #endif
{ "content_hash": "1b64ffc02f9e81c4c70a0c8dd8fb41f7", "timestamp": "", "source": "github", "line_count": 751, "max_line_length": 80, "avg_line_length": 33.339547270306255, "alnum_prop": 0.6998961578400831, "repo_name": "stephentyrone/swift", "id": "c57af52aa3ff5016b8fa6b4a8a15df3be35cd010", "size": "25808", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "include/swift/SIL/SILLocation.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "13584" }, { "name": "C", "bytes": "245193" }, { "name": "C++", "bytes": "38276251" }, { "name": "CMake", "bytes": "542159" }, { "name": "D", "bytes": "1107" }, { "name": "DTrace", "bytes": "2593" }, { "name": "Emacs Lisp", "bytes": "57295" }, { "name": "LLVM", "bytes": "70652" }, { "name": "MATLAB", "bytes": "2576" }, { "name": "Makefile", "bytes": "1841" }, { "name": "Objective-C", "bytes": "425366" }, { "name": "Objective-C++", "bytes": "246376" }, { "name": "Python", "bytes": "1775045" }, { "name": "Roff", "bytes": "3495" }, { "name": "Ruby", "bytes": "2117" }, { "name": "Shell", "bytes": "177384" }, { "name": "Swift", "bytes": "33242293" }, { "name": "Vim Script", "bytes": "19900" }, { "name": "sed", "bytes": "1050" } ], "symlink_target": "" }
package ml.puredark.hviewer.ui.activities; import android.content.Intent; import android.graphics.Bitmap; import android.os.Build; import android.os.Bundle; import android.support.design.widget.AppBarLayout; import android.support.design.widget.CoordinatorLayout; import android.support.v7.widget.Toolbar; import android.webkit.CookieManager; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import ml.puredark.hviewer.HViewerApplication; import ml.puredark.hviewer.R; import ml.puredark.hviewer.beans.Site; import ml.puredark.hviewer.helpers.MDStatusBarCompat; public class LoginActivity extends BaseActivity { @BindView(R.id.btn_return) ImageView btnReturn; @BindView(R.id.tv_title) TextView tvTitle; @BindView(R.id.app_bar) AppBarLayout appbar; @BindView(R.id.toolbar) Toolbar toolbar; @BindView(R.id.web_view) WebView webView; @BindView(R.id.coordinator_layout) CoordinatorLayout coordinatorLayout; private Site site; private boolean checking = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); ButterKnife.bind(this); setSupportActionBar(toolbar); getSupportActionBar().setDisplayShowTitleEnabled(false); MDStatusBarCompat.setSwipeBackToolBar(this, coordinatorLayout, appbar, toolbar); if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) { toolbar.setFitsSystemWindows(true); LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) appbar.getLayoutParams(); lp.height = (int) (MDStatusBarCompat.getStatusBarHeight(this) + getResources().getDimension(R.dimen.tool_bar_height)); appbar.setLayoutParams(lp); } setContainer(coordinatorLayout); /* 为返回按钮加载图标 */ setReturnButton(btnReturn); //获取传递过来的Site实例 if (HViewerApplication.temp instanceof Site) site = (Site) HViewerApplication.temp; //获取失败则结束此界面 if (site == null || site.loginUrl == null || "".equals(site.loginUrl)) { Toast.makeText(this, "没有定义登录地址", Toast.LENGTH_SHORT).show(); finish(); return; } tvTitle.setText("登录" + site.title); WebSettings settings = webView.getSettings(); settings.setSupportZoom(true); settings.setBuiltInZoomControls(true); // settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN); // settings.setLoadWithOverviewMode(true); // settings.setUseWideViewPort(true); settings.setUserAgentString(getResources().getString(R.string.UA)); settings.setDefaultTextEncodingName("UTF-8"); settings.setJavaScriptEnabled(true); webView.setWebViewClient(new WebViewClient() { @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { CookieManager cookieManager = CookieManager.getInstance(); String cookies = cookieManager.getCookie(url); site.cookie = cookies; super.onPageStarted(view, url, favicon); } @Override public void onPageFinished(WebView view, String url) { CookieManager cookieManager = CookieManager.getInstance(); String cookies = cookieManager.getCookie(url); site.cookie = cookies; if (checking) back(); else showSnackBar("登录成功后请点击右上角图标进行首页访问测试"); super.onPageFinished(view, url); } }); webView.loadUrl(site.loginUrl); } @OnClick(R.id.btn_return) void back() { HViewerApplication.temp = site; Intent intent = new Intent(); setResult(RESULT_OK, intent); onBackPressed(); } @OnClick(R.id.btn_visit_index) void check() { if (checking) return; checking = true; showSnackBar("正在打开首页,成功自动返回主界面"); webView.loadUrl(site.indexUrl); } }
{ "content_hash": "77a4b8b70e6389130c2826ba334ca391", "timestamp": "", "source": "github", "line_count": 129, "max_line_length": 96, "avg_line_length": 34.35658914728682, "alnum_prop": 0.6597472924187726, "repo_name": "AI-Cloud/H-Viewer", "id": "f642a0a37f345ad8e0c16b9642fb797722095fa0", "size": "4582", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "app/src/main/java/ml/puredark/hviewer/ui/activities/LoginActivity.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "IDL", "bytes": "908" }, { "name": "Java", "bytes": "1300831" } ], "symlink_target": "" }
ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "ef5f0e48f878bc8096c30714ad0621d1", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.307692307692308, "alnum_prop": 0.6940298507462687, "repo_name": "mdoering/backbone", "id": "a29114981ffb0d020048997495dbc06475adcea1", "size": "186", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Asparagaceae/Lachenalia/Lachenalia campanulata/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
export default function trigger(element, str) { element.dispatchEvent(new Event(str, { view: window, bubbles: true, cancelable: true, })); }
{ "content_hash": "ce053807bbd3080f840716e3083a39a8", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 47, "avg_line_length": 22.428571428571427, "alnum_prop": 0.6624203821656051, "repo_name": "lohfu/dollr", "id": "fbc30b30df4de312eb268c33e141acb6d27d7aae", "size": "157", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/trigger.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "18619" } ], "symlink_target": "" }
import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { Observable } from 'rxjs/Observable'; import { Subject } from 'rxjs/Subject'; import { HeroSearchService } from './hero-search.service'; import { Hero } from './hero'; @Component({ moduleId: 'HeroSearchComponent', selector: 'curly-hero-search', templateUrl: 'hero-search.component.html', styleUrls: ['hero-search.component.css'], providers: [HeroSearchService] }) export class HeroSearchComponent implements OnInit { private heroes: Observable<Hero[]>; private searchTerms = new Subject<string>(); constructor( private heroSearchService: HeroSearchService, private router: Router ) { } // Push a search term into the observable stream. public search(term: string): void { this.searchTerms.next(term); } public ngOnInit(): void { this.heroes = this.searchTerms .debounceTime(300) // wait for 300ms pause in events .distinctUntilChanged() // ignore if next search term is same as previous .switchMap(term => term // switch to new observable each time // return the http search observable ? this.heroSearchService.search(term) // or the observable of empty heroes if no search term : Observable.of<Hero[]>([])) .catch(error => { console.log(error); // TODO: real error handling return Observable.of<Hero[]>([]); }); } public gotoDetail(hero: Hero): void { let link = ['/heroes', hero.id]; this.router.navigate(link); } }
{ "content_hash": "ca357405cf4913b95a7b1ed011931fff", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 81, "avg_line_length": 32.89795918367347, "alnum_prop": 0.6488833746898263, "repo_name": "KiT106/Curly", "id": "af83666e025646d0a0080b7a182edd26af3832e6", "size": "1612", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/app/hero-search.component.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "3428" }, { "name": "HTML", "bytes": "1997" }, { "name": "JavaScript", "bytes": "1833" }, { "name": "TypeScript", "bytes": "12736" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <!-- Copyright 2017 The Chromium Authors. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. --> <androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/control_container" android:layout_width="match_parent" android:layout_height="match_parent" > <ViewStub android:id="@+id/omnibox_results_container_stub" android:layout_width="match_parent" android:layout_height="wrap_content" app:layout_anchor="@id/toolbar" android:background="@android:color/white" android:layout="@layout/omnibox_results_container" /> <FrameLayout android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="@dimen/toolbar_height_no_shadow" android:background="@color/toolbar_background_primary" android:paddingStart="@dimen/toolbar_edge_padding" android:paddingEnd="@dimen/toolbar_edge_padding" android:clickable="true" > <org.chromium.chrome.browser.searchwidget.SearchActivityLocationBarLayout android:id="@+id/search_location_bar" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:layout_marginTop="@dimen/location_bar_vertical_margin" android:layout_marginBottom="@dimen/location_bar_vertical_margin" android:paddingStart="@dimen/location_bar_lateral_padding" android:paddingEnd="@dimen/location_bar_lateral_padding" /> </FrameLayout> <FrameLayout android:id="@+id/bottom_container" android:layout_width="match_parent" android:layout_height="match_parent" /> </androidx.coordinatorlayout.widget.CoordinatorLayout>
{ "content_hash": "918ef5a7b8204d682a066d597b889cc0", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 81, "avg_line_length": 44.702127659574465, "alnum_prop": 0.6520704426463588, "repo_name": "endlessm/chromium-browser", "id": "5634ad71d893229b6408b1f6586823644d4e70ff", "size": "2101", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "chrome/android/java/res/layout/search_activity.xml", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
""" Copyright (c) 2015 Civic Knowledge. This file is licensed under the terms of the Revised BSD License, included in this distribution as LICENSE.txt """ from .core import * class ErrorVT(ValueType): role = ROLE.ERROR vt_code = 'e' def __init__(self,v): pass class MarginOfErrorVT(FloatValue): role = ROLE.ERROR vt_code = 'm' def __init__(self,v): pass @property def se(self): if '/90' in self.vt_code: return self / 1.645 elif '/95' in self.vt_code: return self / 1.96 elif '/99' in self.vt_code: return self / 2.575 else: raise ValueError("Can't understand value_args: {}".format(self.type_args)) @property def m90(self): return self.se * 1.645 @property def m95(self): return self.se * 1.96 @property def m99(self): return self.se * 2.575 def ci90u(self, v): """Return the 90% confidence interval upper value""" return v + self.m90 def ci90l(self, v): """Return the 90% confidence interval lower value""" return v - self.m90 @property def m95(self): pass def ci90u(self, v): """Return the 95% confidence interval upper value""" return v + self.m90 def ci90l(self, v): """Return the 95% confidence interval lower value""" return v - self.m90 def ci95u(self, v): """Return the 95% confidence interval upper value""" return v + self.m95 def ci95l(self, v): """Return the 95% confidence interval lower value""" return v - self.m95 def rse(self, denom): """Return the relative standard error, relative to the given value""" return self.se / denom class ConfidenceIntervalHalfVT(FloatValue): """An upper or lower half of a confidence interval""" role = ROLE.ERROR vt_code = 'ci' def __init__(self,v): pass @property def se(self): pass class StandardErrorVT(FloatValue): """A standard error""" role = ROLE.ERROR vt_code = 'se' @property def m90(self): o = MarginOfErrorVT(self * 1.645) o.vt_code += '/90' return o @property def m95(self): o = MarginOfErrorVT(self * 1.96) o.vt_code += '/95' return o @property def m99(self): o = MarginOfErrorVT(self * 2.575) o.vt_code += '/99' return o def ci90u(self, v): """Return the 95% confidence interval upper value""" return v + self.m90 def ci90l(self, v): """Return the 95% confidence interval lower value""" return v - self.m90 def ci95u(self, v): """Return the 95% confidence interval upper value""" return v + self.m95 def ci95l(self, v): """Return the 95% confidence interval lower value""" return v - self.m95 class RelativeStandardErrorVT(FloatValue): role = ROLE.ERROR vt_code = 'rse' error_value_types = { "margin": MarginOfErrorVT, # m90, m95, m99 "ci": ConfidenceIntervalHalfVT, #ci90u, ci90l, ci95u, ci95l, ci99u, ci99l "se": StandardErrorVT, "rse": RelativeStandardErrorVT, }
{ "content_hash": "0c824f3eddea61bfebf9082d25344416", "timestamp": "", "source": "github", "line_count": 146, "max_line_length": 86, "avg_line_length": 22.273972602739725, "alnum_prop": 0.5756457564575646, "repo_name": "CivicKnowledge/rowgenerators", "id": "de589218d4c7890af8538a6fce8d3ef8bdd2f27b", "size": "3252", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "rowgenerators/valuetype/errors.py", "mode": "33188", "license": "mit", "language": [ { "name": "Jupyter Notebook", "bytes": "823" }, { "name": "Python", "bytes": "109674" } ], "symlink_target": "" }
build: docker build -t vothanhkiet/alpine-s6-krakend:latest -t vothanhkiet/alpine-s6-krakend:0.6.0 --rm=true . upload: docker push vothanhkiet/alpine-s6-krakend:0.6.0 docker push vothanhkiet/alpine-s6-krakend:latest
{ "content_hash": "40728ddbb1cf5d73be40bbeb3fd92183", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 104, "avg_line_length": 36.666666666666664, "alnum_prop": 0.7818181818181819, "repo_name": "vothanhkiet/dockerfile-collections", "id": "4106a11f8e42b4331746d155b7ae48ec007178ea", "size": "220", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "alpine-s6-krakend/Makefile", "mode": "33188", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "41046" }, { "name": "HTML", "bytes": "2101" }, { "name": "Makefile", "bytes": "6256" }, { "name": "Shell", "bytes": "36510" } ], "symlink_target": "" }
<!-- COPYRIGHT LICENSE: This information contains sample code provided in source code form. You may copy, modify, and distribute these sample programs in any form without payment to IBM for the purposes of developing, using, marketing or distributing application programs conforming to the application programming interface for the operating platform for which the sample code is written. Notwithstanding anything to the contrary, IBM PROVIDES THE SAMPLE SOURCE CODE ON AN "AS IS" BASIS AND IBM DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, ANY IMPLIED WARRANTIES OR CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE, AND ANY WARRANTY OR CONDITION OF NON-INFRINGEMENT. IBM SHALL NOT BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR OPERATION OF THE SAMPLE SOURCE CODE. IBM HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS OR MODIFICATIONS TO THE SAMPLE SOURCE CODE. (C) Copyright IBM Corp. 2015. All Rights Reserved. Licensed Materials - Property of IBM. --> <link rel="import" href="../../bower_components/polymer/polymer.html"> <link rel="import" href="../../bower_components/iron-meta/iron-meta.html"> <dom-module name="url-service"> <style> </style> <template> <iron-meta id="meta-config" key="envconfig" value=""></iron-meta> </template> <script> Polymer({ is: "url-service", properties: { }, ready: function() { console.log("url-service is ready."); } }); </script> </dom-module>
{ "content_hash": "3473097c1b0d13b8b0f1ee8d93f89582", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 86, "avg_line_length": 34.1063829787234, "alnum_prop": 0.7442295695570805, "repo_name": "IBM-Bluemix/bluetag", "id": "e7fa8b9429f923c1a93798de8ad85601f893c5f2", "size": "1603", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "bluetag-frontend/www/app/elements/url-service/url-service.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "1116" }, { "name": "C++", "bytes": "5534" }, { "name": "CSS", "bytes": "4963" }, { "name": "HTML", "bytes": "106184" }, { "name": "Java", "bytes": "152454" }, { "name": "JavaScript", "bytes": "54378" }, { "name": "Objective-C", "bytes": "17203" }, { "name": "Shell", "bytes": "1912" } ], "symlink_target": "" }
from gi.repository import Gtk import subprocess class BrightnessScale: def __init__(self): # get active monitor and current brightness self.monitor = self.getActiveMonitor() self.currB = self.getCurrentBrightness() def initUI(self): # initliaze and configure window window = Gtk.Window() window.set_title('Brightness Scale') window.set_default_size(250, 50) window.set_position(Gtk.WindowPosition.CENTER) window.set_border_width(10) # slider configuration self.adjustment = Gtk.Adjustment(self.currB, 0, 100, 1, 10, 0) self.scale = Gtk.HScale() self.scale.set_adjustment(self.adjustment) self.scale.set_digits(0) # close Gtk thread on closing window window.connect("destroy", lambda w: Gtk.main_quit()) # setup event handler on value-changed self.scale.connect("value-changed", self.scale_moved) # add the scale to window window.add(self.scale) # show all components in window window.show_all() # close window on pressing escape key accGroup = Gtk.AccelGroup() key, modifier = Gtk.accelerator_parse('Escape') accGroup.connect(key, modifier, Gtk.AccelFlags.VISIBLE, Gtk.main_quit) window.add_accel_group(accGroup) def showErrDialog(self): self.errDialog = Gtk.MessageDialog(None, Gtk.DialogFlags.MODAL, Gtk.MessageType.ERROR, Gtk.ButtonsType.OK, "Unable to detect active monitor, run 'xrandr --verbose' on command-line for more info") self.errDialog.set_title("brightness control error") self.errDialog.run() self.errDialog.destroy() def initStatus(self): if(self.monitor == "" or self.currB == ""): return False return True def getActiveMonitor(self): #Find display monitor monitor = subprocess.check_output("xrandr -q | grep ' connected' | cut -d ' ' -f1", shell=True) if(monitor != ""): monitor = monitor.split('\n')[0] return monitor def getCurrentBrightness(self): #Find current brightness currB = subprocess.check_output("xrandr --verbose | grep -i brightness | cut -f2 -d ' '", shell=True) if(currB != ""): currB = currB.split('\n')[0] currB = int(float(currB) * 100) else: currB = "" return currB def scale_moved(self, event): #Change brightness newBrightness = float(self.scale.get_value())/100 cmd = "xrandr --output %s --brightness %.2f" % (self.monitor, newBrightness) cmdStatus = subprocess.check_output(cmd, shell=True) if __name__ == "__main__": # new instance of BrightnessScale brcontrol = BrightnessScale() if(brcontrol.initStatus()): # if everything ok, invoke UI and start Gtk thread loop brcontrol.initUI() Gtk.main() else: # show error dialog brcontrol.showErrDialog()
{ "content_hash": "f363f22dd42a8e3fc3711b4f6cd80782", "timestamp": "", "source": "github", "line_count": 89, "max_line_length": 131, "avg_line_length": 36.47191011235955, "alnum_prop": 0.5754775107825015, "repo_name": "ravikiranj/brightness-control", "id": "0cc41bff0f3a61b4df369af194d2f2f992b460a1", "size": "3269", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "brightness.py", "mode": "33261", "license": "bsd-3-clause", "language": [ { "name": "Python", "bytes": "3269" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace MrFusion.Models { public interface IBoard : IChildBase { [Required] string Name { get; set; } [Required] Guid TeamId { get; set; } } }
{ "content_hash": "1c8a20cec44a36d1abd95e5d464f4540", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 44, "avg_line_length": 19.647058823529413, "alnum_prop": 0.6646706586826348, "repo_name": "sefl-corp/mr-fusion", "id": "139002ab5e74f93418975008e52049900d97cacc", "size": "336", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Models/IBoard.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "46553" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>additions: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.8.1 / additions - 8.6.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> additions <small> 8.6.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-10-17 18:19:02 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-10-17 18:19:02 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base camlp5 7.14 Preprocessor-pretty-printer of OCaml conf-findutils 1 Virtual package relying on findutils conf-perl 2 Virtual package relying on perl coq 8.8.1 Formal proof management system num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic ocaml 4.06.1 The OCaml compiler (virtual package) ocaml-base-compiler 4.06.1 Official 4.06.1 release ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.5 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;Hugo.Herbelin@inria.fr&quot; homepage: &quot;https://github.com/coq-contribs/additions&quot; license: &quot;LGPL 2.1&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/Additions&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.6&quot; &amp; &lt; &quot;8.7~&quot;} ] tags: [ &quot;keyword: addition chains&quot; &quot;category: Computer Science/Decision Procedures and Certified Algorithms/Correctness proofs of algorithms&quot; &quot;category: Miscellaneous/Extracted Programs/Arithmetic&quot; ] authors: [ &quot;Pierre Castéran&quot; ] bug-reports: &quot;https://github.com/coq-contribs/additions/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/additions.git&quot; synopsis: &quot;Addition Chains&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/additions/archive/v8.6.0.tar.gz&quot; checksum: &quot;md5=8a8f3ad4f0aa8e5381bdf3b1b0e4a06a&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-additions.8.6.0 coq.8.8.1</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.8.1). The following dependencies couldn&#39;t be met: - coq-additions -&gt; coq &lt; 8.7~ -&gt; ocaml &lt; 4.06.0 base of this switch (use `--unlock-base&#39; to force) No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-additions.8.6.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{ "content_hash": "37a9b424d2154db76361ab18368bce28", "timestamp": "", "source": "github", "line_count": 161, "max_line_length": 229, "avg_line_length": 41.80124223602485, "alnum_prop": 0.5368499257057949, "repo_name": "coq-bench/coq-bench.github.io", "id": "da6cb1d4c8aa8c1eac1e978112f7f3b46e077ea8", "size": "6756", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.06.1-2.0.5/released/8.8.1/additions/8.6.0.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
/* $NetBSD: ldapdb.c,v 1.3.12.2 2015/07/17 04:31:27 snj Exp $ */ /* * ldapdb.c version 1.0-beta * * Copyright (C) 2002, 2004 Stig Venaas * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * Contributors: Jeremy C. McDermond */ /* * If you want to use TLS, uncomment the define below */ /* #define LDAPDB_TLS */ /* * If you are using an old LDAP API uncomment the define below. Only do this * if you know what you're doing or get compilation errors on ldap_memfree(). * This also forces LDAPv2. */ /* #define LDAPDB_RFC1823API */ /* Using LDAPv3 by default, change this if you want v2 */ #ifndef LDAPDB_LDAP_VERSION #define LDAPDB_LDAP_VERSION 3 #endif #include <config.h> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <isc/mem.h> #include <isc/print.h> #include <isc/result.h> #include <isc/util.h> #include <isc/thread.h> #include <dns/sdb.h> #include <named/globals.h> #include <named/log.h> #include <ldap.h> #include "ldapdb.h" /* * A simple database driver for LDAP */ /* enough for name with 8 labels of max length */ #define MAXNAMELEN 519 static dns_sdbimplementation_t *ldapdb = NULL; struct ldapdb_data { char *hostport; char *hostname; int portno; char *base; int defaultttl; char *filterall; int filteralllen; char *filterone; int filteronelen; char *filtername; char *bindname; char *bindpw; #ifdef LDAPDB_TLS int tls; #endif }; /* used by ldapdb_getconn */ struct ldapdb_entry { void *index; size_t size; void *data; struct ldapdb_entry *next; }; static struct ldapdb_entry *ldapdb_find(struct ldapdb_entry *stack, const void *index, size_t size) { while (stack != NULL) { if (stack->size == size && !memcmp(stack->index, index, size)) return stack; stack = stack->next; } return NULL; } static void ldapdb_insert(struct ldapdb_entry **stack, struct ldapdb_entry *item) { item->next = *stack; *stack = item; } static void ldapdb_lock(int what) { static isc_mutex_t lock; switch (what) { case 0: isc_mutex_init(&lock); break; case 1: LOCK(&lock); break; case -1: UNLOCK(&lock); break; } } /* data == NULL means cleanup */ static LDAP ** ldapdb_getconn(struct ldapdb_data *data) { static struct ldapdb_entry *allthreadsdata = NULL; struct ldapdb_entry *threaddata, *conndata; unsigned long threadid; if (data == NULL) { /* cleanup */ /* lock out other threads */ ldapdb_lock(1); while (allthreadsdata != NULL) { threaddata = allthreadsdata; free(threaddata->index); while (threaddata->data != NULL) { conndata = threaddata->data; if (conndata->data != NULL) ldap_unbind((LDAP *)conndata->data); threaddata->data = conndata->next; free(conndata); } allthreadsdata = threaddata->next; free(threaddata); } ldapdb_lock(-1); return (NULL); } /* look for connection data for current thread */ threadid = isc_thread_self(); threaddata = ldapdb_find(allthreadsdata, &threadid, sizeof(threadid)); if (threaddata == NULL) { /* no data for this thread, create empty connection list */ threaddata = malloc(sizeof(*threaddata)); if (threaddata == NULL) return (NULL); threaddata->index = malloc(sizeof(threadid)); if (threaddata->index == NULL) { free(threaddata); return (NULL); } *(unsigned long *)threaddata->index = threadid; threaddata->size = sizeof(threadid); threaddata->data = NULL; /* need to lock out other threads here */ ldapdb_lock(1); ldapdb_insert(&allthreadsdata, threaddata); ldapdb_lock(-1); } /* threaddata points at the connection list for current thread */ /* look for existing connection to our server */ conndata = ldapdb_find((struct ldapdb_entry *)threaddata->data, data->hostport, strlen(data->hostport)); if (conndata == NULL) { /* no connection data structure for this server, create one */ conndata = malloc(sizeof(*conndata)); if (conndata == NULL) return (NULL); conndata->index = data->hostport; conndata->size = strlen(data->hostport); conndata->data = NULL; ldapdb_insert((struct ldapdb_entry **)&threaddata->data, conndata); } return (LDAP **)&conndata->data; } static void ldapdb_bind(struct ldapdb_data *data, LDAP **ldp) { #ifndef LDAPDB_RFC1823API const int ver = LDAPDB_LDAP_VERSION; #endif if (*ldp != NULL) ldap_unbind(*ldp); *ldp = ldap_open(data->hostname, data->portno); if (*ldp == NULL) return; #ifndef LDAPDB_RFC1823API ldap_set_option(*ldp, LDAP_OPT_PROTOCOL_VERSION, &ver); #endif #ifdef LDAPDB_TLS if (data->tls) { ldap_start_tls_s(*ldp, NULL, NULL); } #endif if (ldap_simple_bind_s(*ldp, data->bindname, data->bindpw) != LDAP_SUCCESS) { ldap_unbind(*ldp); *ldp = NULL; } } #ifdef DNS_CLIENTINFO_VERSION static isc_result_t ldapdb_search(const char *zone, const char *name, void *dbdata, void *retdata, dns_clientinfomethods_t *methods, dns_clientinfo_t *clientinfo) #else static isc_result_t ldapdb_search(const char *zone, const char *name, void *dbdata, void *retdata, void *methods, void *clientinfo) #endif /* DNS_CLIENTINFO_VERSION */ { struct ldapdb_data *data = dbdata; isc_result_t result = ISC_R_NOTFOUND; LDAP **ldp; LDAPMessage *res, *e; char *fltr, *a, **vals = NULL, **names = NULL; char type[64]; #ifdef LDAPDB_RFC1823API void *ptr; #else BerElement *ptr; #endif int i, j, errno, msgid; UNUSED(methods); UNUSED(clientinfo); ldp = ldapdb_getconn(data); if (ldp == NULL) return (ISC_R_FAILURE); if (*ldp == NULL) { ldapdb_bind(data, ldp); if (*ldp == NULL) { isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_SERVER, ISC_LOG_ERROR, "LDAP sdb zone '%s': bind failed", zone); return (ISC_R_FAILURE); } } if (name == NULL) { fltr = data->filterall; } else { if (strlen(name) > MAXNAMELEN) { isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_SERVER, ISC_LOG_ERROR, "LDAP sdb zone '%s': name %s too long", zone, name); return (ISC_R_FAILURE); } sprintf(data->filtername, "%s))", name); fltr = data->filterone; } msgid = ldap_search(*ldp, data->base, LDAP_SCOPE_SUBTREE, fltr, NULL, 0); if (msgid == -1) { ldapdb_bind(data, ldp); if (*ldp != NULL) msgid = ldap_search(*ldp, data->base, LDAP_SCOPE_SUBTREE, fltr, NULL, 0); } if (*ldp == NULL || msgid == -1) { isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_SERVER, ISC_LOG_ERROR, "LDAP sdb zone '%s': search failed, filter %s", zone, fltr); return (ISC_R_FAILURE); } /* Get the records one by one as they arrive and return them to bind */ while ((errno = ldap_result(*ldp, msgid, 0, NULL, &res)) != LDAP_RES_SEARCH_RESULT ) { LDAP *ld = *ldp; int ttl = data->defaultttl; /* not supporting continuation references at present */ if (errno != LDAP_RES_SEARCH_ENTRY) { isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_SERVER, ISC_LOG_ERROR, "LDAP sdb zone '%s': ldap_result returned %d", zone, errno); ldap_msgfree(res); return (ISC_R_FAILURE); } /* only one entry per result message */ e = ldap_first_entry(ld, res); if (e == NULL) { ldap_msgfree(res); isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_SERVER, ISC_LOG_ERROR, "LDAP sdb zone '%s': ldap_first_entry failed", zone); return (ISC_R_FAILURE); } if (name == NULL) { names = ldap_get_values(ld, e, "relativeDomainName"); if (names == NULL) continue; } vals = ldap_get_values(ld, e, "dNSTTL"); if (vals != NULL) { ttl = atoi(vals[0]); ldap_value_free(vals); } for (a = ldap_first_attribute(ld, e, &ptr); a != NULL; a = ldap_next_attribute(ld, e, ptr)) { char *s; for (s = a; *s; s++) *s = toupper(*s); s = strstr(a, "RECORD"); if ((s == NULL) || (s == a) || (s - a >= (signed int)sizeof(type))) { #ifndef LDAPDB_RFC1823API ldap_memfree(a); #endif continue; } strncpy(type, a, s - a); type[s - a] = '\0'; vals = ldap_get_values(ld, e, a); if (vals != NULL) { for (i = 0; vals[i] != NULL; i++) { if (name != NULL) { result = dns_sdb_putrr(retdata, type, ttl, vals[i]); } else { for (j = 0; names[j] != NULL; j++) { result = dns_sdb_putnamedrr(retdata, names[j], type, ttl, vals[i]); if (result != ISC_R_SUCCESS) break; } } ; if (result != ISC_R_SUCCESS) { isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_SERVER, ISC_LOG_ERROR, "LDAP sdb zone '%s': dns_sdb_put... failed for %s", zone, vals[i]); ldap_value_free(vals); #ifndef LDAPDB_RFC1823API ldap_memfree(a); if (ptr != NULL) ber_free(ptr, 0); #endif if (name == NULL) ldap_value_free(names); ldap_msgfree(res); return (ISC_R_FAILURE); } } ldap_value_free(vals); } #ifndef LDAPDB_RFC1823API ldap_memfree(a); #endif } #ifndef LDAPDB_RFC1823API if (ptr != NULL) ber_free(ptr, 0); #endif if (name == NULL) ldap_value_free(names); /* free this result */ ldap_msgfree(res); } /* free final result */ ldap_msgfree(res); return (result); } /* callback routines */ #ifdef DNS_CLIENTINFO_VERSION static isc_result_t ldapdb_lookup(const char *zone, const char *name, void *dbdata, dns_sdblookup_t *lookup, dns_clientinfomethods_t *methods, dns_clientinfo_t *clientinfo) { UNUSED(methods); UNUSED(clientinfo); return (ldapdb_search(zone, name, dbdata, lookup, NULL, NULL)); } #else static isc_result_t ldapdb_lookup(const char *zone, const char *name, void *dbdata, dns_sdblookup_t *lookup) { return (ldapdb_search(zone, name, dbdata, lookup, methods, clientinfo)); } #endif /* DNS_CLIENTINFO_VERSION */ static isc_result_t ldapdb_allnodes(const char *zone, void *dbdata, dns_sdballnodes_t *allnodes) { return (ldapdb_search(zone, NULL, dbdata, allnodes, NULL, NULL)); } static char * unhex(char *in) { static const char hexdigits[] = "0123456789abcdef"; char *p, *s = in; int d1, d2; while ((s = strchr(s, '%'))) { if (!(s[1] && s[2])) return NULL; if ((p = strchr(hexdigits, tolower(s[1]))) == NULL) return NULL; d1 = p - hexdigits; if ((p = strchr(hexdigits, tolower(s[2]))) == NULL) return NULL; d2 = p - hexdigits; *s++ = d1 << 4 | d2; memmove(s, s + 2, strlen(s) - 1); } return in; } /* returns 0 for ok, -1 for bad syntax, -2 for unknown critical extension */ static int parseextensions(char *extensions, struct ldapdb_data *data) { char *s, *next, *name, *value; int critical; while (extensions != NULL) { s = strchr(extensions, ','); if (s != NULL) { *s++ = '\0'; next = s; } else { next = NULL; } if (*extensions != '\0') { s = strchr(extensions, '='); if (s != NULL) { *s++ = '\0'; value = *s != '\0' ? s : NULL; } else { value = NULL; } name = extensions; critical = *name == '!'; if (critical) { name++; } if (*name == '\0') { return -1; } if (!strcasecmp(name, "bindname")) { data->bindname = value; } else if (!strcasecmp(name, "x-bindpw")) { data->bindpw = value; #ifdef LDAPDB_TLS } else if (!strcasecmp(name, "x-tls")) { data->tls = value == NULL || !strcasecmp(value, "true"); #endif } else if (critical) { return -2; } } extensions = next; } return 0; } static void free_data(struct ldapdb_data *data) { if (data->hostport != NULL) isc_mem_free(ns_g_mctx, data->hostport); if (data->hostname != NULL) isc_mem_free(ns_g_mctx, data->hostname); if (data->filterall != NULL) isc_mem_put(ns_g_mctx, data->filterall, data->filteralllen); if (data->filterone != NULL) isc_mem_put(ns_g_mctx, data->filterone, data->filteronelen); isc_mem_put(ns_g_mctx, data, sizeof(struct ldapdb_data)); } static isc_result_t ldapdb_create(const char *zone, int argc, char **argv, void *driverdata, void **dbdata) { struct ldapdb_data *data; char *s, *filter = NULL, *extensions = NULL; int defaultttl; UNUSED(driverdata); /* we assume that only one thread will call create at a time */ /* want to do this only once for all instances */ if ((argc < 2) || (argv[0] != strstr( argv[0], "ldap://")) || ((defaultttl = atoi(argv[1])) < 1)) return (ISC_R_FAILURE); data = isc_mem_get(ns_g_mctx, sizeof(struct ldapdb_data)); if (data == NULL) return (ISC_R_NOMEMORY); memset(data, 0, sizeof(struct ldapdb_data)); data->hostport = isc_mem_strdup(ns_g_mctx, argv[0] + strlen("ldap://")); if (data->hostport == NULL) { free_data(data); return (ISC_R_NOMEMORY); } data->defaultttl = defaultttl; s = strchr(data->hostport, '/'); if (s != NULL) { *s++ = '\0'; data->base = s; /* attrs, scope, filter etc? */ s = strchr(s, '?'); if (s != NULL) { *s++ = '\0'; /* ignore attributes */ s = strchr(s, '?'); if (s != NULL) { *s++ = '\0'; /* ignore scope */ s = strchr(s, '?'); if (s != NULL) { *s++ = '\0'; /* filter */ filter = s; s = strchr(s, '?'); if (s != NULL) { *s++ = '\0'; /* extensions */ extensions = s; s = strchr(s, '?'); if (s != NULL) { *s++ = '\0'; } if (*extensions == '\0') { extensions = NULL; } } if (*filter == '\0') { filter = NULL; } } } } if (*data->base == '\0') { data->base = NULL; } } /* parse extensions */ if (extensions != NULL) { int err; err = parseextensions(extensions, data); if (err < 0) { /* err should be -1 or -2 */ free_data(data); if (err == -1) { isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_SERVER, ISC_LOG_ERROR, "LDAP sdb zone '%s': URL: extension syntax error", zone); } else if (err == -2) { isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_SERVER, ISC_LOG_ERROR, "LDAP sdb zone '%s': URL: unknown critical extension", zone); } return (ISC_R_FAILURE); } } if ((data->base != NULL && unhex(data->base) == NULL) || (filter != NULL && unhex(filter) == NULL) || (data->bindname != NULL && unhex(data->bindname) == NULL) || (data->bindpw != NULL && unhex(data->bindpw) == NULL)) { free_data(data); isc_log_write(ns_g_lctx, NS_LOGCATEGORY_GENERAL, NS_LOGMODULE_SERVER, ISC_LOG_ERROR, "LDAP sdb zone '%s': URL: bad hex values", zone); return (ISC_R_FAILURE); } /* compute filterall and filterone once and for all */ if (filter == NULL) { data->filteralllen = strlen(zone) + strlen("(zoneName=)") + 1; data->filteronelen = strlen(zone) + strlen("(&(zoneName=)(relativeDomainName=))") + MAXNAMELEN + 1; } else { data->filteralllen = strlen(filter) + strlen(zone) + strlen("(&(zoneName=))") + 1; data->filteronelen = strlen(filter) + strlen(zone) + strlen("(&(zoneName=)(relativeDomainName=))") + MAXNAMELEN + 1; } data->filterall = isc_mem_get(ns_g_mctx, data->filteralllen); if (data->filterall == NULL) { free_data(data); return (ISC_R_NOMEMORY); } data->filterone = isc_mem_get(ns_g_mctx, data->filteronelen); if (data->filterone == NULL) { free_data(data); return (ISC_R_NOMEMORY); } if (filter == NULL) { sprintf(data->filterall, "(zoneName=%s)", zone); sprintf(data->filterone, "(&(zoneName=%s)(relativeDomainName=", zone); } else { sprintf(data->filterall, "(&%s(zoneName=%s))", filter, zone); sprintf(data->filterone, "(&%s(zoneName=%s)(relativeDomainName=", filter, zone); } data->filtername = data->filterone + strlen(data->filterone); /* support URLs with literal IPv6 addresses */ data->hostname = isc_mem_strdup(ns_g_mctx, data->hostport + (*data->hostport == '[' ? 1 : 0)); if (data->hostname == NULL) { free_data(data); return (ISC_R_NOMEMORY); } if (*data->hostport == '[' && (s = strchr(data->hostname, ']')) != NULL ) *s++ = '\0'; else s = data->hostname; s = strchr(s, ':'); if (s != NULL) { *s++ = '\0'; data->portno = atoi(s); } else data->portno = LDAP_PORT; *dbdata = data; return (ISC_R_SUCCESS); } static void ldapdb_destroy(const char *zone, void *driverdata, void **dbdata) { struct ldapdb_data *data = *dbdata; UNUSED(zone); UNUSED(driverdata); free_data(data); } static dns_sdbmethods_t ldapdb_methods = { ldapdb_lookup, NULL, /* authority */ ldapdb_allnodes, ldapdb_create, ldapdb_destroy, NULL /* lookup2 */ }; /* Wrapper around dns_sdb_register() */ isc_result_t ldapdb_init(void) { unsigned int flags = DNS_SDBFLAG_RELATIVEOWNER | DNS_SDBFLAG_RELATIVERDATA | DNS_SDBFLAG_THREADSAFE; ldapdb_lock(0); return (dns_sdb_register("ldap", &ldapdb_methods, NULL, flags, ns_g_mctx, &ldapdb)); } /* Wrapper around dns_sdb_unregister() */ void ldapdb_clear(void) { if (ldapdb != NULL) { /* clean up thread data */ ldapdb_getconn(NULL); dns_sdb_unregister(&ldapdb); } }
{ "content_hash": "ac03265954be43fa13ed95a96759c7c3", "timestamp": "", "source": "github", "line_count": 692, "max_line_length": 118, "avg_line_length": 24.802023121387283, "alnum_prop": 0.6135873681757269, "repo_name": "execunix/vinos", "id": "7ed3325d3b5dd7dd6fa904b12be883bf39ec09b8", "size": "17163", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "external/bsd/bind/dist/contrib/sdb/ldap/ldapdb.c", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
angular.module('starter', ['ionic', 'starter.services', 'starter.controllers']) .config(function($stateProvider, $urlRouterProvider) { // Ionic uses AngularUI Router which uses the concept of states // Learn more here: https://github.com/angular-ui/ui-router // Set up the various states which the app can be in. // Each state's controller can be found in controllers.js $stateProvider // setup an abstract state for the tabs directive .state('tab', { url: "/tab", abstract: true, templateUrl: "templates/tabs.html" }) // the pet tab has its own child nav-view and history .state('tab.beer-index', { url: '/beers', views: { 'beers-tab': { templateUrl: 'templates/beer-index.html', controller: 'BeerIndexCtrl' } } }) .state('tab.beer-detail', { url: '/beer/:beerId', views: { 'beers-tab': { templateUrl: 'templates/beer-detail.html', controller: 'BeerDetailCtrl' } } }) .state('tab.adopt', { url: '/adopt', views: { 'adopt-tab': { templateUrl: 'templates/adopt.html' } } }) .state('tab.about', { url: '/about', views: { 'about-tab': { templateUrl: 'templates/about.html' } } }); // if none of the above states are matched, use this as the fallback $urlRouterProvider.otherwise('/tab/beers'); });
{ "content_hash": "3f11418620669b9f09b1d4fd3cc9b8ee", "timestamp": "", "source": "github", "line_count": 62, "max_line_length": 79, "avg_line_length": 23.903225806451612, "alnum_prop": 0.5634278002699056, "repo_name": "ashleyopie/ionicshellbetter", "id": "b49479d13f403966feedec5a0c7c396b5bbd9703", "size": "1845", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "www/js/app.js", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "181297" }, { "name": "JavaScript", "bytes": "1979647" } ], "symlink_target": "" }
using Bridge.Html5; using System; namespace Bridge.jQuery2 { public partial class jQuery { /// <summary> /// Retrieve the elements matched by the jQuery object. /// </summary> /// <returns></returns> public virtual Array Get() { return null; } /// <summary> /// Retrieve one of the elements matched by the jQuery object. /// </summary> /// <param name="index">A zero-based integer indicating which element to retrieve.</param> /// <returns></returns> public Element Get(int index) { return null; } /// <summary> /// Search for a given element from among the matched elements. /// </summary> /// <returns></returns> public virtual int Index() { return 0; } /// <summary> /// Search for a given element from among the matched elements. /// </summary> /// <param name="selector">The DOM element or first element within the jQuery object to look for.</param> /// <returns></returns> public virtual int Index(string selector) { return 0; } /// <summary> /// Search for a given element from among the matched elements. /// </summary> /// <param name="element">The DOM element or first element within the jQuery object to look for.</param> /// <returns></returns> public virtual int Index(Element element) { return 0; } /// <summary> /// Search for a given element from among the matched elements. /// </summary> /// <param name="element">The DOM element or first element within the jQuery object to look for.</param> /// <returns></returns> public virtual int Index(jQuery element) { return 0; } /// <summary> /// Retrieve all the elements contained in the jQuery set, as an array. /// </summary> /// <returns></returns> public virtual Array ToArray() { return null; } } }
{ "content_hash": "f6a87d9b35186ea0a516b89893e282b1", "timestamp": "", "source": "github", "line_count": 75, "max_line_length": 113, "avg_line_length": 29.253333333333334, "alnum_prop": 0.5314494074749316, "repo_name": "e-lefort/Frameworks", "id": "9d903b402a1e55e9eea391c590189f210e8fd9ae", "size": "2194", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "jQuery2/Miscellaneous/Dom.cs", "mode": "33261", "license": "mit", "language": [ { "name": "C#", "bytes": "923571" }, { "name": "HTML", "bytes": "234" }, { "name": "JavaScript", "bytes": "427909" } ], "symlink_target": "" }
@interface ViewController : UIViewController @end
{ "content_hash": "bbb98894d67453659af476a663e3fa3b", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 44, "avg_line_length": 10.6, "alnum_prop": 0.7924528301886793, "repo_name": "warmSunshine/MyUtilities", "id": "c89402fd55962d9bc6127012e4d312c3cb892edb", "size": "210", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "TestBlock/TestBlock/ViewController.h", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "48909" } ], "symlink_target": "" }
class CreateAuthTokens < ActiveRecord::Migration create_table :auth_tokens do |t| t.string :value t.integer :user_id t.datetime :expire_at t.timestamps end end
{ "content_hash": "b25630cb505dbd7d0cd857b2224f9b2f", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 48, "avg_line_length": 20.11111111111111, "alnum_prop": 0.6961325966850829, "repo_name": "soarpatriot/dream", "id": "28f61bc472004d2dcef636b3b5c64d1fc8fef57a", "size": "181", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "db/migrate/20141020150841_create_auth_tokens.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "3475" }, { "name": "Ruby", "bytes": "55813" } ], "symlink_target": "" }
/** @file MainGameScene.cpp */ #include "LevelInfo.h" #include "Scene.h" #include "Landscape.h" #include "../FontInfo.h" #include "../Audio.h" #include "../../OpenGLESApp2/OpenGLESApp2.Android.NativeActivity/Renderer.h" #include <boost/math/constants/constants.hpp> #include <array> #include <tuple> #include <algorithm> #include <random> #ifndef NDEBUG #ifdef __ANDROID__ #include "android_native_app_glue.h" #include <android/log.h> #define LOGI(...) ((void)__android_log_print(ANDROID_LOG_INFO, "SSU.MainGame", __VA_ARGS__)) #define LOGE(...) ((void)__android_log_print(ANDROID_LOG_ERROR, "SSU.MainGame", __VA_ARGS__)) #else #define LOGI(...) ((void)printf(__VA_ARGS__), (void)printf("\n")) #define LOGE(...) ((void)printf(__VA_ARGS__), (void)printf("\n")) #endif // __ANDROID__ #else #define LOGI(...) #define LOGE(...) #endif // NDEBUG // if activate this macro, the collision box of obstacles is displayed. //#define SSU_DEBUG_DISPLAY_COLLISION_BOX // Generate course seed instead of course info, and infinite to play main game. //#define SSU_GENERATE_COURSE_SEED namespace SunnySideUp { using namespace Mai; enum DirectionKey { DIRECTIONKEY_UP, DIRECTIONKEY_LEFT, DIRECTIONKEY_DOWN, DIRECTIONKEY_RIGHT, }; /** The additional function controller for debugging. This class uses only on debugging. It will disabled if NDEBUG macro is defined. */ struct DebugData { #ifndef NDEBUG DebugData() : debug(false) , dragging(false) , mouseX(-1) , mouseY(-1) , camera(Position3F(0, 0, 0), Vector3F(0, 0, -1), Vector3F(0, 1, 0)) { #ifdef SSU_DEBUG_DISPLAY_COLLISION_BOX collisionBoxList.reserve(64); #endif // SSU_DEBUG_DISPLAY_COLLISION_BOX } /// Clear all holding objects. void Clear() { #ifdef SSU_DEBUG_DISPLAY_COLLISION_BOX collisionBoxList.clear(); #endif // SSU_DEBUG_DISPLAY_COLLISION_BOX for (auto& e : debugObj) { e.reset(); } } /** Set the object to the debugging target. @param i The target index(0-2). Do nothing if it is invalid value. @param obj The object setting to (i)th debugging target. If (i)th already set, it will be overwritten. */ void SetDebugObj(size_t i, const ObjectPtr& obj) { if (i < debugObj.size()) { debugObj[i] = obj; } } /** Add collision box. @param r The renderer object. @param trans The translation of collision. @param rx, ry, rz The rotation of collision. @param scale The scaling of collision. Box shape has 1x1x1 size(it means that each axis have 0.5 length). So, (1, 1, 1) is given to scale, one vertex have (0.5, 0.5, 0.5) position. Add the collision box to the collision box list. The list is append by AppendCollsionBox() to the display object list. @sa AppendCollisionBox(). */ #ifdef SSU_DEBUG_DISPLAY_COLLISION_BOX void AddCollisionBoxShape(Renderer& r, const Vector3F& trans, float rx, float ry, float rz, const Vector3F& scale) { auto o = r.CreateObject("unitbox", Material(Color4B(255, 255, 255, 255), 0, 0), "default", ShadowCapability::Disable); o->SetTranslation(trans); o->SetRotation(rx, ry, rz); o->SetScale(scale); collisionBoxList.push_back(o); } #else void AddCollisionBoxShape(Renderer&, const Vector3F&, float, float, float, const Vector3F&) {} #endif // SSU_DEBUG_DISPLAY_COLLISION_BOX /** Append collsion box list to the display object list. @param objList The display object list. It will send to the Renderer. @sa AddCollisionBoxShape() */ #ifdef SSU_DEBUG_DISPLAY_COLLISION_BOX void AppendCollisionBox(std::vector<ObjectPtr>& objList) { objList.insert(objList.end(), collisionBoxList.begin(), collisionBoxList.end()); } #else void AppendCollisionBox(std::vector<ObjectPtr>&) {} #endif // SSU_DEBUG_DISPLAY_COLLISION_BOX /** Set the mouse button press information. @param mx The mouse cursor position on the X axis. @param my The mouse cursor position on the Y axis. */ void PressMouseButton(int mx, int my) { if (debug) { mouseX = mx; mouseY = my; dragging = true; } } /** Set the mouse buttion release information. */ void ReleaseMouseButton() { if (debug) { dragging = false; } } /** Set the mouse buttion move information. @param mx The mouse cursor position on the X axis. @param my The mouse cursor position on the Y axis. */ void MoveMouse(int mx, int my) { if (debug) { if (dragging) { const float x = static_cast<float>(mouseX - mx) * 0.005f; const float y = static_cast<float>(mouseY - my) * 0.005f; const Vector3F leftVector = camera.eyeVector.Cross(camera.upVector).Normalize(); camera.eyeVector = (Quaternion(camera.upVector, x) * Quaternion(leftVector, y)).Apply(camera.eyeVector).Normalize(); camera.upVector = Quaternion(leftVector, y).Apply(camera.upVector).Normalize(); } mouseX = mx; mouseY = my; } } /** Move the debug camera position. @param inputList The key information list for moving. It should have 4 elements. @sa DirectionKey */ void MoveCamera(const bool* inputList) { if (debug) { if (inputList[DIRECTIONKEY_UP]) { camera.position += camera.eyeVector * 0.25f; }; if (inputList[DIRECTIONKEY_DOWN]) { camera.position -= camera.eyeVector * 0.25f; } if (inputList[DIRECTIONKEY_LEFT]) { camera.position -= camera.eyeVector.Cross(camera.upVector) * 0.25f; } if (inputList[DIRECTIONKEY_RIGHT]) { camera.position += camera.eyeVector.Cross(camera.upVector) * 0.25f; } } } /** Update the state of all debug objects. @param r The renderer object. @param deltaTime The time from previous frame(unit:sec). */ bool Updata(Renderer& r, float deltaTime) { if (debug) { r.Update(deltaTime, camera.position, camera.eyeVector, camera.upVector); if (debugObj[0]) { Object& o = *debugObj[0]; static float rot = 90, accel = 0.0f; rot += accel; if (rot >= 360) { rot -= 360; } else if (rot < 0) { rot += 360; } static int target = 2; if (target == 0) { o.SetRotation(degreeToRadian<float>(rot), degreeToRadian<float>(0), degreeToRadian<float>(0)); } else if (target == 1) { o.SetRotation(degreeToRadian<float>(0), degreeToRadian<float>(rot), degreeToRadian<float>(0)); } else { o.SetRotation(degreeToRadian<float>(0), degreeToRadian<float>(0), degreeToRadian<float>(rot)); } } if (debugObj[1]) { Object& o = *debugObj[1]; static float roughness = 0, metallic = 0; o.SetRoughness(roughness); o.SetMetallic(metallic); } } return debug; } bool debug; bool dragging; int mouseX; int mouseY; Camera camera; std::array<ObjectPtr, 3> debugObj; #ifdef SSU_DEBUG_DISPLAY_COLLISION_BOX std::vector<ObjectPtr> collisionBoxList; #endif // SSU_DEBUG_DISPLAY_COLLISION_BOX #ifdef SHOW_DEBUG_SENSOR_OBJECT ObjectPtr debugSensorObj; #endif // SHOW_DEBUG_SENSOR_OBJECT #else void Clear() {} void SetDebugObj(size_t, const ObjectPtr&) {} void AddCollisionBoxShape(Renderer&, const Vector3F&, float, float, float, const Vector3F&) {} void AppendCollisionBox(std::vector<ObjectPtr>&) {} void PressMouseButton(int, int) {} void ReleaseMouseButton() {} void MoveMouse(int, int) {} void MoveCamera(const bool*) {} bool Updata(Renderer&, float) { return false; } #endif // NDEBUG }; static const Region region = { Position3F(-100, 200, -100), Position3F(100, 3800, 100) }; static const float unitRegionSize = 100.0f; static const size_t maxObject = 1000; static const float countDownTimerInitialTime = 3.5f; static const float countDownTimerStartTime = 3.0f; static const float countDownTimerTrailingTime = -1.0f; static const int goalHeight = 50; static const int unitObstructsSize = 100; static const int minObstructHeight = goalHeight + 150; static const int offsetTopObstructs = -500; static const int goalAreaRadius = 500; /** De Boor algorithm for B-Spline. @param k The counter of the recursion. At first, it shoud equal to 'degree'. @param degree The degree of B-Spline. @param i The interval of line. At first, it should be 'floor(x)'. @param x The position of line. It should be 1 to the size of 'points'. @param points The vector of the control point. It must have a size greater than 'degree'. @param The point in the current recursion. @note This is the internal function. Please call DeBoor() instead of this. */ Vector3F DeBoorI(int k, int degree, int i, float x, const std::vector<Vector3F>& points) { if (k == 0) { return points[std::max(0, std::min<int>(i, points.size() - 1))]; } const float alpha = (x - static_cast<float>(i)) / static_cast<float>(degree + 1 - k); const Vector3F a = DeBoorI(k - 1, degree, i - 1, x, points); const Vector3F b = DeBoorI(k - 1, degree, i, x, points); return a * (1.0f - alpha) + b * alpha; } /** De Boor algorithm for B-Spline. @param degree The degree of B-Spline. @param x The position of line. It should be 1 to the size of 'points'. @param points The vector of the control point. It must have a size greater than 'degree'. @param The point in the current recursion. */ Vector3F DeBoor(int degree, float x, const std::vector<Vector3F>& points) { const int i = static_cast<int>(x); return DeBoorI(degree, degree, i, x, points); } /** Create the degree 3 B-Spline curve. @param points The vector of the control point. It must have a size greater than 3. @param numOfSegments The division nunmber of the line. @return B-Spline curve. it will contain the 'numOfSegments' elements. */ std::vector<Position3F> CreateBSpline(const std::vector<Vector3F>& points, int numOfSegments) { std::vector<Position3F> v; v.reserve(numOfSegments); const float n = static_cast<float>(points.size() + 1); for (int i = 0; i < numOfSegments - 1; ++i) { const float ratio = static_cast<float>(i) / static_cast<float>(numOfSegments - 1); const float x = ratio * n + 1; const Vector3F pos = DeBoor(3, x, points); v.emplace_back(pos.x, pos.y, pos.z); } v.push_back(points.back().ToPosition3F()); return v; } /** Create the control points. @param start The first control point. @param goal The last control point. @param count The number of the control point with 'start' and 'goal'. @param random The random number generator. @param level The game level. This changes the control point allocation radius. @return B-Spline curve. It will contain the 'numOfSegments' elements. */ template<typename R> std::vector<Vector3F> CreateControlPoints(const Position3F& start, const Position3F& goal, int count, R& random, int level) { count = std::max(4, count); std::vector<Vector3F> v; v.reserve(count); v.emplace_back(start.x, start.y, start.z); const Vector3F distance = goal - start; Position3F center(0, 0, 0); std::uniform_real_distribution<float> tgen(0.0f, 360.0f); float range = 25.0f; const float additionalRange = level * level * level; for (int i = 1; i < count - 1; ++i) { const Position3F p = start + distance * static_cast<float>(i) / static_cast<float>(count - 1); const float theta = degreeToRadian(tgen(random)); float r = std::uniform_real_distribution<float>(0.0f, range)(random); const float tx = center.x + std::cos(theta) * r; const float tz = center.z + std::sin(theta) * r; v.emplace_back(p.x + tx, p.y, p.z + tz); Vector3F centerVector(-tx, 0, -tz); const float cr = std::normal_distribution<float>(1.0f, 1.0f)(random); center = Position3F(tx, 0, tz) + centerVector * cr; if (i < count / 2) { range = 150.0f + additionalRange; } else { range = 50.0f + additionalRange * 0.5f; } } v.emplace_back(goal.x, goal.y, goal.z); return v; } /** Create the model route. @param start The start point of the route. @param goal The end(goal) point of the route. @param random The random number generator. @param level The game level. This changes the control point allocation radius. @return The model route. This function creates the route based on B-Spline. At first, generate some control points at regular intervals. Then, generate more points at equal intervals on the curve. */ template<typename R> std::vector<Position3F> CreateModelRoute(const Position3F& start, const Position3F& goal, R& random, int level) { const int length = std::abs(static_cast<int>(goal.y - start.y)); const std::vector<Vector3F> controlPoints = CreateControlPoints(start, goal, (length + 499) / 500 + 2, random, level); return CreateBSpline(controlPoints, (length + 99) / 100); } /** Get the number of digits. @param n The number. Ignore after the decimal point. @return The number of digiets of the integral part. */ size_t GetNumberOfDigits(float n) { if (n != 0.0f && !std::isnormal(n)) { return 1; } int64_t i = static_cast<int64_t>(n); size_t num = 1; while (i >= 10) { ++num; i /= 10; } return num; } /** Convert the digits to string. @param n The digits. @param num The maximum number of digits. @param padding If true, do padding with zero. Otherwize not padding. @return The string converted from 'n'. */ std::string DigitsToString(float n, size_t num, bool padding) { std::string s; const size_t nod = GetNumberOfDigits(n); s.reserve(nod); int32_t nn = static_cast<int32_t>(n); if (n != 0.0f && !std::isnormal(n)) { nn = 0; } for (size_t i = 0; i < nod; ++i) { s.push_back(static_cast<char>(nn % 10) + '0'); nn /= 10; }; if (padding && nod < num) { const char pad = padding ? '0' : ' '; s.append(num - nod, pad); } std::reverse(s.begin(), s.end()); return s; } /** Control the main game play. Player start to fall down from the range of 4000m from 2000m. When player reaches 100m, it is success if the moving vector is facing within the range of target. Otherwise fail. */ class MainGameScene : public Scene { public: MainGameScene() : initialized(false) , hasTiltWarning(false) , pPartitioner() , random(static_cast<uint32_t>(time(nullptr))) , playerMovement(0, 0, 0) , playerRotation(0, 0, 0) , prevPlayerPos(0, 10000, 0) , countDownTimer(countDownTimerInitialTime) , stopWatch(0) , warningTransparency(0) , updateFunc(&MainGameScene::DoUpdate) , debugData() { directionKeyDownList.fill(false); } virtual ~MainGameScene() {} /** Load the game objects. @param engine The engine object. */ virtual bool Load(Engine& engine) { if (initialized) { status = STATUSCODE_RUNNABLE; return true; } directionKeyDownList.fill(false); Renderer& renderer = engine.GetRenderer(); pPartitioner.reset(new SpacePartitioner(region.min, region.max, unitRegionSize, maxObject)); const int level = std::min(GetMaximumLevel(), engine.GetCommonData<CommonData>()->level); const int courseNo = std::min(GetMaximumCourseNo(level), engine.GetCommonData<CommonData>()->courseNo); const CourseInfo& courseInfo = GetCourseInfo(level, courseNo); #ifdef SSU_GENERATE_COURSE_SEED static uint64_t debugCourseSeed = 0; ++debugCourseSeed; random.seed(debugCourseSeed); LOGI("Course seed: %lld", debugCourseSeed); #else random.seed(courseInfo.seed); LOGI("Course seed: %lld", courseInfo.seed); #endif // SSU_GENERATE_COURSE_SEED // Set a scene lighting information. { const TimeOfScene tos = [courseInfo]() { if (courseInfo.hoursOfDay >= 7 && courseInfo.hoursOfDay < 16) { return TimeOfScene_Noon; } else if (courseInfo.hoursOfDay >= 16 && courseInfo.hoursOfDay < 19) { return TimeOfScene_Sunset; } else { return TimeOfScene_Night; } }(); renderer.SetTimeOfScene(tos); renderer.DoesDrawSkybox(false); const Vector3F shadowDir = GetSunRayDirection(tos); const int level = std::min(GetMaximumLevel(), engine.GetCommonData<CommonData>()->level); const int courseNo = std::min(GetMaximumCourseNo(level), engine.GetCommonData<CommonData>()->courseNo); const float radius = static_cast<float>(GetCourseInfo(level, courseNo).startHeight) * 0.5f; renderer.SetShadowLight(Position3F(0, radius, 0) - shadowDir * radius, shadowDir, 100, radius * 3.0f, Vector2F(0.5f, 1.0f / 3.0f)); } // The player character. { auto obj = renderer.CreateObject("ChickenEgg", Material(Color4B(255, 255, 255, 255), 0, 0), "default"); Object& o = *obj; o.SetAnimation(renderer.GetAnimation("Dive")); const Vector3F trans(5, static_cast<GLfloat>(courseInfo.startHeight), 4.5f); o.SetTranslation(trans); playerRotation = Vector3F(degreeToRadian<float>(0), degreeToRadian<float>(180), degreeToRadian<float>(0)); o.SetRotation(playerRotation.x, playerRotation.y, playerRotation.z); //o.SetScale(Vector3F(5, 5, 5)); Collision::RigidBodyPtr p(new Collision::SphereShape(trans.ToPosition3F(), 3.0f, 0.1f)); //p->thrust = Vector3F(0, 9.8f, 0); pPartitioner->Insert(obj, p, Vector3F(0, 0, 0)); rigidCamera = p; objPlayer = obj; } // The target(as known as Flying-pan). { auto obj = renderer.CreateObject("FlyingPan", Material(Color4B(255, 255, 255, 255), 0, 0), "default"); Object& o = *obj; o.SetScale(Vector3F(courseInfo.targetScale, courseInfo.targetScale, courseInfo.targetScale)); const float theta = degreeToRadian<float>(RandomFloat(360)); const float distance = RandomFloat(goalAreaRadius); const float tx = std::cos(theta) * (distance * 2.0f + 10.0f); const float tz = std::sin(theta) * (distance + 20.0f); o.SetTranslation(Vector3F(tx, 40, tz)); pPartitioner->Insert(obj); objFlyingPan = obj; } { auto obj = renderer.CreateObject("TargetCursor", Material(Color4B(240, 2, 1, 255), 0, 0), "emission", ShadowCapability::Disable); Object& o = *obj; o.SetAnimation(renderer.GetAnimation("Rotation")); o.SetScale(Vector3F(courseInfo.targetScale, courseInfo.targetScale, courseInfo.targetScale) * 2); o.SetTranslation(objFlyingPan->Position() - Position3F(0, -10, 0)); pPartitioner->Insert(obj); } const Position3F startPosition(5, static_cast<float>(courseInfo.startHeight), 4.5f); { static const size_t posListSize = 5; const std::vector<Position3F> modelRoute = CreateModelRoute(startPosition, objFlyingPan->Position() + Vector3F(0, static_cast<float>(goalHeight), 0), random, level); const auto end = modelRoute.end() - 2; std::normal_distribution<float> normalDistributer(0, 2); const float step = static_cast<float>(unitObstructsSize) * std::max(1.0f, (4.0f - static_cast<float>(courseInfo.difficulty) * 0.5f)); const int density = std::min<int>(posListSize, courseInfo.density); for (float height = static_cast<float>(courseInfo.startHeight + offsetTopObstructs); height > static_cast<float>(minObstructHeight); height -= step) { auto itr = std::upper_bound(modelRoute.begin(), modelRoute.end(), height, [](float h, const Position3F& p) { return h > p.y; } ); if (itr >= end) { continue; } const Position3F& e = *itr; Vector3F axis(*(itr + 1) - e); axis.y = 0; if (axis.LengthSq() < 0.0001f) { axis.x = axis.z = 1.0f; } axis.Normalize(); axis *= RandomFloat(10) + 70.0f; const Vector3F posList[posListSize] = { Vector3F(e.x, e.y, e.z), Vector3F(e.x - axis.x, e.y, e.z - axis.z), Vector3F(e.x + axis.z, e.y, e.z - axis.x), Vector3F(e.x - axis.z, e.y, e.z + axis.x), Vector3F(e.x + axis.z, e.y, e.z + axis.x) }; for (int j = 0; j < density; ++j) { if (random() % 3 < 2) { auto obj = renderer.CreateObject("rock_s", Material(Color4B(255, 255, 255, 255), 0, 0), "default"); Object& o = *obj; const Vector3F trans = posList[j]; o.SetTranslation(trans); const float scale = 12.0f + normalDistributer(random); o.SetScale(Vector3F(scale, scale, scale)); const float rx = degreeToRadian<float>(RandomFloat(30)); const float ry = degreeToRadian<float>(RandomFloat(360)); const float rz = degreeToRadian<float>(RandomFloat(30)); o.SetRotation(rx, ry + degreeToRadian(45.0f), rz); const Vector3F collisionScale(Vector3F(0.625f, 1.25f, 0.625f) * scale); Collision::RigidBodyPtr p(new Collision::BoxShape(trans.ToPosition3F(), o.RotTrans().rot, collisionScale, scale * scale * scale * (5 * 6 * 5 / 3.0f))); o.SetRotation(rx, ry, rz); p->thrust = Vector3F(0, 9.8f, 0); pPartitioner->Insert(obj, p); debugData.AddCollisionBoxShape(renderer, trans, rx, ry + degreeToRadian(45.0f), rz, collisionScale * 2.0f); } else { auto obj = renderer.CreateObject("FlyingRock", Material(Color4B(255, 255, 255, 255), 0, 0), "default"); Object& o = *obj; const Vector3F trans = posList[j]; o.SetTranslation(trans); const float scale = 6; o.SetScale(Vector3F(scale, scale, scale)); const float rx = degreeToRadian<float>(RandomFloat(30)); const float ry = degreeToRadian<float>(RandomFloat(360)); const float rz = degreeToRadian<float>(RandomFloat(30)); o.SetRotation(rx, ry, rz); const Vector3F collisionScale(Vector3F(2.0f, 2.5f, 2.0f) * scale); Collision::RigidBodyPtr p(new Collision::BoxShape(trans.ToPosition3F(), o.RotTrans().rot, collisionScale, scale * scale * scale * (5 * 6 * 5 / 3.0f))); p->thrust = Vector3F(0, 9.8f, 0); pPartitioner->Insert(obj, p); debugData.AddCollisionBoxShape(renderer, trans, rx, ry, rz, collisionScale * 2.0f); } } } // add check points. checkPointList.reserve(courseInfo.startHeight / 1000 + 1); for (float height = static_cast<float>(courseInfo.startHeight) - 1100.0f; height > goalHeight + 500.0f; height -= 1000.0f) { auto itr = std::lower_bound(modelRoute.begin(), modelRoute.end(), height, [](const Position3F& p, float h) { return p.y >= h; } ); if (itr == modelRoute.end() || itr == modelRoute.begin()) { continue; } const Position3F& pos0 = *(itr - 1); // higher equal pos1 const Position3F& pos1 = *itr; // lower equal pos0 const Vector3F axis((pos1 - pos0)); Vector3F trans = Vector3F(pos0) + axis * ((pos0.y - height) / (pos0.y - pos1.y)); if (trans.x < 0) { trans.x += 20.0f; } else { trans.x -= 20.0f; } if (trans.z < 0) { trans.z += 20.0f; } else { trans.z -= 20.0f; } auto obj = renderer.CreateObject("CheckPoint", Material(Color4B(200, 200, 200, 255), 0.0f, 0.0f), "default", ShadowCapability::Disable); Object& o = *obj; o.SetScale(Vector3F(30, 30, 30)); o.SetTranslation(trans); pPartitioner->Insert(obj); checkPointList.push_back(CheckPoint(obj)); } #ifndef NDEBUG const float actualGoalHeight = objFlyingPan->Position().y + static_cast<float>(goalHeight); for (float height = static_cast<float>(courseInfo.startHeight); height > actualGoalHeight; height -= 50.0f) { auto itr = std::lower_bound(modelRoute.begin(), modelRoute.end(), height, [](const Position3F& p, float h) { return p.y >= h; } ); if (itr == modelRoute.end() || itr == modelRoute.begin()) { continue; } const Position3F& pos0 = *(itr - 1); // higher equal pos1 const Position3F& pos1 = *itr; // lower equal pos0 const Vector3F axis((pos1 - pos0)); const Vector3F trans = Vector3F(pos0) + axis * ((pos0.y - height) / (pos0.y - pos1.y)); auto obj = renderer.CreateObject("Sphere", Material(Color4B(200, 200, 200, 255), 0, 0), "default"); Object& o = *obj; o.SetTranslation(trans); const float scale = 2.0f; o.SetScale(Vector3F(scale, scale, scale)); pPartitioner->Insert(obj); } #endif // NDEBUG } // the slate block is generated around the line between the start and the goal. const Vector3F courseVector = startPosition - objFlyingPan->Position(); for (float height = static_cast<float>(courseInfo.startHeight + offsetTopObstructs); height > static_cast<float>(minObstructHeight); height -= static_cast<float>(unitObstructsSize) * 5) { const float h = RandomFloat(unitObstructsSize * 2) + static_cast<float>(unitObstructsSize) * 0.5f; const Position3F pos = objFlyingPan->Position() + courseVector * ((height + h - objFlyingPan->Position().y) / courseVector.y); auto obj = renderer.CreateObject("block1", Material(Color4B(255, 255, 255, 255), 0, 0), "default"); Object& o = *obj; const float theta = degreeToRadian<float>(RandomFloat(360)); const float distance = RandomFloat(150); const Vector3F trans(pos.x + std::cos(theta) * distance, height + h, pos.z + std::sin(theta) * distance); o.SetTranslation(trans); const float scale = 5.0f; o.SetScale(Vector3F(scale, scale, scale)); const float rx = degreeToRadian<float>(RandomFloat(90) - 45.0f); const float ry = degreeToRadian<float>(RandomFloat(360)); o.SetRotation(rx, ry, 0); const Vector3F collisionScale(Vector3F(4.8f, 0.375f, 3.8f) * scale); Collision::RigidBodyPtr p(new Collision::BoxShape(trans.ToPosition3F(), o.RotTrans().rot, collisionScale, 10 * 1 * 8)); p->thrust = Vector3F(0, 9.8f, 0); pPartitioner->Insert(obj, p); debugData.AddCollisionBoxShape(renderer, trans, rx, ry, 0, collisionScale * 2.0f); } #if 0 { auto obj = renderer.CreateObject("Accelerator", Material(Color4B(255, 255, 255, 255), 0, 0), "default"); Object& o = *obj; o.SetScale(Vector3F(5, 5, 5)); o.SetTranslation(Vector3F(-15, 120, 0)); o.SetRotation(degreeToRadian<float>(0), degreeToRadian<float>(0), degreeToRadian<float>(0)); pPartitioner->Insert(obj); } #endif const Landscape::ObjectList landscapeObjList = Landscape::GetCoast(renderer, Vector3F(0, 0, 100), 14.0f); for (auto& e : landscapeObjList) { pPartitioner->Insert(e); } // Add cloud. { for (int i = 0; i < 5; ++i) { const int cloudCount = ((i * i / 2 + 1) * courseInfo.cloudage) / courseInfo.maxCloudage; const int heightMax = 2600 - i * 400; const int heightMin = heightMax - 400; const int radiusMax = (i * i + 4) * 25; const int radiusMax2 = radiusMax * radiusMax; for (int j = 0; j < cloudCount; ++j) { static const char* const idList[] = { "cloud0", "cloud1", "cloud2", "cloud3" }; const int index = boost::random::uniform_int_distribution<>(0, 3)(random); const float y = static_cast<float>(boost::random::uniform_int_distribution<>(heightMin, heightMax)(random)); float r = static_cast<float>(boost::random::uniform_int_distribution<>(10, radiusMax)(random)); //r = radiusMax - r * r / radiusMax2; const float a0 = static_cast<float>(boost::random::uniform_int_distribution<>(0, 359)(random)); const float a1 = static_cast<float>(boost::random::uniform_int_distribution<>(30, 60)(random)); const float scale = boost::random::uniform_int_distribution<>(10, 30)(random) * 0.1f; static const GLubyte alphaList[] = { 64, 64, 96, 96, 96, 96, 96, 128, 128, 192 }; const int alphaIndex = boost::random::uniform_int_distribution<>(0, sizeof(alphaList)/sizeof(alphaList[0]) - 1)(random); static const GLubyte colorList[] = { 255, 224, 192 }; const int colorIndex = boost::random::uniform_int_distribution<>(0, sizeof(colorList) / sizeof(colorList[0]) - 1)(random); const GLubyte color = colorList[colorIndex]; auto obj = renderer.CreateObject(idList[index], Material(Color4B(color, color, color, alphaList[alphaIndex]), 0, 0), "cloud", ShadowCapability::Disable); Object& o = *obj; const Quaternion rot0(Vector3F(0, 1, 0), degreeToRadian<float>(a0)); const Quaternion rot1(Vector3F(0, 1, 0), degreeToRadian<float>(a0)); const Vector3F trans = rot0.Apply(Vector3F(0, y, r)); o.SetTranslation(trans); o.SetRotation(rot1); o.SetScale(Vector3F(scale, scale, scale)); pPartitioner->Insert(obj); } } } AudioInterface& audio = engine.GetAudio(); audio.LoadSE("bound", "Audio/bound.wav"); audio.LoadSE("success", "Audio/success.wav"); audio.LoadSE("failure", "Audio/miss.wav"); audio.LoadSE("wind", "Audio/wind.wav"); audio.LoadSE("countdown_3", "Audio/countdown_3.wav"); audio.LoadSE("countdown_2", "Audio/countdown_2.wav"); audio.LoadSE("countdown_1", "Audio/countdown_1.wav"); audio.LoadSE("countdown_go", "Audio/countdown_go.wav"); audio.PlayBGM("Audio/dive.mp3", 1.0f); status = STATUSCODE_RUNNABLE; initialized = true; return true; } /** Unload all game object. @param engine The engine object. */ virtual bool Unload(Engine& engine) { debugData.Clear(); rigidCamera.reset(); objPlayer.reset(); objFlyingPan.reset(); pPartitioner->Clear(); status = STATUSCODE_STOPPED; initialized = false; return true; } /** Process the window events. @param engine The engine object. @param e The window event. */ virtual void ProcessWindowEvent(Engine&, const Event& e) { switch (e.Type) { case Event::EVENT_MOUSE_BUTTON_PRESSED: if (e.MouseButton.Button == MOUSEBUTTON_LEFT) { debugData.PressMouseButton(e.MouseButton.X, e.MouseButton.Y); } break; case Event::EVENT_MOUSE_BUTTON_RELEASED: if (e.MouseButton.Button == MOUSEBUTTON_LEFT) { debugData.ReleaseMouseButton(); } break; case Event::EVENT_MOUSE_ENTERED: break; case Event::EVENT_MOUSE_LEFT: debugData.ReleaseMouseButton(); break; case Event::EVENT_MOUSE_MOVED: { debugData.MoveMouse(e.MouseMove.X, e.MouseMove.Y); break; } case Event::EVENT_KEY_PRESSED: switch (e.Key.Code) { case KEY_W: directionKeyDownList[DIRECTIONKEY_UP] = true; break; case KEY_S: directionKeyDownList[DIRECTIONKEY_DOWN] = true; break; case KEY_A: directionKeyDownList[DIRECTIONKEY_LEFT] = true; break; case KEY_D: directionKeyDownList[DIRECTIONKEY_RIGHT] = true; break; default: /* DO NOTING */ break; } break; case Event::EVENT_KEY_RELEASED: switch (e.Key.Code) { case KEY_W: directionKeyDownList[DIRECTIONKEY_UP] = false; break; case KEY_S: directionKeyDownList[DIRECTIONKEY_DOWN] = false; break; case KEY_A: directionKeyDownList[DIRECTIONKEY_LEFT] = false; break; case KEY_D: directionKeyDownList[DIRECTIONKEY_RIGHT] = false; break; default: /* DO NOTING */ break; } break; case Event::EVENT_TILT: { static const float offsetY = 0.2f; static const float margin = 0.05f; static const float scale = 20.f; const float tz = e.Tilt.Z; if (std::abs(tz) <= margin) { playerMovement.x = 0.0f; } else if (tz < 0.0f) { playerMovement.x = (tz + margin) * scale; } else { playerMovement.x = (tz - margin) * scale; } const float ty = e.Tilt.Y + offsetY; if (std::abs(ty) < margin) { playerMovement.z = 0.0f; } else if (ty < 0.0f) { playerMovement.z = -(ty + margin) * scale; } else { playerMovement.z = -(ty - margin) * scale; } break; } default: break; } } /** Update the state of all game objects. @param engine The engine object. @param deltaTime The time from previous frame(unit:sec). */ virtual int Update(Engine& engine, float deltaTime) { return (this->*updateFunc)(engine, deltaTime); } /** update game play. @param engine The engine object. @param e The window event. Transition to DoFadeOut() when the player character reached the target height. This is the update function called from Update(). */ int DoUpdate(Engine& engine, float deltaTime) { #if 1 debugData.MoveCamera(&directionKeyDownList[0]); //debugCamera.Update(deltaTime, fusedOrientation); const int prevCount = static_cast<int>(countDownTimer + 1.0f); if (countDownTimer >= countDownTimerTrailingTime) { countDownTimer -= deltaTime; } const int newCount = static_cast<int>(countDownTimer + 1.0f); if (prevCount != newCount) { static const char* const seNameList[] = { "countdown_go", "countdown_1", "countdown_2", "countdown_3", }; if (prevCount >= 1 && prevCount < sizeof(seNameList)/sizeof(seNameList[0]) + 1) { engine.GetAudio().PlaySE(seNameList[prevCount - 1], 1.0f); } } { const bool prevWarning = hasTiltWarning; hasTiltWarning = playerMovement.Length() >= 15.0f; if (prevWarning != hasTiltWarning) { warningTransparency = 0.0f; } else if (hasTiltWarning) { warningTransparency += deltaTime; while (warningTransparency > 1.0f) { warningTransparency -= 1.0f; } } } if (countDownTimer <= 0.0f) { if (objPlayer->Position().y >= goalHeight) { stopWatch += deltaTime; } #ifndef __ANDROID__ if (directionKeyDownList[DIRECTIONKEY_UP]) { rigidCamera->thrust.z = std::min(15.0f, rigidCamera->thrust.z - 1.0f); } else if (directionKeyDownList[DIRECTIONKEY_DOWN]) { rigidCamera->thrust.z = std::max(-15.0f, rigidCamera->thrust.z + 1.0f); } else { rigidCamera->thrust.z *= 0.9f; if (std::abs(rigidCamera->thrust.z) < 0.1) { rigidCamera->thrust.z = 0.0f; } } if (directionKeyDownList[DIRECTIONKEY_LEFT]) { rigidCamera->thrust.x = std::min(15.0f, rigidCamera->thrust.x - 1.0f); } else if (directionKeyDownList[DIRECTIONKEY_RIGHT]) { rigidCamera->thrust.x = std::max(-15.0f, rigidCamera->thrust.x + 1.0f); } else { rigidCamera->thrust.x *= 0.9f; if (std::abs(rigidCamera->thrust.x) < 0.1) { rigidCamera->thrust.x = 0.0f; } } rigidCamera->thrust.y = 0.0f; if (rigidCamera->accel.y < 0.0f) { rigidCamera->thrust.y = std::min(-rigidCamera->accel.y, std::max(0.0f, rigidCamera->thrust.Length() * 0.5f)); } playerRotation.x = std::min(0.5f, std::max(-0.5f, rigidCamera->thrust.z * -0.05f)); playerRotation.z = std::min(0.5f, std::max(-0.5f, rigidCamera->thrust.x * -0.05f)); objPlayer->SetRotation(playerRotation.x, playerRotation.y, playerRotation.z); #else rigidCamera->thrust = playerMovement; rigidCamera->thrust.y = 0.0f; if (rigidCamera->accel.y < 0.0f) { rigidCamera->thrust.y = std::min(-rigidCamera->accel.y * 0.25f, std::max(0.0f, rigidCamera->thrust.Length() * 0.5f)); } playerRotation.x = std::min(0.5f, std::max(-0.5f, playerMovement.z * -0.05f)); playerRotation.z = std::min(0.5f, std::max(-0.5f, playerMovement.x * -0.05f)); objPlayer->SetRotation(playerRotation.x, playerRotation.y, playerRotation.z); #endif // __ANDROID__ if (DidPassCheckPoint()) { engine.GetAudio().PlaySE("wind", 1.0f); rigidCamera->accel += Normalize(rigidCamera->accel) * 75.0f; LOGI("Pass CheckPoint"); } } pPartitioner->Update(deltaTime); if (rigidCamera && rigidCamera->hasLatestCollision && rigidCamera->accel.LengthSq() > (2.0f * 2.0f)) { engine.GetAudio().PlaySE("bound", 1.0f); } #else const Position3F prevCamPos = debugCamera.Position(); debugCamera.Update(deltaTime, fusedOrientation); Vector3F camVec = debugCamera.Position() - prevCamPos; if (rigidCamera) { if (camVec.LengthSq() == 0.0f) { Vector3F v = rigidCamera->accel; v.y = 0; if (v.LengthSq() < 0.1f) { v = Vector3F::Unit(); } else { v.Normalize(); v *= 0.1f; } rigidCamera->accel -= v; } else { rigidCamera->accel = camVec * 10.0f; } if (rigidCamera->Position().y < 5.0f && debugCamera.Direction() == TouchSwipeCamera::MoveDir_Back) { debugCamera.Direction(TouchSwipeCamera::MoveDir_Newtral); rigidCamera->Position(Position3F(0, 4000, 0)); } } pPartitioner->Update(engine.deltaTime); if (rigidCamera) { Position3F pos = rigidCamera->Position(); pos.y += 10.0f; debugCamera.Position(pos); } #endif Renderer& renderer = engine.GetRenderer(); if (!debugData.Updata(renderer, deltaTime)) { renderer.Update(deltaTime, rigidCamera->Position() + Vector3F(0, 20, -2), Vector3F(0, -1, 0), Vector3F(0, 0, -1)); // for (auto&& e : engine.obj) { // e.Update(engine.deltaTime); // while (e.GetCurrentTime() >= 1.0f) { // e.SetCurrentTime(e.GetCurrentTime() - 1.0f); // } // } } renderer.SetBlurScale(1.0f + std::max(0.0f, std::abs(rigidCamera->accel.y) - 100.0f) * 0.001f); #if 0 static float roughness = 1.0f; static float step = 0.005; obj[1].SetRoughness(roughness); roughness += step; if (roughness >= 1.0) { step = -0.005f; } else if (roughness <= 0.0) { step = 0.005f; } #endif if (objPlayer->Position().y <= goalHeight) { AudioInterface& audio = engine.GetAudio(); audio.StopBGM(5.0f); renderer.FadeOut(Color4B(0, 0, 0, 0), 1.0f); updateFunc = &MainGameScene::DoFadeOut; } return SCENEID_CONTINUE; } /** Do fade out. @param engine The engine object. @param deltaTime The time from previous frame(unit:sec). Transition to the scene of the success/failure event when the fadeout finished. This is the update function called from Update(). */ int DoFadeOut(Engine& engine, float deltaTime) { Renderer& renderer = engine.GetRenderer(); if (!debugData.Updata(renderer, deltaTime)) { renderer.Update(deltaTime, rigidCamera->Position() + Vector3F(0, 20, -2), Vector3F(0, -1, 0), Vector3F(0, 0, -1)); } if (renderer.GetCurrentFilterMode() == Renderer::FILTERMODE_NONE) { engine.GetCommonData<CommonData>()->currentTime = static_cast<int64_t>(stopWatch * 1000.0f); renderer.FadeIn(1.0f); #ifdef SSU_GENERATE_COURSE_SEED return SCENEID_MAINGAME; #else const float scale = objFlyingPan->Scale().x; const Vector3F v = objPlayer->Position() - objFlyingPan->Position(); const float distance = std::sqrt(v.x * v.x + v.z * v.z); if (distance <= 1.25f * scale) { AudioInterface& audio = engine.GetAudio(); audio.PlayBGM("Audio/fryingegg.mp3", 1.0f); audio.SetBGMLoopFlag(false); audio.PlaySE("success", 1.0f); return SCENEID_SUCCESS; } engine.GetAudio().PlaySE("failure", 1.0f); return SCENEID_FAILURE; #endif // SSU_GENERATE_COURSE_SEED } return SCENEID_CONTINUE; } /** Draw all game objects. @param engine The engine object. */ virtual void Draw(Engine& engine) { std::vector<ObjectPtr> objList; objList.reserve(10 * 10); #if 0 float posY = debugCamera.Position().y; if (debugCamera.EyeVector().y >= 0.0f) { posY = std::max(region.min.y, posY - unitRegionSize * 2); for (int i = 0; i < 6; ++i) { const Cell& cell = pPartitioner->GetCell(posY); for (auto& e : cell.objects) { objList.push_back(e.object); } posY += unitRegionSize; if (posY >= region.max.y) { break; } } } else { posY = std::min(region.max.y, posY + unitRegionSize * 2); for (int i = 0; i < 6; ++i) { const Cell& cell = pPartitioner->GetCell(posY); for (auto& e : cell.objects) { objList.push_back(e.object); } posY -= unitRegionSize; if (posY < region.min.y) { break; } } } const Position3F eyePos = debugCamera.Position(); const Vector3F eyeVec = debugCamera.EyeVector(); objList.erase( std::remove_if( objList.begin(), objList.end(), [eyePos, eyeVec](const ObjectPtr& n) { const Vector3F tmp = n->Position() - eyePos; return (tmp.LengthSq() > 15.0f * 15.0f) && (eyeVec.Dot(Vector3F(tmp).Normalize()) < 0.0f); } ), objList.end() ); std::sort( objList.begin(), objList.end(), [eyePos](const ObjectPtr& lhs, const ObjectPtr& rhs) { const Vector3F v0 = lhs->Position() - eyePos; const Vector3F v1 = rhs->Position() - eyePos; return v0.LengthSq() < v1.LengthSq(); } ); #else for (auto itr = pPartitioner->Begin(); itr != pPartitioner->End(); ++itr) { for (auto& e : itr->objects) { objList.push_back(e.object); } } #endif debugData.AppendCollisionBox(objList); #ifdef SHOW_DEBUG_SENSOR_OBJECT { Position3F pos = debugCamera.Position(); const Vector3F ev = debugCamera.EyeVector(); const Vector3F uv = debugCamera.UpVector(); const Vector3F sv = ev.Cross(uv); pos += ev * 4.0f; pos += -uv * 1.5f; pos += sv * 0.9f; debugSensorObj->SetTranslation(Vector3F(pos.x, pos.y, pos.z)); // fusedOrientation has each axis range of x(+pi, -pi), y(+pi/2, -pi/2), z(+pi, -pi). const float rx = (fusedOrientation.x + boost::math::constants::pi<float>()) * 0.5f; const float ry = -fusedOrientation.y + boost::math::constants::pi<float>() * 0.5f; const float rz = (fusedOrientation.z + boost::math::constants::pi<float>()) * 0.5f; Matrix4x4 mRot = LookAt(Position3F(0, 0, 0), Position3F(ev.x, ev.y, ev.z), uv); mRot = Matrix4x4::RotationX(rx) * Matrix4x4::RotationX(ry) * Matrix4x4::RotationX(rz) * mRot; Quaternion q; mRot.Decompose(&q, nullptr, nullptr); debugSensorObj->SetRotation(q); objList.push_back(debugSensorObj); } #endif // SHOW_DEBUG_SENSOR_OBJECT Renderer& renderer = engine.GetRenderer(); if (rigidCamera) { static float numberFontScale = 0.8f; static float fontScale = 2.0f / 3.0f; static float uw = 1.0f / 12.0f / fontScale; static float cw = 1.0f / 20.0f; static float cw0 = 1.0f / 20.0f; static float baseX = 0.75f; { const float n = std::abs(rigidCamera->accel.y) * 3.6f; const float nod = static_cast<float>(GetNumberOfDigits(n)); const std::string s = DigitsToString(n, 3, false); renderer.AddString(baseX - cw * nod, 0.05f, numberFontScale, Color4B(255, 255, 255, 255), s.c_str(), Renderer::FONTOPTION_OUTLINE, uw); renderer.AddString(baseX, 0.055f, fontScale, Color4B(255, 255, 255, 255), "Km/h", Renderer::FONTOPTION_OUTLINE); } { float y = objPlayer->Position().y; if (auto radius = rigidCamera->GetRadius()) { y -= *radius; } const float nod = static_cast<float>(GetNumberOfDigits(y)); const std::string s = DigitsToString(y, 4, false); renderer.AddString(baseX - cw * (nod - 1.0f), 0.1f, numberFontScale, Color4B(255, 255, 255, 255), s.c_str(), Renderer::FONTOPTION_OUTLINE, uw); renderer.AddString(baseX + cw0, 0.105f, fontScale, Color4B(255, 255, 255, 255), "M", Renderer::FONTOPTION_OUTLINE); } { const float nod = static_cast<float>(GetNumberOfDigits(stopWatch)); const std::string s = DigitsToString(stopWatch, 3, false); renderer.AddString(baseX - cw * (nod + 2.5f), 0.15f, numberFontScale, Color4B(255, 255, 255, 255), s.c_str(), Renderer::FONTOPTION_OUTLINE, uw); renderer.AddString(baseX - cw * 2.5f, 0.15f, fontScale, Color4B(255, 255, 255, 255), ".", Renderer::FONTOPTION_OUTLINE); } { const float pointDecimal = (stopWatch - std::floor(stopWatch)) * 1000.0f; const std::string s = DigitsToString(pointDecimal, 3, true); renderer.AddString(baseX - cw * 2.0f, 0.15f, numberFontScale, Color4B(255, 255, 255, 255), s.c_str(), Renderer::FONTOPTION_OUTLINE, uw); renderer.AddString(baseX + cw0, 0.155f, fontScale, Color4B(255, 255, 255, 255), "Sec", Renderer::FONTOPTION_OUTLINE); } { CommonData& commonData = *engine.GetCommonData<CommonData>(); std::string s = DigitsToString(commonData.level + 1, 1, false); s += "-"; s += DigitsToString(commonData.courseNo + 1, 1, false); renderer.AddString(0.05f, 0.05f, numberFontScale, Color4B(255, 255, 255, 255), s.c_str(), Renderer::FONTOPTION_OUTLINE, uw); } { CommonData& commonData = *engine.GetCommonData<CommonData>(); const std::string s(std::max(0, std::min(sizeOfEggPack, commonData.remainingEggs - 1)), static_cast<char>(EMOJIFONTID_EGG)); renderer.AddString(0.05f, 0.95f, numberFontScale, Color4B(255, 255, 255, 255), s.c_str(), Renderer::FONTOPTION_KEEPCOLOR, uw); } if (countDownTimer > 0.0f) { static const char strReady[] = "READY!"; static const char* const strNumber[] = { "1", "2", "3" }; renderer.AddString(0.5f - renderer.GetStringWidth(strReady), 0.3f, 2.0f, Color4B(255, 240, 200, 255), strReady, Renderer::FONTOPTION_OUTLINE); if (countDownTimer < countDownTimerStartTime) { const int index = static_cast<int>(countDownTimer); float dummy; const float scale = 4.0f - std::modf(countDownTimer, &dummy) * 2.0f; const float w = renderer.GetStringWidth(strNumber[index]) * 0.5f * scale; const float h = renderer.GetStringHeight(strNumber[index]) * 0.5f * scale; const GLbyte a = static_cast<GLbyte>(255.0f * (2.0f - scale * 0.5f)); renderer.AddString(0.5f - w, 0.5f - h, scale, Color4B(255, 255, 255, a), strNumber[index], Renderer::FONTOPTION_OUTLINE); } } else if (countDownTimer > countDownTimerTrailingTime) { static const char str[] = "GO!"; const float scale = 2.0f + (-countDownTimer / -countDownTimerTrailingTime) * 3.0f; const float w = renderer.GetStringWidth(str) * 0.5f * scale; const float h = renderer.GetStringHeight(str) * 0.5f * scale; const GLbyte a = static_cast<GLbyte>(255.0f * (1.0f - (scale - 2.0f) / 3.0f)); renderer.AddString(0.5f - w, 0.5f - h, scale, Color4B(255, 200, 155, a), str, Renderer::FONTOPTION_OUTLINE); } if (hasTiltWarning) { static const char strTiltWarning[] = "TURN HORIZONTALLY"; const uint8_t alpha = static_cast<uint8_t>((warningTransparency < 0.5f ? warningTransparency : 1.0f - warningTransparency) * 255.0f * 2.0f); renderer.AddString(0.5f - renderer.GetStringWidth(strTiltWarning) * 0.4f, 0.75f, 0.8f, Color4B(240, 16, 32, alpha), strTiltWarning); } } renderer.Render(&objList[0], &objList[0] + objList.size()); } private: void InsertObject( const ObjectPtr& obj, const Collision::RigidBodyPtr& c = Collision::RigidBodyPtr(), const Vector3F& offset = Vector3F::Unit() ) { if (pPartitioner) { pPartitioner->Insert(obj, c, offset); } } template<typename T> float RandomFloat(T n) { return static_cast<float>(std::uniform_int_distribution<>(0, static_cast<int>(n))(random)); } struct CheckPoint { explicit CheckPoint(ObjectPtr& o) : obj(o), checked(false) {} ObjectPtr obj; bool checked; }; bool DidPassCheckPoint() { const Position3F playerPos = objPlayer->Position(); for (CheckPoint& e : checkPointList) { if (!e.checked) { const Position3F targetPos = e.obj->Position(); if (prevPlayerPos.y >= targetPos.y && playerPos.y < targetPos.y) { const Position3F tmpPlayerPos = prevPlayerPos + (playerPos - prevPlayerPos) * ((prevPlayerPos.y - targetPos.y) / (prevPlayerPos.y - playerPos.y)); Vector3F distance = targetPos - tmpPlayerPos; distance.y = 0; if (distance.LengthSq() < 32.0f * 32.0f) { e.checked = true; prevPlayerPos = playerPos; return true; } } } } prevPlayerPos = playerPos; return false; } private: bool initialized; bool hasTiltWarning; std::unique_ptr<SpacePartitioner> pPartitioner; boost::random::mt19937 random; Collision::RigidBodyPtr rigidCamera; ObjectPtr objPlayer; ObjectPtr objFlyingPan; Vector3F playerMovement; Vector3F playerRotation; Position3F prevPlayerPos; std::vector<CheckPoint> checkPointList; float countDownTimer; float stopWatch; float warningTransparency; int(MainGameScene::*updateFunc)(Engine&, float); std::array<bool, 4> directionKeyDownList; DebugData debugData; }; /** Create MainGameScene object. @param engine The engine object. @return MainGameScene object. */ ScenePtr CreateMainGameScene(Engine&) { return ScenePtr(new MainGameScene); } } // namespace SunnySideUp
{ "content_hash": "e4abdefc3f4eabf04e50c2ddd0f0e0b9", "timestamp": "", "source": "github", "line_count": 1315, "max_line_length": 190, "avg_line_length": 35.79543726235742, "alnum_prop": 0.6651228994497673, "repo_name": "tn-mai/NDKOpenGLES2App", "id": "da6c8edd1db78d645d0256aac215672894a9a939", "size": "47071", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Shared/Scenes/MainGameScene.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "5437" }, { "name": "C", "bytes": "29277" }, { "name": "C++", "bytes": "442503" }, { "name": "GLSL", "bytes": "44234" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Reflection; using System.Threading.Tasks; using Cheetah.DataAccess.Interfaces; using Cheetah.DataAccess.Interfaces.Base; using Cheetah.DataAccess.Repositories.Base; using Cheetah.DataAccess.Models; using PetaPoco; namespace Cheetah.DataAccess.Repositories.Base { abstract class OwnableRepository<TKey, TOwner, TValue> : Repository<TKey, TValue>, IOwnableRepository<TKey, TOwner, TValue> where TValue : class, new() { protected OwnableRepository() { SetOwnerPropertyName("CreatedBy"); SetDefaultSortOrder(CreatedAtProperty.Name, "DESC"); } #region IAsyncOwnableRepository implementation #region Convention Tools public string OwnerKeyName { get; set; } public PropertyInfo OwnerProperty { get; set; } public void SetOwnerPropertyName(string ownerPropertyName) { OwnerKeyName = ownerPropertyName; OwnerProperty = GetPropertyInfo<TValue>(ownerPropertyName); } #endregion public ICollection<TValue> ListByOwner(TOwner ownerKey) { return Database.Fetch<TValue>($"WHERE {OwnerKeyName}=@0 {DefaultSortOrder}", ownerKey); } #endregion } }
{ "content_hash": "32e94ca5167af8404e7276e838249956", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 99, "avg_line_length": 28.404255319148938, "alnum_prop": 0.6666666666666666, "repo_name": "LarsVonQualen/cheetah", "id": "660b520a23e8fff3bf02cc5bed0fc0c624896da2", "size": "1337", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "cheetah.api/CheetahApi/Cheetah.DataAccess/Repositories/Base/OwnableRepository.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "357502" }, { "name": "CSS", "bytes": "5208" }, { "name": "HTML", "bytes": "15041" }, { "name": "JavaScript", "bytes": "6426" }, { "name": "TypeScript", "bytes": "32906" } ], "symlink_target": "" }
layout: default title: CAS - Protocol Overview category: Protocols --- {% include variables.html %} # Protocols Overview The following protocols are supported and provided by CAS: * [CAS](CAS-Protocol.html) * [OAuth](OAuth-Protocol.html) * [OpenID Connect](OIDC-Protocol.html) * [WS Federation](WS-Federation-Protocol.html) * [SAML1](SAML-Protocol.html) * [SAML2](../authentication/Configuring-SAML2-Authentication.html) * [REST Protocol](REST-Protocol.html) ## Design CAS presents itself as a multilingual platform supporting protocols such as CAS, SAML2, OAuth2 and OpenID Connect, etc. Support and functionality for each of these protocols continually improves per every iteration and release of the software thanks to excellent community feedback and adoption. While almost all such protocols are similar in nature and intention, they all have their own specific bindings, parameters, payload and security requirements. This section provides a quick introduction on how existing protocols are supported in CAS. It all starts with something rather trivial: The Bridge. ### The Bridge The bridge *design pattern* is an approach where an intermediary sits between the client and the server, translating requests back and forth. It acts as a link between the two sides allowing authentication requests from the client to be translated, massaged and transformed and then routed "invisibly" to CAS and then back. This is a neat trick because the client does not care how the authentication request is processes once it's submitted. The *thing* that receives that request, acting as a bridge can do anything required to process that request and ultimately submitting some sort of response back to the client. The bridge also does not care what external authentication system handles and honors that request and how all that processing internally works. All the bridge cares about is, "I routed the request to X. As long as X gives me back the right stuff, I should be fine to resume". So the bridge for the most part is the "control tower" of the operation. It speaks many languages and protocols, and just like any decent translator, it knows about the quirks and specifics of each language and as such is able to dynamically translate the technical lingo. ### Supported Protocols If you understand the above strategy, then you would be glad to learn that *almost* all protocols supported by CAS operate with the same exact intentions. A given CAS deployment is equipped with embedded plugins/bridges/modules that know how to speak SAML2 and CAS, OAuth2 and CAS, or OpenID Connect and CAS or whatever. The right-hand side of that equation is always CAS when you consider, as an example, the following authentication flow with an OAuth2-enabled client application: 1. The CAS deployment has turned on the OAuth2 plugin. 2. An OAuth2 authorization request is submitted to the relevant CAS endpoint. 3. The OAuth2 plugin verifies the request and translates it to a CAS authentication request! 4. The authentication request is routed to the relevant CAS login endpoint. 5. User authenticates and CAS routes the flow back to the OAuth2 plugin, having issued a service ticket for the plugin. 6. The OAuth2 plugin attempts to validate that ticket to retrieve the necessary user profile and attributes. 7. The OAuth2 plugin then proceeds to issue the right OAuth2 response by translating and transforming the profile and validated assertions into what the client application may need. <div class="alert alert-info"><strong>Note</strong><p>The above strategy applies exactly the same, if CAS decides to delegate the authentication to an external identity provider such as Facebook or a SAML2 identity provider.</p></div> The right-hand side of the flow is always CAS, because the plugin always translates protocol requests into CAS requests. Another way of looking at it is that all protocol plugins and modules are themselves clients of the CAS server! They are issued service tickets and they proceed to validate them just like any other CAS-enabled client. Just like above, to the OAuth2-enabled client all such details are totally transparent and as long as “the right stuff” is produced back to the client, it shall not care. There are some internal technical and architectural advantages to this approach. Namely: The core of the CAS authentication engine, flow and components need not be modified at all. After all, we are just integrating yet another client even if it’s embedded directly in CAS itself. Because of that, support for that protocol can be very easily removed, if needed. After all, protocols come and go every day. Finally and just like any other CAS client, all features of the CAS server are readily available and translated to the relevant client removing the need to duplicate and re-create protocol-specific configuration as much as possible. Things like access strategies, attribute release, username providers, etc.
{ "content_hash": "664096cc105b5225de9d487e3664d869", "timestamp": "", "source": "github", "line_count": 52, "max_line_length": 626, "avg_line_length": 95.53846153846153, "alnum_prop": 0.8011272141706924, "repo_name": "apereo/cas", "id": "861601694444de8483e4ee9c9edd37938c8ed73d", "size": "4978", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/cas-server-documentation/protocol/Protocol-Overview.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "16679" }, { "name": "Dockerfile", "bytes": "1207" }, { "name": "Groovy", "bytes": "63590" }, { "name": "HTML", "bytes": "385378" }, { "name": "Java", "bytes": "20049652" }, { "name": "JavaScript", "bytes": "642995" }, { "name": "Mustache", "bytes": "1946" }, { "name": "PHP", "bytes": "33936" }, { "name": "Python", "bytes": "20629" }, { "name": "Ruby", "bytes": "2628" }, { "name": "Shell", "bytes": "165922" } ], "symlink_target": "" }
package org.examples.designpatterns.factory; public class OperationMul implements Operation { /** * 乘法运算 */ @Override public double getResult(double numberA, double numberB) { return numberA * numberB; } }
{ "content_hash": "9eb284ced02488a02b1f373021ada3c6", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 58, "avg_line_length": 16.857142857142858, "alnum_prop": 0.6779661016949152, "repo_name": "Dustfate/examples", "id": "defb0d611894b17ecbfaf28afe9e4021c9cc8e0f", "size": "244", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "examples-designpatterns/src/main/java/org/examples/designpatterns/factory/OperationMul.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "1727704" }, { "name": "HTML", "bytes": "4825082" }, { "name": "Java", "bytes": "1366002" }, { "name": "JavaScript", "bytes": "6405592" }, { "name": "PHP", "bytes": "3916" } ], "symlink_target": "" }
from rdkit import RDConfig from rdkit import Chem import sys,csv def Convert(suppl,outFile,keyCol='',stopAfter=-1,includeChirality=0,smilesFrom=''): w = csv.writer(outFile) mol = suppl[0] propNames = list(mol.GetPropNames()) if keyCol and keyCol in propNames: propNames.remove(keyCol) outL = [] if keyCol: outL.append(keyCol) outL.append('SMILES') outL.extend(propNames) w.writerow(outL) nDone = 0 for mol in suppl: if not mol: continue if not smilesFrom or not mol.HasProp(smilesFrom): smi = Chem.MolToSmiles(mol,includeChirality) else: smi = mol.GetProp(smilesFrom) tMol = Chem.MolFromSmiles(smi) smi = Chem.MolToSmiles(tMol,includeChirality) outL = [] if keyCol: outL.append(str(mol.GetProp(keyCol))) outL.append(smi) for prop in propNames: if mol.HasProp(prop): outL.append(str(mol.GetProp(prop))) else: outL.append('') w.writerow(outL) nDone += 1 if nDone == stopAfter: break return #------------------- # Testing: import unittest class TestCase(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test1(self): import os from cStringIO import StringIO fName = os.path.join(RDConfig.RDDataDir,'NCI','first_200.props.sdf') suppl = Chem.SDMolSupplier(fName) io = StringIO() try: Convert(suppl,io) except: import traceback traceback.print_exc() self.fail('conversion failed') txt = io.getvalue() lines = txt.split('\n') if not lines[-1]: del lines[-1] self.failUnless(len(lines)==201,'bad num lines: %d'%len(lines)) line0 = lines[0].split(',') self.failUnlessEqual(len(line0),19) self.failUnless(line0[0]=='SMILES') def test2(self): import os from cStringIO import StringIO fName = os.path.join(RDConfig.RDDataDir,'NCI','first_200.props.sdf') suppl = Chem.SDMolSupplier(fName) io = StringIO() try: Convert(suppl,io,keyCol='AMW',stopAfter=5) except: import traceback traceback.print_exc() self.fail('conversion failed') txt = io.getvalue() lines = txt.split('\n') if not lines[-1]: del lines[-1] self.failUnless(len(lines)==6,'bad num lines: %d'%len(lines)) line0 = lines[0].split(',') self.failUnlessEqual(len(line0),19) self.failUnless(line0[0]=='AMW') self.failUnless(line0[1]=='SMILES') #------------------- # CLI STuff: def Usage(): message = """ Usage: SDFToCSV [-k keyCol] inFile.sdf [outFile.csv] """ sys.stderr.write(message) sys.exit(-1) if __name__=='__main__': import getopt try: args,extras = getopt.getopt(sys.argv[1:],'hk:', ['test', 'chiral', 'smilesCol=', ]) except: import traceback traceback.print_exc() Usage() keyCol = '' testIt = 0 useChirality=0 smilesCol='' for arg,val in args: if arg=='-k': keyCol = val elif arg=='--chiral': useChirality=1 elif arg=='--smilesCol': smilesCol=val elif arg=='--test': testIt=1 elif arg=='-h': Usage() if not testIt and len(extras)<1: Usage() if not testIt: inFilename = extras[0] if len(extras)>1: outFilename = extras[1] outF = open(outFilename,'w+') else: outF = sys.stdout suppl = Chem.SDMolSupplier(inFilename) Convert(suppl,outF,keyCol=keyCol,includeChirality=useChirality,smilesFrom=smilesCol) else: sys.argv = [sys.argv[0]] unittest.main()
{ "content_hash": "34a915ca49ee44beae9c675b5ed1f737", "timestamp": "", "source": "github", "line_count": 159, "max_line_length": 88, "avg_line_length": 23.150943396226417, "alnum_prop": 0.5908720456397718, "repo_name": "rdkit/rdkit-orig", "id": "7dfa514d8d81d71eeee5754c8e8743f93fd02ded", "size": "3961", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "rdkit/Chem/ChemUtils/SDFToCSV.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "317825" }, { "name": "C#", "bytes": "6745" }, { "name": "C++", "bytes": "4903579" }, { "name": "FORTRAN", "bytes": "7661" }, { "name": "Java", "bytes": "232201" }, { "name": "JavaScript", "bytes": "12734" }, { "name": "Objective-C", "bytes": "26015" }, { "name": "Perl", "bytes": "5919" }, { "name": "Prolog", "bytes": "389" }, { "name": "Python", "bytes": "2698794" }, { "name": "Shell", "bytes": "10661" } ], "symlink_target": "" }
package org.search.nibrs.stagingdata.model; import java.time.LocalDate; import java.util.List; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import org.search.nibrs.stagingdata.model.search.IncidentSearchRequest; import org.search.nibrs.stagingdata.util.DateUtils; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @JsonIgnoreProperties(ignoreUnknown=true) public class SubmissionTrigger { private List<String> oris; private List<Integer> agencyIds; private Integer startYear; private Integer startMonth; private Integer endYear; private Integer endMonth; public SubmissionTrigger() { super(); } public SubmissionTrigger(IncidentSearchRequest incidentSearchRequest) { super(); if (incidentSearchRequest.getAgencyIds() != null && incidentSearchRequest.getAgencyIds().size() > 0) { this.agencyIds = incidentSearchRequest.getAgencyIds(); } this.startYear = incidentSearchRequest.getSubmissionStartYear(); this.endYear = incidentSearchRequest.getSubmissionEndYear(); this.startMonth = incidentSearchRequest.getSubmissionStartMonth(); this.endMonth = incidentSearchRequest.getSubmissionEndMonth(); } public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); } public List<String> getOris() { return oris; } public void setOris(List<String> oris) { this.oris = oris; } public Integer getStartYear() { return startYear; } public void setStartYear(Integer startYear) { this.startYear = startYear; } public Integer getStartMonth() { return startMonth; } public void setStartMonth(Integer startMonth) { this.startMonth = startMonth; } public Integer getEndYear() { return endYear; } public void setEndYear(Integer endYear) { this.endYear = endYear; } public Integer getEndMonth() { return endMonth; } public void setEndMonth(Integer endMonth) { this.endMonth = endMonth; } public java.sql.Date getStartDate() { java.sql.Date date = null; if (startYear != null && startYear > 0) { LocalDate localDate = LocalDate.of(startYear, 1, 1); if (DateUtils.isValidMonth(startMonth)) { localDate = LocalDate.of(startYear, startMonth, 1); } date = java.sql.Date.valueOf(localDate); } return date; } public java.sql.Date getEndDate() { java.sql.Date date = null; if (endYear != null && endYear > 0) { LocalDate localDate = LocalDate.of(endYear, 12, 31); if (DateUtils.isValidMonth(endMonth)) { if (endMonth < 12) { localDate = LocalDate.of(endYear, endMonth+1, 1).minusDays(1); } else { localDate = LocalDate.of(endYear, 12, 31); } } date = java.sql.Date.valueOf(localDate); } return date; } public List<Integer> getAgencyIds() { return agencyIds; } public void setAgencyIds(List<Integer> agencyIds) { this.agencyIds = agencyIds; } }
{ "content_hash": "4f7d1735dfb5122d6488e06edc57298a", "timestamp": "", "source": "github", "line_count": 128, "max_line_length": 82, "avg_line_length": 23.1953125, "alnum_prop": 0.7214550353654429, "repo_name": "SEARCH-NCJIS/nibrs", "id": "20fe3d1b230e67572578dd960f038935132920bc", "size": "3620", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tools/nibrs-staging-data-common/src/main/java/org/search/nibrs/stagingdata/model/SubmissionTrigger.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "15483" }, { "name": "Dockerfile", "bytes": "16472" }, { "name": "HTML", "bytes": "213403" }, { "name": "Java", "bytes": "3226231" }, { "name": "JavaScript", "bytes": "29325" }, { "name": "R", "bytes": "465961" }, { "name": "Shell", "bytes": "32944" }, { "name": "XSLT", "bytes": "127003" } ], "symlink_target": "" }
package example.com.lenovo.tripbook.adapter; import android.content.Context; import android.util.Log; import android.util.SparseArray; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.Toast; import java.util.ArrayList; import java.util.Random; import example.com.lenovo.tripbook.R; import example.com.lenovo.tripbook.view.DynamicHeightTextView; /*** * ADAPTER */ public class WaterfallAdapter extends ArrayAdapter<String> { private static final String TAG = "WaterfallAdapter"; static class ViewHolder { DynamicHeightTextView txtLineOne; Button btnGo; } private final LayoutInflater mLayoutInflater; private final Random mRandom; private final ArrayList<Integer> mBackgroundColors; private static final SparseArray<Double> sPositionHeightRatios = new SparseArray<Double>(); public WaterfallAdapter(final Context context, final int textViewResourceId) { super(context, textViewResourceId); mLayoutInflater = LayoutInflater.from(context); mRandom = new Random(); mBackgroundColors = new ArrayList<Integer>(); mBackgroundColors.add(R.color.orange); mBackgroundColors.add(R.color.green); mBackgroundColors.add(R.color.blue); mBackgroundColors.add(R.color.yellow); mBackgroundColors.add(R.color.grey); } @Override public View getView(final int position, View convertView, final ViewGroup parent) { ViewHolder vh; if (convertView == null) { convertView = mLayoutInflater.inflate(R.layout.waterfall_item, parent, false); vh = new ViewHolder(); vh.txtLineOne = (DynamicHeightTextView) convertView.findViewById(R.id.txt_line1); vh.btnGo = (Button) convertView.findViewById(R.id.btn_go); convertView.setTag(vh); } else { vh = (ViewHolder) convertView.getTag(); } double positionHeight = getPositionRatio(position); int backgroundIndex = position >= mBackgroundColors.size() ? position % mBackgroundColors.size() : position; // convertView.setBackgroundResource(mBackgroundColors.get(backgroundIndex)); convertView.setBackgroundResource(R.drawable.background); Log.d(TAG, "getView position:" + position + " h:" + positionHeight); vh.txtLineOne.setHeightRatio(positionHeight); vh.txtLineOne.setText(getItem(position) + position); vh.btnGo.setOnClickListener(new View.OnClickListener() { @Override public void onClick(final View v) { Toast.makeText(getContext(), "Button Clicked Position " + position, Toast.LENGTH_SHORT).show(); } }); return convertView; } private double getPositionRatio(final int position) { double ratio = sPositionHeightRatios.get(position, 0.0); // if not yet done generate and stash the columns height // in our real world scenario this will be determined by // some match based on the known height and width of the image // and maybe a helpful way to get the column height! if (ratio == 0) { ratio = getRandomHeightRatio(); sPositionHeightRatios.append(position, ratio); Log.d(TAG, "getPositionRatio:" + position + " ratio:" + ratio); } return ratio; } private double getRandomHeightRatio() { return (mRandom.nextDouble() / 2.0) + 1.0; // height will be 1.0 - 1.5 the width } }
{ "content_hash": "52144099c5e73eb2622d180376ef06f3", "timestamp": "", "source": "github", "line_count": 107, "max_line_length": 95, "avg_line_length": 34.467289719626166, "alnum_prop": 0.6672993492407809, "repo_name": "BJTUTripbook1/tripbook", "id": "4eb104d4c298f3969c160a82b610bd1d47189898", "size": "3688", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/example/com/lenovo/tripbook/adapter/WaterfallAdapter.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "352577" } ], "symlink_target": "" }
package org.jsillitoe.casino.keno.paytable; public class PayTableException extends Exception { private static final long serialVersionUID = 1L; public PayTableException() { // TODO Auto-generated constructor stub } public PayTableException(String message) { super(message); // TODO Auto-generated constructor stub } public PayTableException(Throwable cause) { super(cause); // TODO Auto-generated constructor stub } public PayTableException(String message, Throwable cause) { super(message, cause); // TODO Auto-generated constructor stub } public PayTableException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); // TODO Auto-generated constructor stub } }
{ "content_hash": "49a47133c0dabd584ed3a8b093e3a540", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 115, "avg_line_length": 25.774193548387096, "alnum_prop": 0.772215269086358, "repo_name": "jsillitoe/open-keno", "id": "ed1cd545d29cd89eac6f8d1acca7f82aba745526", "size": "799", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/org/jsillitoe/casino/keno/paytable/PayTableException.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "23194" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <!-- --> <configuration> <property> <name>REPOSITORY_CONFIG_USERNAME</name> <display-name>Repository config username</display-name> <value>keyadmin</value> <description></description> </property> <property> <name>REPOSITORY_CONFIG_PASSWORD</name> <display-name>Repository config password</display-name> <value>keyadmin</value> <property-type>PASSWORD</property-type> <description></description> </property> <property> <name>DB_FLAVOR</name> <display-name>DB FLAVOR</display-name> <value>MYSQL</value> <description>The database type to be used</description> <value-attributes> <overridable>false</overridable> <type>value-list</type> <entries> <entry> <value>MYSQL</value> <label>MYSQL</label> </entry> <entry> <value>ORACLE</value> <label>ORACLE</label> </entry> <entry> <value>POSTGRES</value> <label>POSTGRES</label> </entry> <entry> <value>MSSQL</value> <label>MSSQL</label> </entry> <entry> <value>SQLA</value> <label>SQL Anywhere</label> </entry> </entries> <selection-cardinality>1</selection-cardinality> </value-attributes> </property> <property> <name>SQL_CONNECTOR_JAR</name> <display-name>SQL connector jar</display-name> <value>/usr/share/java/mysql-connector-java.jar</value> <description>Location of DB client library (please check the location of the jar file)</description> <value-attributes> <overridable>false</overridable> </value-attributes> <depends-on> <property> <type>kms-properties</type> <name>DB_FLAVOR</name> </property> </depends-on> </property> <property> <name>db_root_user</name> <display-name>Database Administrator (DBA) username</display-name> <value>root</value> <description>Database admin user. This user should have DBA permission to create the Ranger Database and Ranger Database User</description> <value-attributes> <overridable>false</overridable> </value-attributes> </property> <property> <name>db_root_password</name> <display-name>Database Administrator (DBA) password</display-name> <value></value> <property-type>PASSWORD</property-type> <description>Database password for the database admin username</description> <value-attributes> <overridable>false</overridable> </value-attributes> </property> <property> <name>db_host</name> <display-name>Ranger KMS DB host</display-name> <value></value> <description>Database host</description> <value-attributes> <overridable>false</overridable> </value-attributes> </property> <property> <name>db_name</name> <display-name>Ranger KMS DB name</display-name> <value>rangerkms</value> <description>Database name</description> <value-attributes> <overridable>false</overridable> </value-attributes> </property> <property> <name>db_user</name> <display-name>Ranger KMS DB username</display-name> <value>rangerkms</value> <description>Database username used for the Ranger KMS schema</description> <value-attributes> <overridable>false</overridable> </value-attributes> </property> <property> <name>db_password</name> <display-name>Ranger KMS DB password</display-name> <value></value> <property-type>PASSWORD</property-type> <description>Database password for the Ranger KMS schema</description> <value-attributes> <overridable>false</overridable> </value-attributes> </property> <property> <name>KMS_MASTER_KEY_PASSWD</name> <display-name>KMS master key password</display-name> <value></value> <property-type>PASSWORD</property-type> <description></description> <value-attributes> <overridable>false</overridable> </value-attributes> </property> </configuration>
{ "content_hash": "a3a0039215a42f6f41a5e60fcb48e708", "timestamp": "", "source": "github", "line_count": 145, "max_line_length": 143, "avg_line_length": 28.71034482758621, "alnum_prop": 0.6404035551285131, "repo_name": "alexryndin/ambari", "id": "c84615a2082544e1f904cdca40a9dbaceda85420", "size": "4969", "binary": false, "copies": "2", "ref": "refs/heads/branch-adh-1.5", "path": "ambari-server/src/main/resources/stacks/ADH/1.4/services/RANGER_KMS/configuration/kms-properties.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "44884" }, { "name": "C", "bytes": "331204" }, { "name": "C#", "bytes": "215907" }, { "name": "C++", "bytes": "257" }, { "name": "CSS", "bytes": "786184" }, { "name": "CoffeeScript", "bytes": "8465" }, { "name": "FreeMarker", "bytes": "2654" }, { "name": "Groovy", "bytes": "89958" }, { "name": "HTML", "bytes": "2514774" }, { "name": "Java", "bytes": "29565801" }, { "name": "JavaScript", "bytes": "19033151" }, { "name": "Makefile", "bytes": "11111" }, { "name": "PHP", "bytes": "149648" }, { "name": "PLpgSQL", "bytes": "316489" }, { "name": "PowerShell", "bytes": "2090340" }, { "name": "Python", "bytes": "17215686" }, { "name": "R", "bytes": "3943" }, { "name": "Roff", "bytes": "13935" }, { "name": "Ruby", "bytes": "33764" }, { "name": "SQLPL", "bytes": "4277" }, { "name": "Shell", "bytes": "886011" }, { "name": "Vim script", "bytes": "5813" }, { "name": "sed", "bytes": "2303" } ], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <title>enet: _ENetProtocolPing Struct Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">enet </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.1.2 --> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="pages.html"><span>Related&#160;Pages</span></a></li> <li><a href="modules.html"><span>Modules</span></a></li> <li class="current"><a href="annotated.html"><span>Data&#160;Structures</span></a></li> <li><a href="files.html"><span>Files</span></a></li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Data&#160;Structures</span></a></li> <li><a href="classes.html"><span>Data&#160;Structure&#160;Index</span></a></li> <li><a href="functions.html"><span>Data&#160;Fields</span></a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="summary"> <a href="#pub-attribs">Data Fields</a> </div> <div class="headertitle"> <div class="title">_ENetProtocolPing Struct Reference</div> </div> </div><!--header--> <div class="contents"> <table class="memberdecls"> <tr class="heading"><td colspan="2"><h2><a name="pub-attribs"></a> Data Fields</h2></td></tr> <tr class="memitem:a9ef0511594084de36617564114775c1b"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a9ef0511594084de36617564114775c1b"></a> <a class="el" href="struct__ENetProtocolCommandHeader.html">ENetProtocolCommandHeader</a>&#160;</td><td class="memItemRight" valign="bottom"><b>header</b></td></tr> </table> <hr/>The documentation for this struct was generated from the following file:<ul> <li><a class="el" href="protocol_8h_source.html">protocol.h</a></li> </ul> </div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Wed Mar 6 2013 18:35:52 for enet by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.1.2 </small></address> </body> </html>
{ "content_hash": "af4c23047456d47e148963c5960670f8", "timestamp": "", "source": "github", "line_count": 69, "max_line_length": 166, "avg_line_length": 41.710144927536234, "alnum_prop": 0.6511466296038916, "repo_name": "FatalEagle/Crowbot", "id": "a4de4fa428e2f0790287837241a832a71464ab27", "size": "2878", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "tools/enet/docs/html/struct__ENetProtocolPing.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "3503" } ], "symlink_target": "" }
package cspbuilder import ( "strings" ) const ( // Fetch Directives ChildSrc = "child-src" ConnectSrc = "connect-src" DefaultSrc = "default-src" FontSrc = "font-src" FrameSrc = "frame-src" ImgSrc = "img-src" ManifestSrc = "manifest-src" MediaSrc = "media-src" ObjectSrc = "object-src" PrefetchSrc = "prefetch-src" ScriptSrc = "script-src" ScriptSrcAttr = "script-src-attr" ScriptSrcElem = "script-src-elem" StyleSrc = "style-src" StyleSrcAttr = "style-src-attr" StyleSrcElem = "style-src-elem" WorkerSrc = "worker-src" // Document Directives BaseURI = "base-uri" Sandbox = "sandbox" // Navigation directives FormAction = "form-action" FrameAncestors = "frame-ancestors" NavigateTo = "navigate-to" // Reporting directives ReportURI = "report-uri" ReportTo = "report-to" // Other directives RequireTrustedTypesFor = "require-trusted-types-for" TrustedTypes = "trusted-types" UpgradeInsecureRequests = "upgrade-insecure-requests" ) type Builder struct { Directives map[string]([]string) } // MustBuild is like Build but panics if an error occurs. func (builder *Builder) MustBuild() string { policy, err := builder.Build() if err != nil { panic(err) } return policy } // Build creates a content security policy string from the specified directives. // If any directive contains invalid values, an error is returned instead. func (builder *Builder) Build() (string, error) { var sb strings.Builder for directive := range builder.Directives { if sb.Len() > 0 { sb.WriteString("; ") } switch directive { case Sandbox: err := buildDirectiveSandbox(&sb, builder.Directives[directive]) if err != nil { return "", err } case FrameAncestors: err := buildDirectiveFrameAncestors(&sb, builder.Directives[directive]) if err != nil { return "", err } case ReportTo: err := buildDirectiveReportTo(&sb, builder.Directives[directive]) if err != nil { return "", err } case RequireTrustedTypesFor: err := buildDirectiveRequireTrustedTypesFor(&sb, builder.Directives[directive]) if err != nil { return "", err } case TrustedTypes: err := buildDirectiveTrustedTypes(&sb, builder.Directives[directive]) if err != nil { return "", err } case UpgradeInsecureRequests: err := buildDirectiveUpgradeInsecureRequests(&sb, builder.Directives[directive]) if err != nil { return "", err } default: // no special handling of directive values needed err := buildDirectiveDefault(&sb, directive, builder.Directives[directive]) if err != nil { return "", err } } } return sb.String(), nil }
{ "content_hash": "c211538b5ac8715f2d47b8ee8c56bf69", "timestamp": "", "source": "github", "line_count": 110, "max_line_length": 83, "avg_line_length": 24.62727272727273, "alnum_prop": 0.6718346253229974, "repo_name": "unrolled/secure", "id": "dd9e44347603c43a71d4acd05230666a00243f20", "size": "2709", "binary": false, "copies": "1", "ref": "refs/heads/v1", "path": "cspbuilder/builder.go", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "78794" }, { "name": "Makefile", "bytes": "440" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "66759620e822da9fddb6208f08f23daf", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "3e0c85f798128ede76608896e6778a4f0d8de96f", "size": "186", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Fabales/Fabaceae/Pultenaea/Pultenaea daphnoides/Pultenaea daphnoides daphnoides/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package com.paypal.selion.grid; import static com.paypal.selion.pojos.SeLionGridConstants.*; import java.io.IOException; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import org.apache.commons.exec.CommandLine; import org.apache.commons.lang.SystemUtils; import com.paypal.selion.SeLionConstants; import com.paypal.selion.logging.SeLionGridLogger; /** * This is a stand alone class which sets up SeLion dependencies and spawns {@link SeLionGridLauncher}. */ public final class JarSpawner extends AbstractBaseProcessLauncher { private static final SeLionGridLogger LOGGER = SeLionGridLogger.getLogger(JarSpawner.class); private static final String SEPARATOR = "\n----------------------------------\n"; public JarSpawner(String[] args) { this(args, null); } public JarSpawner(String[] args, ProcessLauncherOptions options) { super(); init(args, options); } public static final void main(String[] args) { new JarSpawner(args).run(); } /** * Print the usage of SeLion Grid jar */ final void printUsageInfo() { StringBuilder usage = new StringBuilder(); usage.append(SEPARATOR); usage.append("To use SeLion Grid"); usage.append(SEPARATOR); usage.append("\n"); usage.append("Usage: java [system properties] -jar SeLion-Grid.jar [options] \n"); usage.append(" [selenium options] \n"); usage.append("\n"); usage.append(" Options:\n"); usage.append(" " + TYPE_ARG + " <sauce>: \n"); usage.append(" Used with '-role hub' to start a hub with the on demand \n"); usage.append(" sauce proxy \n"); usage.append(" " + SELION_CONFIG_ARG + " <config file name>: \n"); usage.append(" A SeLion Grid configuration JSON file \n"); usage.append(" " + SELION_NOCONTINUOUS_ARG + "\n"); usage.append(" Disable continuous restarting of node/hub sub-process \n"); usage.append("\n"); usage.append(" Selenium Options: \n"); usage.append(" Any valid Selenium standalone or grid dash option(s). \n"); usage.append(" E.g. '-role hub -port 2054' -- To start a hub on port 2054. \n"); usage.append("\n"); usage.append(" System Properties: \n"); usage.append(" -DselionHome=<folderPath>: \n"); usage.append(" Path of SeLion home directory. Defaults to \n"); usage.append(" <user.home>/.selion/ \n"); usage.append(" -D[property]=[value]: \n"); usage.append(" Any other System Property you wish to pass to the JVM \n"); System.out.print(usage.toString()); } @Override final void startProcess(boolean squelch) throws IOException { setCommandLine(createJavaCommandForChildProcess()); super.startProcess(squelch); } /** * This method load the default arguments required to spawn SeLion Grid/Node * * @return {@link CommandLine} * @throws IOException */ private CommandLine createJavaCommandForChildProcess() throws IOException { LOGGER.entering(); // start command with java CommandLine cmdLine = CommandLine.parse("java"); // add the -D system properties cmdLine.addArguments(getJavaSystemPropertiesArguments()); // Set the classpath cmdLine.addArguments(getJavaClassPathArguments("selenium-", SeLionGridLauncher.class.getName())); // add the program argument / dash options cmdLine.addArguments(getProgramArguments()); LOGGER.exiting(cmdLine.toString()); return cmdLine; } @Override String[] getJavaSystemPropertiesArguments() throws IOException { LOGGER.entering(); List<String> args = new LinkedList<String>(); // include everything a typical process launcher would add for a java process args.addAll(Arrays.asList(super.getJavaSystemPropertiesArguments())); // include the WebDriver binary paths for Chromedriver, IEDriver, and PhantomJs args.addAll(Arrays.asList(getWebDriverBinarySystemPropertiesArguments())); LOGGER.exiting(args.toString()); return args.toArray(new String[args.size()]); } private String[] getWebDriverBinarySystemPropertiesArguments() { LOGGER.entering(); List<String> args = new LinkedList<String>(); if (getLauncherOptions().isIncludeWebDriverBinaryPaths() && (getType().equals(InstanceType.SELENIUM_NODE) || getType().equals(InstanceType.SELENIUM_STANDALONE))) { // Make sure we setup WebDriver binary paths for the child process if (SystemUtils.IS_OS_WINDOWS && System.getProperty(SeLionConstants.WEBDRIVER_IE_DRIVER_PROPERTY) == null) { args.add("-D" + SeLionConstants.WEBDRIVER_IE_DRIVER_PROPERTY + "=" + SeLionConstants.SELION_HOME_DIR + SeLionConstants.IE_DRIVER); } if (System.getProperty(SeLionConstants.WEBDRIVER_CHROME_DRIVER_PROPERTY) == null) { args.add("-D" + SeLionConstants.WEBDRIVER_CHROME_DRIVER_PROPERTY + "=" + SeLionConstants.SELION_HOME_DIR + SeLionConstants.CHROME_DRIVER); } if (System.getProperty(SeLionConstants.WEBDRIVER_PHANTOMJS_DRIVER_PROPERTY) == null) { args.add("-D" + SeLionConstants.WEBDRIVER_PHANTOMJS_DRIVER_PROPERTY + "=" + SeLionConstants.SELION_HOME_DIR + SeLionConstants.PHANTOMJS_DRIVER); } } LOGGER.exiting(args.toString()); return args.toArray(new String[args.size()]); } }
{ "content_hash": "5096a209e8f471857d5ef5a512defe4c", "timestamp": "", "source": "github", "line_count": 142, "max_line_length": 122, "avg_line_length": 40.61971830985915, "alnum_prop": 0.6331484049930652, "repo_name": "paulbrodner/SeLion", "id": "f013a3d26cea9a586b4c76840d572d9e43920b7b", "size": "7447", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "server/src/main/java/com/paypal/selion/grid/JarSpawner.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "51701" }, { "name": "HTML", "bytes": "67565" }, { "name": "Java", "bytes": "2710378" }, { "name": "JavaScript", "bytes": "150678" }, { "name": "Objective-C", "bytes": "24249" }, { "name": "Shell", "bytes": "4226" } ], "symlink_target": "" }
'use strict'; import * as React from "react"; import * as ReactDOM from "react-dom"; import { Home } from "./components/Home/Home"; ReactDOM.render( <Home firstname="Damien" lastname="Assany" />, document.getElementById("content") );
{ "content_hash": "2d79583794b5cf7e1db3e77d439eb5ff", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 50, "avg_line_length": 22.272727272727273, "alnum_prop": 0.6816326530612244, "repo_name": "PandaDevIO/react-typescript-starter", "id": "3e94763c01bfb54bdbfd46eb4ea5a87537f6b9dc", "size": "245", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/index.tsx", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "424" }, { "name": "JavaScript", "bytes": "2796" }, { "name": "TypeScript", "bytes": "291" } ], "symlink_target": "" }
package org.openbaton.catalogue.mano.descriptor; import java.io.Serializable; import java.util.Set; import javax.persistence.*; import org.openbaton.catalogue.mano.common.ConnectionPoint; import org.openbaton.catalogue.mano.common.Security; import org.openbaton.catalogue.util.IdGenerator; /** * Created by lto on 06/02/15. * * <p>Based on ETSI GS NFV-MAN 001 V1.1.1 (2014-12) */ @Entity public class PhysicalNetworkFunctionDescriptor implements Serializable { /** The ID (e.g. name) of this PNFD. */ @Id private String id; @Version private int hb_version = 0; /** The vendor generating this PNFD. */ private String vendor; /** The version of PNF this PNFD is describing. */ private String version; /** Description of physical device functionality. */ private String description; /** * This element describes an external interface exposed by this PNF enabling connection with a VL. */ @OneToMany(cascade = CascadeType.ALL) private Set<ConnectionPoint> connection_point; /** Version of the PNF descriptor. */ private String descriptor_version; /** * This is a signature of pnfd to prevent tampering. The particular hash algorithm used to compute * the signature, together with the corresponding cryptographic certificate to validate the * signature should also be included. */ @OneToOne(cascade = CascadeType.ALL) private Security pnfd_security; public PhysicalNetworkFunctionDescriptor() {} public int getHb_version() { return hb_version; } public void setHb_version(int hb_version) { this.hb_version = hb_version; } @PrePersist public void ensureId() { id = IdGenerator.createUUID(); } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getVendor() { return vendor; } public void setVendor(String vendor) { this.vendor = vendor; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Set<ConnectionPoint> getConnection_point() { return connection_point; } public void setConnection_point(Set<ConnectionPoint> connection_point) { this.connection_point = connection_point; } public String getDescriptor_version() { return descriptor_version; } public void setDescriptor_version(String descriptor_version) { this.descriptor_version = descriptor_version; } public Security getPnfd_security() { return pnfd_security; } public void setPnfd_security(Security pnfd_security) { this.pnfd_security = pnfd_security; } @Override public String toString() { return "PhysicalNetworkFunctionDescriptor [id=" + id + ", hb_version=" + hb_version + ", vendor=" + vendor + ", version=" + version + ", description=" + description + ", connection_point=" + connection_point + ", descriptor_version=" + descriptor_version + ", pnfd_security=" + pnfd_security + "]"; } }
{ "content_hash": "e50407069323716c99d687190318cfe4", "timestamp": "", "source": "github", "line_count": 136, "max_line_length": 100, "avg_line_length": 23.970588235294116, "alnum_prop": 0.6773006134969325, "repo_name": "openbaton/openbaton-libs", "id": "af647e31aa6c41ab0cbbc3ce9d4c4408b6c3eb2e", "size": "3888", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "catalogue/src/main/java/org/openbaton/catalogue/mano/descriptor/PhysicalNetworkFunctionDescriptor.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "619479" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="robots" content="index, follow, all" /> <title>Grav\Common\Errors | Grav API</title> <link rel="stylesheet" type="text/css" href="../../css/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="../../css/bootstrap-theme.min.css"> <link rel="stylesheet" type="text/css" href="../../css/sami.css"> <script src="../../js/jquery-1.11.1.min.js"></script> <script src="../../js/bootstrap.min.js"></script> <script src="../../js/typeahead.min.js"></script> <script src="../../sami.js"></script> <meta name="MobileOptimized" content="width"> <meta name="HandheldFriendly" content="true"> <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1"> </head> <body id="namespace" data-name="namespace:Grav_Common_Errors" data-root-path="../../"> <div id="content"> <div id="left-column"> <div id="control-panel"> <form id="search-form" action="../../search.html" method="GET"> <span class="glyphicon glyphicon-search"></span> <input name="search" class="typeahead form-control" type="search" placeholder="Search"> </form> </div> <div id="api-tree"></div> </div> <div id="right-column"> <nav id="site-nav" class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar-elements"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="../../index.html">Grav API</a> </div> <div class="collapse navbar-collapse" id="navbar-elements"> <ul class="nav navbar-nav"> <li><a href="../../classes.html">Classes</a></li> <li><a href="../../namespaces.html">Namespaces</a></li> <li><a href="../../interfaces.html">Interfaces</a></li> <li><a href="../../traits.html">Traits</a></li> <li><a href="../../doc-index.html">Index</a></li> <li><a href="../../search.html">Search</a></li> </ul> </div> </div> </nav> <div class="namespace-breadcrumbs"> <ol class="breadcrumb"> <li><span class="label label-default">Namespace</span></li> <li><a href="../../Grav.html">Grav</a></li> <li><a href="../../Grav/Common.html">Common</a></li> <li><a href="../../Grav/Common/Errors.html">Errors</a></li> </ol> </div> <div id="page-content"> <div class="page-header"> <h1>Grav\Common\Errors</h1> </div> <h2>Classes</h2> <div class="container-fluid underlined"> <div class="row"> <div class="col-md-6"> <a href="../../Grav/Common/Errors/Errors.html"><abbr title="Grav\Common\Errors\Errors">Grav\Common\Errors\Errors</abbr></a> </div> <div class="col-md-6"> Class Debugger </div> </div> <div class="row"> <div class="col-md-6"> <a href="../../Grav/Common/Errors/SimplePageHandler.html"><abbr title="Grav\Common\Errors\SimplePageHandler">Grav\Common\Errors\SimplePageHandler</abbr></a> </div> <div class="col-md-6"> </div> </div> </div> </div> <div id="footer"> Generated on December 8th at 8:01pm by <a href="http://sami.sensiolabs.org/">Sami</a> </div> </div> </div> </body> </html>
{ "content_hash": "ed1a46a2cbc88e269bb5b905f4f3a8cc", "timestamp": "", "source": "github", "line_count": 111, "max_line_length": 200, "avg_line_length": 40.73873873873874, "alnum_prop": 0.45466607695709865, "repo_name": "getgrav/grav-api", "id": "0d39bffb0db226ace6159918aafabf6cc8aeb08c", "size": "4522", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "api/Grav/Common/Errors.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "6417" }, { "name": "HTML", "bytes": "5595444" }, { "name": "PHP", "bytes": "649" }, { "name": "Shell", "bytes": "66" } ], "symlink_target": "" }
<!-- Memory Example java.lang:type=MemoryPool,name=<NAME> CollectionUsage.committed CollectionUsage.init CollectionUsage.max CollectionUsage.used CollectionUsageThreshold CollectionUsageThresholdCount CollectionUsageThresholdExceeded CollectionUsageThresholdSupported MemoryManagerNames (note that the type of this attribute is String[]) PeakUsage.committed PeakUsage.init PeakUsage.max PeakUsage.used Usage.* --> <Settings> <pollingRate>-1</pollingRate><!-- for fitness testing --> <folderLocation>extracted\\</folderLocation> <url></url> <BeanList> <Bean> <name>java.lang:type=MemoryPool,name=PS Perm Gen</name> <alias>MemoryPoolPSPermGenExample</alias> <AttributeList> <Attribute> <name>CollectionUsage.committed</name> </Attribute> <Attribute> <name>CollectionUsage.init</name> </Attribute> <Attribute> <name>CollectionUsage.max</name> </Attribute> <Attribute> <name>CollectionUsage.used</name> </Attribute> <Attribute> <name>CollectionUsageThreshold</name> </Attribute> <Attribute> <name>CollectionUsageThresholdCount</name> </Attribute> <Attribute> <name>CollectionUsageThresholdExceeded</name> </Attribute> <Attribute> <name>CollectionUsageThresholdSupported</name> </Attribute> <Attribute> <name>MemoryManagerNames</name> </Attribute> <Attribute> <name>PeakUsage.committed</name> </Attribute> <Attribute> <name>PeakUsage.init</name> </Attribute> <Attribute> <name>PeakUsage.max</name> </Attribute> <Attribute> <name>PeakUsage.used</name> </Attribute> <Attribute> <name>Usage.*</name> </Attribute> </AttributeList> <enable>true</enable> </Bean> </BeanList> </Settings>
{ "content_hash": "24cde6f345ccdd07a153575edb9313e9", "timestamp": "", "source": "github", "line_count": 76, "max_line_length": 69, "avg_line_length": 23.736842105263158, "alnum_prop": 0.6890243902439024, "repo_name": "TeamDewberry/jmxdatamart", "id": "8382d1ef942964b212b3425adf818db48d5a9607", "size": "1804", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "fitnesse/MemoryPool_PS_Perm_Gen.xml", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Java", "bytes": "245215" } ], "symlink_target": "" }
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "7df11d457a7f6a8ea43d64184e599995", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.23076923076923, "alnum_prop": 0.6917293233082706, "repo_name": "mdoering/backbone", "id": "785b2e2487ce3a29ad0e5f73b54c9c285071aa5b", "size": "191", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Orchidaceae/Papilionanthe/Papilionanthe sillemiana/ Syn. Aerides sillemiana/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
NS_ASSUME_NONNULL_BEGIN @interface RXMaskViewViewController : UIViewController @end NS_ASSUME_NONNULL_END
{ "content_hash": "834089d9f86360d1a480335711bd4602", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 54, "avg_line_length": 15.571428571428571, "alnum_prop": 0.8256880733944955, "repo_name": "xzjxylophone/RXVerifyExample", "id": "00ab16f1bcc2a57832f9981d823055931d070946", "size": "290", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "RXVerifyExample/RXVerifyExample/Verify/UI/MaskView/RXMaskViewViewController.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "3331" }, { "name": "C++", "bytes": "1578988" }, { "name": "JavaScript", "bytes": "145" }, { "name": "LLVM", "bytes": "45738" }, { "name": "Objective-C", "bytes": "1454563" }, { "name": "Objective-C++", "bytes": "9289" }, { "name": "Ruby", "bytes": "1589" } ], "symlink_target": "" }
import _ from 'lodash'; import './style.scss'; function component() { //var element = document.createElement('div'); //element.innerHTML = _.join(['Hello', 'webpack'], ' '); //return element; } document.body.appendChild(component());
{ "content_hash": "a4e8378c205292e61b568d687f791e9e", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 60, "avg_line_length": 20.833333333333332, "alnum_prop": 0.636, "repo_name": "Raffi-001/bootspackbp", "id": "500fefd8a07cfea7183302d25debd54fdb978136", "size": "250", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/index.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "34591" }, { "name": "HTML", "bytes": "2548" }, { "name": "JavaScript", "bytes": "1859" } ], "symlink_target": "" }
from netforce.model import Model, fields class customerMessage(Model): _name = "cms.customer.message" _fields = { "name": fields.Char("Name", required=True), "email": fields.Char("Email", required=True), "description": fields.Text("Description",required=True), } customerMessage.register()
{ "content_hash": "ff3e099894f0f3a5ca63131087b859bf", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 64, "avg_line_length": 27.416666666666668, "alnum_prop": 0.6565349544072948, "repo_name": "anastue/netforce", "id": "372fbc6c9a42560e29798e3d3939f7d0eec5d1d2", "size": "1434", "binary": false, "copies": "4", "ref": "refs/heads/stable-3.1", "path": "netforce_cms/netforce_cms/models/cms_customer_message.py", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "73" }, { "name": "CSS", "bytes": "407336" }, { "name": "Groff", "bytes": "15858" }, { "name": "HTML", "bytes": "477928" }, { "name": "Java", "bytes": "11870" }, { "name": "JavaScript", "bytes": "3711952" }, { "name": "Makefile", "bytes": "353" }, { "name": "PHP", "bytes": "2274" }, { "name": "Python", "bytes": "3455528" }, { "name": "Shell", "bytes": "117" } ], "symlink_target": "" }
PyD and distutils ================= PyD provides patches to distutils so it can use DMD, LDC, and GDC. .. seealso:: `distutils <https://docs.python.org/2/library/distutils.html#module-distutils>`__ Mostly, this consists of a different :code:`setup` that must be called, and a different :code:`Extension` that must be used: .. literalinclude:: ../../examples/hello/setup.py Command line flags ~~~~~~~~~~~~~~~~~~ compiler -------- Specify the D compiler to use. Expects one of dmd, ldc, gdc. .. code-block:: bash python setup.py install --compiler=ldc Default: dmd debug ------- Have the D compiler compile things with debugging information. .. code-block:: bash python setup.py install --debug Extension arguments ~~~~~~~~~~~~~~~~~~~ In addition to the `arguments <https://docs.python.org/2/distutils/apiref.html#distutils.core.Extension>`__ accepted by distutils' Extension, PyD's `Extension` accepts the following arguments: version_flags ------------- A list of strings passed to the D compiler as D version identifiers. Default: :code:`[]` debug_flags ----------- similar to version_flags for D debug identifiers Default: :code:`[]` raw_only -------- When :code:`True`, suppress linkage of all of PyD except the bare C API. Equivalent to setting `with_pyd` and `with_main` to :code:`False`. Default: :code:`False` with_pyd -------- Setting this flag to :code:`False` suppresses compilation and linkage of PyD. `with_main` effectively becomes :code:`False` as well; `PydMain` won't be used unless PyD is in use. Default: :code:`True` with_main --------- Setting this flag to :code:`False` suppresses the use of `PydMain`, allowing the user to write a C-style init function instead. Default: :code:`True` build_deimos ------------ Build object files for deimos headers. Ideally, this should not be necessary; however some compilers (\*cough* ldc) try to link to PyObject typeinfo. If you get link errors like `undefined symbol: _D6deimos6python12methodobject11PyMethodDef6__initZ` try setting this flag to :code:`True`. Default: :code:`False` optimize -------- Have D compilers do optimized compilation. Default: :code:`False` d_lump ------ Lump compilation of all d files into a single command. Default: :code:`False` d_unittest ---------- Have D compilers generate unittest code Default: :code:`False` d_property ---------- Have D compilers enable property checks (i.e. trying to call functions without parens will result in an error) Default: :code:`False` string_imports -------------- Specify string import files to pass to D compilers. Takes a list of strings which are either paths to import files or paths to directories containing import files. Default: :code:`[]` pydexe ~~~~~~ PyD also provides a custom command to compile D code that embeds python. The format of setup.py stays the same. .. literalinclude:: ../../examples/pyind/setup.py Mixing C and D extensions ~~~~~~~~~~~~~~~~~~~~~~~~~ It is totally possible. Use PyD's :code:`setup`. .. literalinclude:: ../../examples/misc/d_and_c/setup.py
{ "content_hash": "9f4680c8f6c2023aa32a0aeb36c56b24", "timestamp": "", "source": "github", "line_count": 142, "max_line_length": 192, "avg_line_length": 21.661971830985916, "alnum_prop": 0.6947334200260078, "repo_name": "ariovistus/pyd", "id": "5040d340a99c737aef5e2986343f03ba380be412", "size": "3076", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/source/distutils.rst", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "383" }, { "name": "C", "bytes": "4779" }, { "name": "D", "bytes": "952779" }, { "name": "Dockerfile", "bytes": "7125" }, { "name": "Makefile", "bytes": "207" }, { "name": "Python", "bytes": "74109" }, { "name": "Shell", "bytes": "1341" } ], "symlink_target": "" }
<!DOCTYPE html> <!-- ~ Copyright (c) 2013, IT Services, Stockholm University ~ All rights reserved. ~ ~ Redistribution and use in source and binary forms, with or without ~ modification, are permitted provided that the following conditions are met: ~ ~ Redistributions of source code must retain the above copyright notice, this ~ list of conditions and the following disclaimer. ~ ~ Redistributions in binary form must reproduce the above copyright notice, ~ this list of conditions and the following disclaimer in the documentation ~ and/or other materials provided with the distribution. ~ ~ Neither the name of Stockholm University nor the names of its contributors ~ may be used to endorse or promote products derived from this software ~ without specific prior written permission. ~ ~ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" ~ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ~ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ~ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE ~ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR ~ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF ~ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS ~ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN ~ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ~ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE ~ POSSIBILITY OF SUCH DAMAGE. --> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Stockholms universitet</title> <link rel="stylesheet" href="css/jquery.mobile-1.3.1.min.css"/> <link rel="stylesheet" href="css/SU-ThemeA-B.css"/> <link rel="stylesheet" href="css/SU-beta.css"/> <link rel="stylesheet" href="css/start.css"/> <script type="text/javascript" charset="utf-8" src="cordova-2.7.0.js"></script> <script type="text/javascript" charset="utf-8" src="GAPlugin.js"></script> <script src="js/lib/jquery-1.8.2.min.js"></script> <script src="js/lib/jquery.mobile-1.3.1.min.js"></script> <script src="js/lib/underscore-1.4.4-min.js"></script> <script src="js/lib/backbone-1.0.0-min.js"></script> <script src="js/lib/fastclick/fastclick.min.js"></script> <script src="js/jquery.mobile-config.js"></script> <!-- Translation with i18next --> <script type="text/javascript" src="js/lib/i18next-1.6.2.min.js"></script> <script src="js/locale.js"></script> <!-- Global config file --> <script src="js/config.js"></script> <!-- Default javascripts --> <script src="js/jst/common.js"></script> <script src="js/default.js"></script> <script src="js/views/start-view.js"></script> </head> <body> <div data-role="page" class="type-home" id="page-home" data-header="common/header"> <!-- Home --> <div data-role="content"> <div id="buttongrid" class="ui-grid-b button-grid"> <div class="ui-block-a buildings"> <a href="map/index.html#/buildings" data-ajax="false"> <div class="button-container"> <div class="glare"></div> <img src="img/icons/icon-building.svg"/> </div> <span data-i18n="start.menuItem.buildings"></span> </a> </div> <div class="ui-block-b"> <a href="map/index.html#/departments" data-ajax="false"> <div class="button-container"> <div class="glare"></div> <img src="img/icons/icon-departments.svg"/> </div> <span data-i18n="start.menuItem.departments"></span> </a> </div> <div class="ui-block-c"> <a href="map/index.html#/auditoriums" data-ajax="false"> <div class="button-container"> <div class="glare"></div> <img src="img/icons/icon-auditoriums.svg"/> </div> <span data-i18n="start.menuItem.auditoriums"></span> </a> </div> <div class="ui-block-a"> <a href="map/index.html#/computerLabs" data-ajax="false"> <div class="button-container"> <div class="glare"></div> <img src="img/icons/icon-computer-labs.svg"/> </div> <span data-i18n="start.menuItem.computerLabs"></span> </a> </div> <div class="ui-block-b"> <a href="map/index.html#/parkingspaces" data-ajax="false"> <div class="button-container"> <div class="glare"></div> <img src="img/icons/icon-parking.svg"/> </div> <span data-i18n="start.menuItem.parkingspaces"></span> </a> </div> <div class="ui-block-c"> <a href="map/index.html#/restaurants" data-ajax="false"> <div class="button-container"> <div class="glare"></div> <img src="img/icons/icon-restaurants.svg"/> </div> <span data-i18n="start.menuItem.restaurants"></span> </a> </div> <div class="ui-block-a"> <a id="info-link" href="info/index.html" data-ajax="false"> <div class="button-container"> <div class="glare"></div> <img src="img/icons/icon-accessibility.svg"/> </div> <span data-i18n="start.menuItem.accessibility"></span> </a> </div> <div class="ui-block-b"> <a id="servicelink" href="studentservice/index.html" data-ajax="false"> <div class="button-container"> <div class="glare"></div> <img src="img/icons/icon-student-service.svg"/> </div> <span data-i18n="start.menuItem.studentService"></span> </a> </div> <div class="ui-block-c"> <a id="sisulink" data-i18n="[href]start.sisu.link" target="_blank" data-ajax="false"> <div class="button-container"> <div class="glare"></div> <img src="img/icons/icon-sisu.svg"/> </div> <span data-i18n="start.menuItem.courses"></span> </a> </div> </div> </div> </div> <script type="text/javascript"> $(document).ready(function () { var view = new StartView({ el: $('#page-home') }); view.render(); }); </script> </body> </html>
{ "content_hash": "50bbcb57b3ec6b044ec70997f39a2b15", "timestamp": "", "source": "github", "line_count": 165, "max_line_length": 93, "avg_line_length": 38.624242424242425, "alnum_prop": 0.615094931743292, "repo_name": "carllarsson/hermes", "id": "af3a78a1eb125d302747c6c19f05ffa1ffad73e2", "size": "6373", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "assets/www/index.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "178619" }, { "name": "CoffeeScript", "bytes": "1225" }, { "name": "Groovy", "bytes": "11882" }, { "name": "Java", "bytes": "3517" }, { "name": "JavaScript", "bytes": "755794" }, { "name": "Shell", "bytes": "8031" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; namespace MostFrequentNumber { public class MostFrequentNumber { public static void Main() { string[] input = Console.ReadLine().Split(); int[] nums = new int[input.Length]; for (int i = 0; i < nums.Length; i++) { nums[i] = int.Parse(input[i]); } int biggestOccurence = 0; int mostFrequentNum = 0; for (int i = 0; i < nums.Length; i++) { int currentNum = nums[i]; int occurrences = 1; for (int j = i + 1; j < nums.Length; j++) { if (currentNum == nums[j]) { occurrences++; } } if (occurrences > biggestOccurence) { biggestOccurence = occurrences; mostFrequentNum = currentNum; } } Console.WriteLine(mostFrequentNum); } } }
{ "content_hash": "72dc1301c0cd0575aed4451f8aa0a25b", "timestamp": "", "source": "github", "line_count": 45, "max_line_length": 57, "avg_line_length": 25.2, "alnum_prop": 0.42151675485008816, "repo_name": "arobertov/SoftUniExercises", "id": "3ec00b9440a836fb137242f0b74befd8391544fa", "size": "1136", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ArraysExercises/MostFrequentNumber/MostFrequend.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "131486" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "e609d0a229ab3275b3bb3bf27d54d463", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "78cd7f5c1beb2a9b237bca81aa0d4c08260c65f3", "size": "173", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Santalales/Loranthaceae/Cladocolea/Cladocolea glauca/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<?php /** * DO NOT EDIT THIS FILE! * * This file was automatically generated from external sources. * * Any manual change here will be lost the next time the SDK * is updated. You've been warned! */ namespace DTS\eBaySDK\ResolutionCaseManagement\Types; /** * * @property integer $pageNumber * @property integer $entriesPerPage */ class PaginationInput extends \DTS\eBaySDK\Types\BaseType { /** * @var array Properties belonging to objects of this class. */ private static $propertyTypes = [ 'pageNumber' => [ 'type' => 'integer', 'repeatable' => false, 'attribute' => false, 'elementName' => 'pageNumber' ], 'entriesPerPage' => [ 'type' => 'integer', 'repeatable' => false, 'attribute' => false, 'elementName' => 'entriesPerPage' ] ]; /** * @param array $values Optional properties and values to assign to the object. */ public function __construct(array $values = []) { list($parentValues, $childValues) = self::getParentValues(self::$propertyTypes, $values); parent::__construct($parentValues); if (!array_key_exists(__CLASS__, self::$properties)) { self::$properties[__CLASS__] = array_merge(self::$properties[get_parent_class()], self::$propertyTypes); } if (!array_key_exists(__CLASS__, self::$xmlNamespaces)) { self::$xmlNamespaces[__CLASS__] = 'xmlns="http://www.ebay.com/marketplace/resolution/v1/services"'; } $this->setValues(__CLASS__, $childValues); } }
{ "content_hash": "87f4ce5c0d905b3e78189722c6db4c24", "timestamp": "", "source": "github", "line_count": 57, "max_line_length": 116, "avg_line_length": 28.771929824561404, "alnum_prop": 0.5835365853658536, "repo_name": "davidtsadler/ebay-sdk-php", "id": "95e9d3de8975d76aa4aa203d90cf90cfb6206090", "size": "1640", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/ResolutionCaseManagement/Types/PaginationInput.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Makefile", "bytes": "10944" }, { "name": "PHP", "bytes": "9958599" } ], "symlink_target": "" }
/************************************************************************ * libc/math/lib_sqrt.c * * This file is a part of NuttX: * * Copyright (C) 2012 Gregory Nutt. All rights reserved. * Ported by: Darcy Gong * * It derives from the Rhombs OS math library by Nick Johnson which has * a compatibile, MIT-style license: * * Copyright (C) 2009-2011 Nick Johnson <nickbjohnson4224 at gmail.com> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * ************************************************************************/ /************************************************************************ * Included Files ************************************************************************/ #include <tinyara/config.h> #include <tinyara/compiler.h> #include <math.h> #include <errno.h> #include "lib_internal.h" /************************************************************************ * Public Functions ************************************************************************/ #ifdef CONFIG_HAVE_DOUBLE double sqrt(double x) { long double y, y1; if (x < 0.0) { set_errno(EDOM); return NAN; } if (isnan(x)) { return NAN; } if (isinf(x)) { return INFINITY; } if (x == 0.0) { return 0.0; } /* Guess square root (using bit manipulation) */ y = lib_sqrtapprox(x); /* Perform four iterations of approximation. This number (4) is * definitely optimal */ y = 0.5 * (y + x / y); y = 0.5 * (y + x / y); y = 0.5 * (y + x / y); y = 0.5 * (y + x / y); /* If guess was terribe (out of range of float). Repeat approximation * until convergence. */ if (y * y < x - 1.0 || y * y > x + 1.0) { y1 = -1.0; while (y != y1) { y1 = y; y = 0.5 * (y + x / y); } } return y; } #endif
{ "content_hash": "e4272ab8cd5a6931a176c059be152253", "timestamp": "", "source": "github", "line_count": 94, "max_line_length": 75, "avg_line_length": 25.79787234042553, "alnum_prop": 0.5360824742268041, "repo_name": "lssgood/TizenRT", "id": "e5b0ccd4d181c64c4797a0b4465ee78a8b4d98e0", "size": "3200", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "lib/libc/math/lib_sqrt.c", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "206235" }, { "name": "Batchfile", "bytes": "39014" }, { "name": "C", "bytes": "29355146" }, { "name": "C++", "bytes": "532697" }, { "name": "HTML", "bytes": "2149" }, { "name": "Makefile", "bytes": "504571" }, { "name": "Objective-C", "bytes": "90599" }, { "name": "Perl", "bytes": "2687" }, { "name": "Python", "bytes": "31505" }, { "name": "Shell", "bytes": "129081" }, { "name": "Tcl", "bytes": "325812" } ], "symlink_target": "" }
\section{Related readings} \label{sec:related-readings} \begin{itemize} \item Closed queueing networks: \cite{lazowska1984quantitative,menasce2001capacity} \item Comparison Open/Closed queueing networks: \cite{bondi1986influence,schroeder2006open,tay2013analytical,whitt1984open} \item Stability conditions for queueing networks: \cite{bramson2008stability} \item Generalization of Little's Law: \cite{el2012sample,miyazawa1994rate}. \item Markov Chains: \cite{ross2014introduction}. \item Generalization of PASTA: \cite{wolff1982poisson}. \item insensitivity property: \cite{tijms2003first}. \item reverse-chains and time-reversibility: \cite{bertsekas1992data,ross1996stochastic}. \item Burke theorem: \cite{burke1956output} \item Jackson Networks: \cite{jackson1963jobshop}. \item normalizing constants for closed systems: \cite{harrison1985technical,choudhury1995calculating}. \item Mean Value Analysis: \cite{reiser1980mean,bolch2006queueing,menasce2001capacity,allen2014probability}. \item Scheduling Policies \cite{wierman2007scheduling}. \item Processor-Sharing: \cite{aalto2007beyond}. \item Foreground-Background: \cite{nuijens2004foreground,rai2003analysis}. \end{itemize}
{ "content_hash": "fd3ac82ee7cd561e72bbd00258704fc1", "timestamp": "", "source": "github", "line_count": 45, "max_line_length": 124, "avg_line_length": 27.622222222222224, "alnum_prop": 0.7972646822204345, "repo_name": "gmarciani/research", "id": "a97cf0827d46431d6c3e8642932f0ae6b4833664", "size": "1243", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "performance-modeling/sec/related-readings.tex", "mode": "33261", "license": "mit", "language": [ { "name": "Gnuplot", "bytes": "658" }, { "name": "HTML", "bytes": "59426" }, { "name": "TeX", "bytes": "2258225" } ], "symlink_target": "" }
@font-face { font-family: 'Roboto Condensed'; src: url('RobotoCondensed-Light-webfont.eot'); src: url('RobotoCondensed-Light-webfont.eot?#iefix') format('embedded-opentype'), url('RobotoCondensed-Light-webfont.woff') format('woff'), url('RobotoCondensed-Light-webfont.ttf') format('truetype'), url('RobotoCondensed-Light-webfont.svg#roboto_condensedlight') format('svg'); font-weight: 300; font-style: normal; }
{ "content_hash": "bd627b1cf897253b4719e5be717cd28a", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 86, "avg_line_length": 38.416666666666664, "alnum_prop": 0.6789587852494577, "repo_name": "gsavin/gsavin.github.io", "id": "bd220751b0ea45cdafaaf2c1bf39b17caf3226ab", "size": "461", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "fonts/roboto_condensed/roboto_lightcondensed_macroman/stylesheet.css", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "454196" }, { "name": "HTML", "bytes": "697606" }, { "name": "JavaScript", "bytes": "168339" }, { "name": "Ruby", "bytes": "6993" } ], "symlink_target": "" }
Change Log ========== *No releases yet...*
{ "content_hash": "52b9861ae80848b9cd4bce6458880e52", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 20, "avg_line_length": 10.75, "alnum_prop": 0.5116279069767442, "repo_name": "carlovanhoutte/android-bank-finder", "id": "3b051f809b9906adbaea63955e9fa610d4f98b92", "size": "43", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "CHANGELOG.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<div> Usa <a href="people">a própria lista de usuários do Hudson</a> para fazer a autenticação, ao invés de delegar isto para um sistema externo. Isto é indicado para uma configuração simples onde você não tem uma base de usuário em lugar algum. </div>
{ "content_hash": "960a3113f029fe7a841ccc7a51e6667b", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 91, "avg_line_length": 43.333333333333336, "alnum_prop": 0.75, "repo_name": "vivek/hudson", "id": "29eebc6fa3e5c05d6febec01067a7859a00787f8", "size": "260", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "war/resources/help/security/private-realm_pt_BR.html", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "2091" }, { "name": "Groovy", "bytes": "44211" }, { "name": "Java", "bytes": "5159191" }, { "name": "JavaScript", "bytes": "102072" }, { "name": "PHP", "bytes": "70" }, { "name": "Perl", "bytes": "12839" }, { "name": "Python", "bytes": "2161" }, { "name": "Ruby", "bytes": "3822" }, { "name": "Shell", "bytes": "15373" } ], "symlink_target": "" }
@interface NSArray (Add) - (NSString *)jsonStringEncoded; @end
{ "content_hash": "c814522b87feefb954cd2ba368c42f6f", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 32, "avg_line_length": 13, "alnum_prop": 0.7230769230769231, "repo_name": "LarryPage/AutoParser", "id": "3675d25118b41623a3a00ded83703c74f08f863e", "size": "244", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "AutoParser/SafeCategories/NSArray/NSArray+Add.h", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "97616" } ], "symlink_target": "" }
Downstream consumers of Content API updates are not always be interested in referent updates, or may not be equally concerned with all types of referent updates. Currently, Content API updates do not provide any metadata about what changed in a document. This puts the onus on consumers to either process every update, regardless of source, or manually track state and compare the update with the current state to determine if processing is necessary. ## Proposed Solution ## Add trigger metadata to outgoing updates which reflects the _primary trigger event_ that triggered the content api operation. ``` { "id" : "default_false_XYZ123", "type": "insert-story", "version" : "0.5.9", ... "trigger": { "type": "image", "id": "AB456", } } ``` * *trigger.type* - Indicates the type of input that caused the operation. Possible values: "story", "gallery", "image", "video", "url", "site", "author" (Later, perhaps, "clavis"). * *trigger.id* - The id of the input document, if any, that caused the operation. * *trigger.referent_update* - If true, this update was triggered indirectly. ## Implications ## These new fields should be an optimization only. There is no new information added by these fields that could not be determined by diffing the state or consuming the trigger operations from the relevant primary source services. These will not be guaranteed to be present in all cases by Content API, but they will be guaranteed to be correct if present. There should be no effect for existing consumers. The fields are completely ignorable if you are already consuming and processing all updates. ## Questions ## ### Why not just provide a separate stream of full diffs like Dynamo/Kinesis? ### This would be desirable in some ways but would necessitate new logic from all downstream consumers to take full advantage of it. Barring additional limitations, it would also increase the potential maximum message size (already we have pushed Kafka's max message size to 10MB.) ### What is the point of `trigger.referent_update`? Isn't it the same as `(type.indexOf(trigger.type) > -1 && (id.indexOf(trigger.id) > -1)`? ### No. Since ANS documents can include references to themselves, it is possible for an update to a single document to also trigger referent updates to that same document.
{ "content_hash": "721c9412157b7815b2e5d3a2a8ebb002", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 451, "avg_line_length": 54.02325581395349, "alnum_prop": 0.753336203185536, "repo_name": "washingtonpost/ans-schema", "id": "0ab0509bb25d4d8ee79ed1f1ab8b28a9c2d73018", "size": "2361", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "docs/proposals/2017-08-03_Source_Metadata_on_Content_Operations.md", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "397908" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc --> <title>org.robolectric.shadows.gms.common Class Hierarchy</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> <link rel="stylesheet" type="text/css" href="../../../../../jquery/jquery-ui.css" title="Style"> <script type="text/javascript" src="../../../../../script.js"></script> <script type="text/javascript" src="../../../../../jquery/jszip/dist/jszip.min.js"></script> <script type="text/javascript" src="../../../../../jquery/jszip-utils/dist/jszip-utils.min.js"></script> <!--[if IE]> <script type="text/javascript" src="../../../../../jquery/jszip-utils/dist/jszip-utils-ie.min.js"></script> <![endif]--> <script type="text/javascript" src="../../../../../jquery/jquery-1.10.2.js"></script> <script type="text/javascript" src="../../../../../jquery/jquery-ui.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="org.robolectric.shadows.gms.common Class Hierarchy"; } } catch(err) { } //--> var pathtoroot = "../../../../../";loadScripts(document, 'script');</script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <div class="fixedNav"> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li>Class</li> <li class="navBarCell1Rev">Tree</li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><ul class="navList" style="font-size: 1.5em;"><li>Robolectric 4.3 | <a href="/" target="_top"><img src="http://robolectric.org/images/logo-with-bubbles-down.png" style="max-height: 18pt; vertical-align: sub;"/></a></li></ul></div> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../org/robolectric/shadows/gms/package-tree.html">Prev</a></li> <li><a href="../../../../../org/robolectric/shadows/httpclient/package-tree.html">Next</a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/robolectric/shadows/gms/common/package-tree.html" target="_top">Frames</a></li> <li><a href="package-tree.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <ul class="navListSearch"> <li><span>SEARCH:&nbsp;</span> <input type="text" id="search" value=" " disabled="disabled"> <input type="reset" id="reset" value=" " disabled="disabled"> </li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> </div> <div class="navPadding">&nbsp;</div> <div class="header"> <h1 class="title">Hierarchy For Package org.robolectric.shadows.gms.common</h1> <span class="packageHierarchyLabel">Package Hierarchies:</span> <ul class="horizontal"> <li><a href="../../../../../overview-tree.html">All Packages</a></li> </ul> </div> <div class="contentContainer"> <h2 title="Class Hierarchy">Class Hierarchy</h2> <ul> <li class="circle">java.lang.<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang"><span class="typeNameLink">Object</span></a> <ul> <li class="circle">org.robolectric.shadows.gms.common.<a href="../../../../../org/robolectric/shadows/gms/common/ShadowGoogleApiAvailability.html" title="class in org.robolectric.shadows.gms.common"><span class="typeNameLink">ShadowGoogleApiAvailability</span></a></li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li>Class</li> <li class="navBarCell1Rev">Tree</li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><ul class="navList" style="font-size: 1.5em;"><li>Robolectric 4.3 | <a href="/" target="_top"><img src="http://robolectric.org/images/logo-with-bubbles-down.png" style="max-height: 18pt; vertical-align: sub;"/></a></li></ul><script type="text/javascript" src="../../../../../highlight.pack.js"></script> <script type="text/javascript"><!-- hljs.initHighlightingOnLoad(); //--></script></div> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../org/robolectric/shadows/gms/package-tree.html">Prev</a></li> <li><a href="../../../../../org/robolectric/shadows/httpclient/package-tree.html">Next</a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/robolectric/shadows/gms/common/package-tree.html" target="_top">Frames</a></li> <li><a href="package-tree.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
{ "content_hash": "2438b124f02556a2e1a4dbe54600cc77", "timestamp": "", "source": "github", "line_count": 163, "max_line_length": 330, "avg_line_length": 41.061349693251536, "alnum_prop": 0.6282683400567758, "repo_name": "robolectric/robolectric.github.io", "id": "13e79bb20d8850cd2c84313915c625fe4161766c", "size": "6693", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "javadoc/4.3/org/robolectric/shadows/gms/common/package-tree.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "132673" }, { "name": "HTML", "bytes": "277730" }, { "name": "JavaScript", "bytes": "24371" }, { "name": "Ruby", "bytes": "1051" }, { "name": "SCSS", "bytes": "64100" }, { "name": "Shell", "bytes": "481" } ], "symlink_target": "" }
namespace ui { LayerAnimationSequence::LayerAnimationSequence() : properties_(LayerAnimationElement::UNKNOWN), is_repeating_(false), last_element_(0), waiting_for_group_start_(false), animation_group_id_(0), last_progressed_fraction_(0.0) {} LayerAnimationSequence::LayerAnimationSequence( std::unique_ptr<LayerAnimationElement> element) : properties_(LayerAnimationElement::UNKNOWN), is_repeating_(false), last_element_(0), waiting_for_group_start_(false), animation_group_id_(0), last_progressed_fraction_(0.0) { AddElement(std::move(element)); } LayerAnimationSequence::~LayerAnimationSequence() { for (auto& observer : observers_) observer.DetachedFromSequence(this, true); } void LayerAnimationSequence::Start(LayerAnimationDelegate* delegate) { DCHECK(start_time_ != base::TimeTicks()); last_progressed_fraction_ = 0.0; if (elements_.empty()) return; elements_[0]->set_requested_start_time(start_time_); elements_[0]->Start(delegate, animation_group_id_); NotifyStarted(); // This may have been aborted. } void LayerAnimationSequence::Progress(base::TimeTicks now, LayerAnimationDelegate* delegate) { DCHECK(start_time_ != base::TimeTicks()); bool redraw_required = false; if (elements_.empty()) return; if (last_element_ == 0) last_start_ = start_time_; size_t current_index = last_element_ % elements_.size(); bool just_completed_sequence = false; base::TimeDelta element_duration; while (is_repeating_ || last_element_ < elements_.size()) { elements_[current_index]->set_requested_start_time(last_start_); if (!elements_[current_index]->IsFinished(now, &element_duration)) break; // Let the element we're passing finish. if (elements_[current_index]->ProgressToEnd(delegate)) redraw_required = true; last_start_ += element_duration; ++last_element_; last_progressed_fraction_ = elements_[current_index]->last_progressed_fraction(); current_index = last_element_ % elements_.size(); DCHECK_GT(last_element_, 0u); just_completed_sequence = current_index == 0; } if (is_repeating_ || last_element_ < elements_.size()) { if (!elements_[current_index]->Started()) { animation_group_id_ = cc::AnimationIdProvider::NextGroupId(); elements_[current_index]->Start(delegate, animation_group_id_); } base::WeakPtr<LayerAnimationSequence> alive(AsWeakPtr()); if (elements_[current_index]->Progress(now, delegate)) redraw_required = true; if (!alive) return; last_progressed_fraction_ = elements_[current_index]->last_progressed_fraction(); } // Since the delegate may be deleted due to the notifications below, it is // important that we schedule a draw before sending them. if (redraw_required) delegate->ScheduleDrawForAnimation(); if (just_completed_sequence) { if (!is_repeating_) { last_element_ = 0; waiting_for_group_start_ = false; animation_group_id_ = 0; NotifyEnded(); } else { NotifyWillRepeat(); } } } bool LayerAnimationSequence::IsFinished(base::TimeTicks time) { if (is_repeating_ || waiting_for_group_start_) return false; if (elements_.empty()) return true; if (last_element_ == 0) last_start_ = start_time_; base::TimeTicks current_start = last_start_; size_t current_index = last_element_; base::TimeDelta element_duration; while (current_index < elements_.size()) { elements_[current_index]->set_requested_start_time(current_start); if (!elements_[current_index]->IsFinished(time, &element_duration)) break; current_start += element_duration; ++current_index; } return (current_index == elements_.size()); } void LayerAnimationSequence::ProgressToEnd(LayerAnimationDelegate* delegate) { bool redraw_required = false; if (elements_.empty()) return; size_t current_index = last_element_ % elements_.size(); while (current_index < elements_.size()) { if (elements_[current_index]->ProgressToEnd(delegate)) redraw_required = true; last_progressed_fraction_ = elements_[current_index]->last_progressed_fraction(); ++current_index; ++last_element_; } if (redraw_required) delegate->ScheduleDrawForAnimation(); if (!is_repeating_) { last_element_ = 0; waiting_for_group_start_ = false; animation_group_id_ = 0; NotifyEnded(); } else { NotifyWillRepeat(); } } void LayerAnimationSequence::GetTargetValue( LayerAnimationElement::TargetValue* target) const { if (is_repeating_) return; for (size_t i = last_element_; i < elements_.size(); ++i) elements_[i]->GetTargetValue(target); } void LayerAnimationSequence::Abort(LayerAnimationDelegate* delegate) { size_t current_index = last_element_ % elements_.size(); while (current_index < elements_.size()) { elements_[current_index]->Abort(delegate); ++current_index; } last_element_ = 0; waiting_for_group_start_ = false; NotifyAborted(); } void LayerAnimationSequence::AddElement( std::unique_ptr<LayerAnimationElement> element) { properties_ |= element->properties(); elements_.push_back(std::move(element)); } bool LayerAnimationSequence::HasConflictingProperty( LayerAnimationElement::AnimatableProperties other) const { return (properties_ & other) != LayerAnimationElement::UNKNOWN; } bool LayerAnimationSequence::IsFirstElementThreaded( LayerAnimationDelegate* delegate) const { if (!elements_.empty()) return elements_[0]->IsThreaded(delegate); return false; } void LayerAnimationSequence::AddObserver(LayerAnimationObserver* observer) { if (!observers_.HasObserver(observer)) { observers_.AddObserver(observer); observer->AttachedToSequence(this); } } void LayerAnimationSequence::RemoveObserver(LayerAnimationObserver* observer) { observers_.RemoveObserver(observer); observer->DetachedFromSequence(this, true); } void LayerAnimationSequence::OnThreadedAnimationStarted( base::TimeTicks monotonic_time, cc::TargetProperty::Type target_property, int group_id) { if (elements_.empty() || group_id != animation_group_id_) return; size_t current_index = last_element_ % elements_.size(); LayerAnimationElement::AnimatableProperties element_properties = elements_[current_index]->properties(); LayerAnimationElement::AnimatableProperty event_property = LayerAnimationElement::ToAnimatableProperty(target_property); DCHECK(element_properties & event_property); elements_[current_index]->set_effective_start_time(monotonic_time); } void LayerAnimationSequence::OnScheduled() { NotifyScheduled(); } void LayerAnimationSequence::OnAnimatorDestroyed() { for (LayerAnimationObserver& observer : observers_) { if (!observer.RequiresNotificationWhenAnimatorDestroyed()) { // Remove the observer, but do not allow notifications to be sent. observers_.RemoveObserver(&observer); observer.DetachedFromSequence(this, false); } } } void LayerAnimationSequence::OnAnimatorAttached( LayerAnimationDelegate* delegate) { for (LayerAnimationObserver& observer : observers_) observer.OnAnimatorAttachedToTimeline(); } void LayerAnimationSequence::OnAnimatorDetached() { for (LayerAnimationObserver& observer : observers_) observer.OnAnimatorDetachedFromTimeline(); } size_t LayerAnimationSequence::size() const { return elements_.size(); } LayerAnimationElement* LayerAnimationSequence::FirstElement() const { if (elements_.empty()) { return nullptr; } return elements_[0].get(); } void LayerAnimationSequence::NotifyScheduled() { for (auto& observer : observers_) observer.OnLayerAnimationScheduled(this); } void LayerAnimationSequence::NotifyStarted() { for (auto& observer : observers_) observer.OnLayerAnimationStarted(this); } void LayerAnimationSequence::NotifyEnded() { for (auto& observer : observers_) observer.OnLayerAnimationEnded(this); } void LayerAnimationSequence::NotifyWillRepeat() { for (auto& observer : observers_) observer.OnLayerAnimationWillRepeat(this); } void LayerAnimationSequence::NotifyAborted() { for (auto& observer : observers_) observer.OnLayerAnimationAborted(this); } LayerAnimationElement* LayerAnimationSequence::CurrentElement() const { if (elements_.empty()) return NULL; size_t current_index = last_element_ % elements_.size(); return elements_[current_index].get(); } std::string LayerAnimationSequence::ElementsToString() const { std::string str; for (size_t i = 0; i < elements_.size(); i++) { if (i > 0) str.append(", "); str.append(elements_[i]->ToString()); } return str; } std::string LayerAnimationSequence::ToString() const { return base::StringPrintf( "LayerAnimationSequence{size=%zu, properties=%s, " "elements=[%s], is_repeating=%d, group_id=%d}", size(), LayerAnimationElement::AnimatablePropertiesToString(properties_).c_str(), ElementsToString().c_str(), is_repeating_, animation_group_id_); } } // namespace ui
{ "content_hash": "3ed959fe5e39a7ac484486871b17f68b", "timestamp": "", "source": "github", "line_count": 313, "max_line_length": 79, "avg_line_length": 29.396166134185304, "alnum_prop": 0.6972068253450712, "repo_name": "chromium/chromium", "id": "41bf59c71c2cc3db1b94803dbc2e3cdb063f7f0f", "size": "9757", "binary": false, "copies": "6", "ref": "refs/heads/main", "path": "ui/compositor/layer_animation_sequence.cc", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
import numpy as np import grizzly.numpy_weld as npw import pandas as pd import grizzly.grizzly as gr import time # Get data (NYC 311 service request dataset) and start cleanup raw_data = pd.read_csv('data/us_cities_states_counties.csv', delimiter='|') raw_data.dropna(inplace=True) data = gr.DataFrameWeld(raw_data) print "Done reading input file..." start = time.time() # Get all city information with total population greater than 500,000 data_big_cities = data[data["Total population"] > 500000] data_big_cities_new_df = data_big_cities[["State short"]] # Compute "crime index" proportional to # exp((Total population + 2*(Total adult population) - 2000*(Number of # robberies)) / 100000) data_big_cities_stats = data_big_cities[ ["Total population", "Total adult population", "Number of robberies"]].values predictions = npw.exp(npw.dot(data_big_cities_stats, np.array( [1, 2, -2000], dtype=np.int64)) / 100000.0) predictions = predictions / predictions.sum() data_big_cities_new_df["Crime index"] = predictions # Aggregate "crime index" scores by state data_big_cities_grouped_df = data_big_cities_new_df.groupby( "State short").sum() print sorted(["%.4f" % ele for ele in data_big_cities_grouped_df.evaluate().to_pandas()["Crime index"]]) end = time.time() print "Total end-to-end time: %.2f" % (end - start)
{ "content_hash": "9997e9f52dfc53531d7557d0b64e81be", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 104, "avg_line_length": 38.08571428571429, "alnum_prop": 0.7231807951987997, "repo_name": "weld-project/weld", "id": "63d00176bbe089df2073661c5f13efe6dc0aa3cf", "size": "1373", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "examples/python/grizzly/get_population_stats_grizzly.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "799" }, { "name": "C", "bytes": "660" }, { "name": "C++", "bytes": "27987" }, { "name": "Makefile", "bytes": "2660" }, { "name": "Python", "bytes": "367344" }, { "name": "Rust", "bytes": "1126668" }, { "name": "Shell", "bytes": "2090" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>angles: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.14.1 / angles - 8.7.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> angles <small> 8.7.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-10-28 17:55:27 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-10-28 17:55:27 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils conf-gmp 4 Virtual package relying on a GMP lib system installation coq 8.14.1 Formal proof management system dune 3.4.1 Fast, portable, and opinionated build system ocaml 4.08.1 The OCaml compiler (virtual package) ocaml-base-compiler 4.08.1 Official release 4.08.1 ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.5 A library manager for OCaml zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;Hugo.Herbelin@inria.fr&quot; homepage: &quot;https://github.com/coq-contribs/angles&quot; license: &quot;Unknown&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/Angles&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.7&quot; &amp; &lt; &quot;8.8~&quot;} ] tags: [ &quot;keyword: Pcoq&quot; &quot;keyword: geometry&quot; &quot;keyword: plane geometry&quot; &quot;keyword: oriented angles&quot; &quot;category: Mathematics/Geometry/General&quot; &quot;date: 2002-01-15&quot; ] authors: [ &quot;Frédérique Guilhot &lt;Frederique.Guilhot@sophia.inria.fr&gt;&quot; ] bug-reports: &quot;https://github.com/coq-contribs/angles/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/angles.git&quot; synopsis: &quot;Formalization of the oriented angles theory&quot; description: &quot;&quot;&quot; The basis of the contribution is a formalization of the theory of oriented angles of non-zero vectors. Then, we prove some classical plane geometry theorems: the theorem which gives a necessary and sufficient condition so that four points are cocyclic, the one which shows that the reflected points with respect to the sides of a triangle orthocenter are on its circumscribed circle, the Simson&#39;s theorem and the Napoleon&#39;s theorem. The reader can refer to the associated research report (http://www-sop.inria.fr/lemme/FGRR.ps) and the README file of the contribution.&quot;&quot;&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/angles/archive/v8.7.0.tar.gz&quot; checksum: &quot;md5=b9f406e5520b5fb3ad63bd88de4a035a&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-angles.8.7.0 coq.8.14.1</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.14.1). The following dependencies couldn&#39;t be met: - coq-angles -&gt; coq &lt; 8.8~ -&gt; ocaml &lt; 4.06.0 base of this switch (use `--unlock-base&#39; to force) Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-angles.8.7.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{ "content_hash": "ddfd524186c252d93160a21c32979c72", "timestamp": "", "source": "github", "line_count": 173, "max_line_length": 218, "avg_line_length": 43.45086705202312, "alnum_prop": 0.5621923639749901, "repo_name": "coq-bench/coq-bench.github.io", "id": "64b5c30260e4649c6b473a8708c3710a595fe47a", "size": "7544", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.08.1-2.0.5/released/8.14.1/angles/8.7.0.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
""" size_compare.py Compare the compiled size of two revisions. Usage: size_compare.py [-h|--help] [target_ref] [base_ref] if no arguments are passed, compares HEAD to master. if just `target_ref` is set, compares HEAD to `target_ref` if `base_ref` is set, compares `target_ref` to `base_ref`.""" import subprocess import sys import os RUST_TARGET_NAME = 'xi-core' def main(): if not os.path.exists('./target'): print("no target directory found, are you running this in \ xi-editor/rust?") return 1 args = sys.argv[1:] if len(args) > 2 or len(args) == 1 and args[0] in ("-h", "--help", "help"): return print_help() base_rev = "master" cur_rev = "HEAD" if len(args) == 1: base_rev = args[0] if len(args) == 2: cur_rev = args[1] if not working_directory_is_clean(): print("Your working directory has unsaved changes. Stash or commit \ your changes and try again") return 2 return compare_revs(base_rev, cur_rev) def print_help(): print(__doc__) return 2 def resolve_rev(rev_id): """Given an arbitrary git revision id, returns the commit's hash""" try: output = subprocess.check_output("git rev-parse {}".format(rev_id), shell=True) return output.decode('utf-8').strip() except subprocess.CalledProcessError as err: print("failed to resolve rev_id {}: {}".format(rev_id, err)) return None def compare_revs(base_rev, cur_rev): base_sha = resolve_rev(base_rev) cur_sha = resolve_rev(cur_rev) if base_sha is None: print("could not resolve ref '{}'".format(base_rev)) return print_help() if cur_sha is None: print("could not resolve ref '{}'".format(cur_rev)) return print_help() if base_sha == cur_sha: print("refs are the same: {}, {}".format(base_rev, cur_rev)) return print_help() cur_size = compile_size_for_commit(cur_sha) base_size = compile_size_for_commit(base_sha) base_str = base_rev + " " + base_sha[:8] cur_str = cur_rev + " " + cur_sha[:8] print_compare(base_str, cur_str, base_size, cur_size) def print_compare(base_str, cur_str, base_size, cur_size): size_delta = base_size - cur_size delta_change = "smaller" if size_delta > 0 else "bigger" pad_size = max(len(base_str), len(cur_str)) + 4 fmt_string = '{:<' + str(pad_size) + '}{}' print(fmt_string.format(base_str, sizeof_fmt(base_size))) print(fmt_string.format(cur_str, sizeof_fmt(cur_size))) if base_size != cur_size: print("{} is {} {} than {}".format(cur_str, sizeof_fmt(abs(size_delta)), delta_change, base_str)) else: print("revisions are equal") # https://stackoverflow.com/questions/1094841/reusable-library-to-get-human-readable-version-of-file-size def sizeof_fmt(num, suffix='B'): for unit in ['','Ki','Mi','Gi','Ti','Pi','Ei','Zi']: if abs(num) < 1024.0: return "%3.3f%s%s" % (num, unit, suffix) num /= 1024.0 return "%.1f%s%s" % (num, 'Yi', suffix) def compile_size_for_commit(sha): subprocess.check_output("git checkout {}".format(sha), shell=True) try: subprocess.check_output("cargo build --release".format(sha), shell=True) except subprocess.CalledProcessError as err: return "{} exited with {}: {}".format(sha, err.returncode, err.output or "") ls_output = subprocess.check_output("ls -l target/release/{}".format(RUST_TARGET_NAME), shell=True) file_size = int(ls_output.split()[4].decode('utf-8')) return file_size def working_directory_is_clean(): try: subprocess.check_call("git diff-index --quiet HEAD --", shell=True) return True except subprocess.CalledProcessError: return False if __name__ == "__main__": main()
{ "content_hash": "e47bee7a2e325bada31080ea176a6ee8", "timestamp": "", "source": "github", "line_count": 123, "max_line_length": 105, "avg_line_length": 31.30081300813008, "alnum_prop": 0.614025974025974, "repo_name": "google/xi-editor", "id": "83d03c88cd606f649cd65d4c5364a2a9cb737a82", "size": "3875", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "rust/compile_size_compare.py", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "3953" }, { "name": "Makefile", "bytes": "2530" }, { "name": "Python", "bytes": "48717" }, { "name": "Rust", "bytes": "1154750" }, { "name": "Shell", "bytes": "465" } ], "symlink_target": "" }
<?xml version="1.0"?> <!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <project default="antunit" xmlns:au="antlib:org.apache.ant.antunit"> <import file="../antunit-base.xml" /> <target name="testModifiedDirectories" description="https://issues.apache.org/bugzilla/show_bug.cgi?id=39122 and https://issues.apache.org/bugzilla/show_bug.cgi?id=44430"> <mkdir dir="${input}/source"/> <mkdir dir="${output}"/> <sleep seconds="2"/> <touch file="${input}/source/file"/> <au:assertFalse> <uptodate> <srcresources> <fileset dir="${input}"/> <dirset dir="${input}"/> </srcresources> <globmapper from="*" to="${output}/*"/> </uptodate> </au:assertFalse> <mkdir dir="${output}/source"/> <touch file="${output}/source/file"/> <au:assertTrue> <uptodate targetfile="${output}"> <srcresources> <fileset dir="${input}"/> <dirset dir="${input}"/> </srcresources> <globmapper from="*" to="${output}/*"/> </uptodate> </au:assertTrue> <sleep seconds="2"/> <touch> <file file="${input}/source"/> </touch> <au:assertFalse> <uptodate targetfile="${output}"> <srcresources> <fileset dir="${input}"/> <dirset dir="${input}"/> </srcresources> <globmapper from="*" to="${output}/*"/> </uptodate> </au:assertFalse> <touch> <file file="${output}/source"/> </touch> <au:assertTrue> <uptodate targetfile="${output}"> <srcresources> <fileset dir="${input}"/> <dirset dir="${input}"/> </srcresources> <globmapper from="*" to="${output}/*"/> </uptodate> </au:assertTrue> <sleep seconds="2"/> <delete file="${input}/source/file"/> <au:assertFalse> <uptodate targetfile="${output}"> <srcresources> <fileset dir="${input}"/> <dirset dir="${input}"/> </srcresources> <globmapper from="*" to="${output}/*"/> </uptodate> </au:assertFalse> </target> </project>
{ "content_hash": "f4721cbf616b055ecd2860e5332e7c24", "timestamp": "", "source": "github", "line_count": 86, "max_line_length": 81, "avg_line_length": 33.7906976744186, "alnum_prop": 0.5905024088093599, "repo_name": "Mayo-WE01051879/mayosapp", "id": "e477803e6f44530db1f38d7d7d6ef501b42b3edf", "size": "2906", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Build/src/tests/antunit/taskdefs/uptodate-test.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "27841" }, { "name": "CSS", "bytes": "6179" }, { "name": "GAP", "bytes": "36428" }, { "name": "HTML", "bytes": "2189621" }, { "name": "Java", "bytes": "8854706" }, { "name": "JavaScript", "bytes": "34849" }, { "name": "Perl", "bytes": "9844" }, { "name": "Python", "bytes": "3299" }, { "name": "Shell", "bytes": "25265" }, { "name": "XSLT", "bytes": "371927" } ], "symlink_target": "" }
/** * */ package org.pjay; import java.util.Random; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * @author vijayk * */ @RestController public class WordController { @Value("${words}") String words; @RequestMapping("/") public String getWord(){ String[] wordArray = words.split(","); Random random = new Random(); return wordArray[random.nextInt(wordArray.length)]; } // Below are Testing end points for verifying the end points registry keys with eureka server /* @RequestMapping("/hello") public String sayHello() { return "Hello Microservices"; } @RequestMapping("/hello/{username}") public String sayHelloUser(@PathVariable String username) { return "Hi there " + username; } @RequestMapping("/test") public String testMethod() { return "This is test endpoint response"; } */ }
{ "content_hash": "b5871cc066572c8fda2c6b86cf0fc98f", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 94, "avg_line_length": 22.130434782608695, "alnum_prop": 0.6856581532416502, "repo_name": "konduruvijaykumar/spring-cloud-boot-lab", "id": "a0cfb0c06abe894329cdc7702960342a84e88347", "size": "1018", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lab4-concise/restservices-all-solution/src/main/java/org/pjay/WordController.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "13458" }, { "name": "HTML", "bytes": "7706" }, { "name": "Java", "bytes": "419891" }, { "name": "Shell", "bytes": "2018" } ], "symlink_target": "" }
require "test_helper" class Taxonomy::RedisCacheAdapterTest < ActiveSupport::TestCase def subject Taxonomy::RedisCacheAdapter.new( redis_client:, adapter: publishing_api_adapter, ) end def redis_client @redis_client ||= stub end def publishing_api_adapter @publishing_api_adapter ||= stub end test "#rebuild_caches" do published_taxons = { "baz" => "qux" } publishing_api_adapter.stubs(:taxon_data).returns(published_taxons) redis_client.expects(:set).with("topic_taxonomy_taxons", JSON.dump(published_taxons)) subject.rebuild_caches end test "#rebuild_world_taxon_caches" do published_world_taxons = { "baz" => "qux" } publishing_api_adapter.stubs(:world_taxon_data).returns(published_world_taxons) redis_client.expects(:set).with("world_taxonomy_taxons", JSON.dump(published_world_taxons)) subject.rebuild_world_taxon_caches end end
{ "content_hash": "2b5ad51367814e5b4384b3de2f0fe881", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 95, "avg_line_length": 28.75, "alnum_prop": 0.7043478260869566, "repo_name": "alphagov/whitehall", "id": "a5d375215f7bc89c3c5b859217e4a128392aff43", "size": "920", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "test/unit/taxonomy/redis_cache_adapter_test.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "3039" }, { "name": "Gherkin", "bytes": "82444" }, { "name": "HTML", "bytes": "695467" }, { "name": "JavaScript", "bytes": "250602" }, { "name": "Procfile", "bytes": "117" }, { "name": "Ruby", "bytes": "5239261" }, { "name": "SCSS", "bytes": "180354" }, { "name": "Shell", "bytes": "3870" } ], "symlink_target": "" }
package org.apache.spark.sql.execution.datasources.v2 import java.util import scala.collection.JavaConverters._ import org.apache.hadoop.fs.{FileStatus, Path} import org.apache.spark.sql.SparkSession import org.apache.spark.sql.connector.catalog.{SupportsRead, SupportsWrite, Table, TableCapability} import org.apache.spark.sql.connector.catalog.TableCapability._ import org.apache.spark.sql.connector.expressions.Transform import org.apache.spark.sql.errors.QueryCompilationErrors import org.apache.spark.sql.execution.datasources._ import org.apache.spark.sql.execution.streaming.{FileStreamSink, MetadataLogFileIndex} import org.apache.spark.sql.types.{DataType, StructType} import org.apache.spark.sql.util.CaseInsensitiveStringMap import org.apache.spark.sql.util.SchemaUtils abstract class FileTable( sparkSession: SparkSession, options: CaseInsensitiveStringMap, paths: Seq[String], userSpecifiedSchema: Option[StructType]) extends Table with SupportsRead with SupportsWrite { import org.apache.spark.sql.connector.catalog.CatalogV2Implicits._ lazy val fileIndex: PartitioningAwareFileIndex = { val caseSensitiveMap = options.asCaseSensitiveMap.asScala.toMap // Hadoop Configurations are case sensitive. val hadoopConf = sparkSession.sessionState.newHadoopConfWithOptions(caseSensitiveMap) if (FileStreamSink.hasMetadata(paths, hadoopConf, sparkSession.sessionState.conf)) { // We are reading from the results of a streaming query. We will load files from // the metadata log instead of listing them using HDFS APIs. new MetadataLogFileIndex(sparkSession, new Path(paths.head), options.asScala.toMap, userSpecifiedSchema) } else { // This is a non-streaming file based datasource. val rootPathsSpecified = DataSource.checkAndGlobPathIfNecessary(paths, hadoopConf, checkEmptyGlobPath = true, checkFilesExist = true, enableGlobbing = globPaths) val fileStatusCache = FileStatusCache.getOrCreate(sparkSession) new InMemoryFileIndex( sparkSession, rootPathsSpecified, caseSensitiveMap, userSpecifiedSchema, fileStatusCache) } } lazy val dataSchema: StructType = { val schema = userSpecifiedSchema.map { schema => val partitionSchema = fileIndex.partitionSchema val resolver = sparkSession.sessionState.conf.resolver StructType(schema.filterNot(f => partitionSchema.exists(p => resolver(p.name, f.name)))) }.orElse { inferSchema(fileIndex.allFiles()) }.getOrElse { throw QueryCompilationErrors.dataSchemaNotSpecifiedError(formatName) } fileIndex match { case _: MetadataLogFileIndex => schema case _ => schema.asNullable } } override lazy val schema: StructType = { val caseSensitive = sparkSession.sessionState.conf.caseSensitiveAnalysis SchemaUtils.checkSchemaColumnNameDuplication(dataSchema, "in the data schema", caseSensitive) dataSchema.foreach { field => if (!supportsDataType(field.dataType)) { throw QueryCompilationErrors.dataTypeUnsupportedByDataSourceError(formatName, field) } } val partitionSchema = fileIndex.partitionSchema SchemaUtils.checkSchemaColumnNameDuplication(partitionSchema, "in the partition schema", caseSensitive) val partitionNameSet: Set[String] = partitionSchema.fields.map(PartitioningUtils.getColName(_, caseSensitive)).toSet // When data and partition schemas have overlapping columns, // tableSchema = dataSchema - overlapSchema + partitionSchema val fields = dataSchema.fields.filterNot { field => val colName = PartitioningUtils.getColName(field, caseSensitive) partitionNameSet.contains(colName) } ++ partitionSchema.fields StructType(fields) } override def partitioning: Array[Transform] = fileIndex.partitionSchema.names.toSeq.asTransforms override def properties: util.Map[String, String] = options.asCaseSensitiveMap override def capabilities: java.util.Set[TableCapability] = FileTable.CAPABILITIES /** * When possible, this method should return the schema of the given `files`. When the format * does not support inference, or no valid files are given should return None. In these cases * Spark will require that user specify the schema manually. */ def inferSchema(files: Seq[FileStatus]): Option[StructType] /** * Returns whether this format supports the given [[DataType]] in read/write path. * By default all data types are supported. */ def supportsDataType(dataType: DataType): Boolean = true /** * The string that represents the format that this data source provider uses. This is * overridden by children to provide a nice alias for the data source. For example: * * {{{ * override def formatName(): String = "ORC" * }}} */ def formatName: String /** * Returns a V1 [[FileFormat]] class of the same file data source. * This is a solution for the following cases: * 1. File datasource V2 implementations cause regression. Users can disable the problematic data * source via SQL configuration and fall back to FileFormat. * 2. Catalog support is required, which is still under development for data source V2. */ def fallbackFileFormat: Class[_ <: FileFormat] /** * Whether or not paths should be globbed before being used to access files. */ private def globPaths: Boolean = { val entry = options.get(DataSource.GLOB_PATHS_KEY) Option(entry).map(_ == "true").getOrElse(true) } } object FileTable { private val CAPABILITIES = Set(BATCH_READ, BATCH_WRITE).asJava }
{ "content_hash": "fc4303e7693aa12e039dea6cdec6ec4b", "timestamp": "", "source": "github", "line_count": 138, "max_line_length": 99, "avg_line_length": 40.833333333333336, "alnum_prop": 0.7471162377994676, "repo_name": "milliman/spark", "id": "507feb2b595aa3a900b1acf24b6071e13dd49f26", "size": "6435", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/FileTable.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "52464" }, { "name": "Batchfile", "bytes": "27405" }, { "name": "C", "bytes": "1493" }, { "name": "CSS", "bytes": "24622" }, { "name": "Dockerfile", "bytes": "9429" }, { "name": "HTML", "bytes": "41560" }, { "name": "HiveQL", "bytes": "1859465" }, { "name": "Java", "bytes": "4316296" }, { "name": "JavaScript", "bytes": "221431" }, { "name": "Jupyter Notebook", "bytes": "4310524" }, { "name": "Makefile", "bytes": "2374" }, { "name": "PLpgSQL", "bytes": "352905" }, { "name": "PowerShell", "bytes": "3882" }, { "name": "Python", "bytes": "7191174" }, { "name": "R", "bytes": "1265563" }, { "name": "ReScript", "bytes": "240" }, { "name": "Roff", "bytes": "27389" }, { "name": "Scala", "bytes": "39048900" }, { "name": "Shell", "bytes": "229968" }, { "name": "Thrift", "bytes": "2016" }, { "name": "q", "bytes": "111129" } ], "symlink_target": "" }
package no.nextgentel.oss.akkatools.aggregate.aggregateTest_usingAggregateStateBase import java.util.UUID import akka.actor.{ActorPath, ActorSystem, PoisonPill, Props} import akka.persistence.{DeleteMessagesFailure, DeleteMessagesSuccess, SaveSnapshotFailure, SaveSnapshotSuccess, SnapshotMetadata, SnapshotOffer} import akka.testkit.{TestKit, TestProbe} import com.typesafe.config.ConfigFactory import no.nextgentel.oss.akkatools.aggregate._ import no.nextgentel.oss.akkatools.persistence.{DurableMessage, DurableMessageReceived} import no.nextgentel.oss.akkatools.testing.{AggregateStateGetter, AggregateTesting} import org.scalatest.{BeforeAndAfter, BeforeAndAfterAll, FunSuiteLike, Matchers} import org.slf4j.LoggerFactory /** * Testing aggregate using AggregateStateBase */ class GeneralAggregateBaseTest_usingAggregateStateBase(_system:ActorSystem) extends TestKit(_system) with FunSuiteLike with Matchers with BeforeAndAfterAll with BeforeAndAfter { def this() = this(ActorSystem("test-actor-system", ConfigFactory.load("application-test.conf"))) override def afterAll { TestKit.shutdownActorSystem(system) } val log = LoggerFactory.getLogger(getClass) private def generateId() = UUID.randomUUID().toString val seatIds = List("s1","id-used-in-Failed-in-onAfterValidationSuccess", "s2", "s3-This-id-is-going-to-be-discarded", "s4") trait TestEnv extends AggregateTesting[XState] { val id = generateId() val dest = TestProbe() val main = system.actorOf(Props( new XAggregate(null, dmForwardAndConfirm(dest.ref).path)), "XAggregate-" + id) def assertState(correctState:XState): Unit = { assert(getState() == correctState) } } test("basic flow") { new TestEnv { assertState(XState(0)) sendDMBlocking(main, AddValueCmd(0)) assertState(XState(2)) dest.expectMsg(ValueWasAdded(1)) dest.expectMsg(ValueWasAdded(2)) sendDMBlocking(main, AddValueCmd(2)) assertState(XState(4)) dest.expectMsg(ValueWasAdded(3)) dest.expectMsg(ValueWasAdded(4)) } } test("auto-handling when re-receiving idempotent dm-cmds") { new TestEnv { assertState(XState(0)) val sender = TestProbe() val confirmationRoutingInfo1 = "used-as-id-when-using-sharding" val dm1 = DurableMessage(1L, AddValueCmd(0), sender.ref.path, confirmationRoutingInfo1) main ! dm1 assertState(XState(2)) sender.expectMsg(DurableMessageReceived(1L, confirmationRoutingInfo1)) dest.expectMsg(ValueWasAdded(1)) dest.expectMsg(ValueWasAdded(2)) // Now we resend the first dm main ! dm1 // Assert that we get the DMReceived one more time, but the state should not have changed. sender.expectMsg(DurableMessageReceived(1L, confirmationRoutingInfo1)) assertState(XState(2)) // Should stay the same // We should NOT get the same ValueWasAdded again - we should not get any at all dest.expectNoMessage() // ---------------------------------------------- // Now we're sending another CMD - AddValueCmdSendingAckBackUsingDMInSuccessHandler - as dm2 // It will not confirm the DM directly, but send 'ack' back from it successhandler using sendAsDM which // will resend (with new payload) the original dm back to us. val dm2 = DurableMessage(2L, AddValueCmdSendingAckBackUsingDMInSuccessHandler(2), sender.ref.path, confirmationRoutingInfo1) sender.send(main, dm2) // Assert that we receive a new dm using the same info - but with 'ack' as payload sender.expectMsg(dm2.withNewPayload(s"ack-2")) assertState(XState(4)) dest.expectMsg(ValueWasAdded(3)) dest.expectMsg(ValueWasAdded(4)) // Now we resend dm2 sender.send(main, dm2) // Assert that we receive a new dm using the same info - but with 'ack' as payload sender.expectMsg(dm2.withNewPayload(s"ack-2")) assertState(XState(4)) // Should stay the same // We should NOT get the same ValueWasAdded again - we should not get any at all dest.expectNoMessage() } } test("test recovering") { new TestEnv { assertState(XState(0)) sendDMBlocking(main, AddValueCmd(0)) assertState(XState(2)) dest.expectMsg(ValueWasAdded(1)) dest.expectMsg(ValueWasAdded(2)) sendDMBlocking(main, AddValueCmd(2)) assertState(XState(4)) dest.expectMsg(ValueWasAdded(3)) dest.expectMsg(ValueWasAdded(4)) Thread.sleep(2000) // kill it system.stop(main) // Wait for it to die Thread.sleep(2000) // recreate it val dest2 = TestProbe() val recoveredMain = system.actorOf(Props( new XAggregate(null, dmForwardAndConfirm(dest2.ref).path)), "XAggregate-" + id) // get its state val recoveredState = AggregateStateGetter[Any](recoveredMain).getState(None).asInstanceOf[XState] assert( recoveredState == XState(4)) // make sure we get no msgs dest2.expectNoMessage() } } test("test recovering from snapshot") { new TestEnv { assertState(XState(0)) sendDMBlocking(main, AddValueCmd(0)) assertState(XState(2)) dest.expectMsg(ValueWasAdded(1)) dest.expectMsg(ValueWasAdded(2)) sendDMBlocking(main, AddValueCmd(2)) assertState(XState(4)) dest.expectMsg(ValueWasAdded(3)) dest.expectMsg(ValueWasAdded(4)) assertState(XState(4)) sendDMBlocking(main,SaveSnapshotOfCurrentState(None,true)) Thread.sleep(2000) // kill it system.stop(main) // Wait for it to die Thread.sleep(2000) // recreate it val dest2 = TestProbe() val recoveredMain = system.actorOf(Props( new XAggregate(null, dmForwardAndConfirm(dest2.ref).path)), "XAggregate-" + id) // get its state val recoveredState = AggregateStateGetter[Any](recoveredMain).getState(None).asInstanceOf[XState] assert( recoveredState == XState(4)) // make sure we get no msgs dest2.expectNoMsg() } } } trait XEvent case class XAddEvent(from:Int) extends XEvent case class XAddSecondEvent(from:Int) extends XEvent case class XState(value:Int) extends AggregateStateBase[XEvent, XState] { override def transitionState(event: XEvent): StateTransition[XEvent, XState] = { event match { case e:XAddEvent => if ( value == e.from) { StateTransition(XState(value + 1), newEvent = Some(XAddSecondEvent(value + 1))) } else throw new AggregateError("Invalid from-value") case e:XAddSecondEvent => if ( value == e.from) { StateTransition(XState(value + 1), None) } else throw new AggregateError("Invalid from-value") case e:Any => throw new AggregateError("Invalid event") } } } case class AddValueCmd(from:Int) extends AggregateCmd { override def id(): String = ??? } case class AddValueCmdSendingAckBackUsingDMInSuccessHandler(from:Int) extends AggregateCmd { override def id(): String = ??? } case class ValueWasAdded(newValue:Int) class XAggregate(dmSelf:ActorPath, dest:ActorPath) extends GeneralAggregateBase[XEvent, XState](dmSelf) { override var state: XState = XState(0) // Called AFTER event has been applied to state override def generateDMs(event: XEvent, previousState: XState): ResultingDMs = { event match { case e:XAddEvent => assert( (state.value - 1) == e.from ) assert( (state.value - 1) == previousState.value) ResultingDMs(ValueWasAdded(state.value), dest) case e:XAddSecondEvent => assert( (state.value - 1) == e.from ) assert( (state.value - 1) == previousState.value) ResultingDMs(ValueWasAdded(state.value), dest) case _ => ResultingDMs(List()) } } override def cmdToEvent: PartialFunction[AggregateCmd, ResultingEvent[XEvent]] = { case c:AddValueCmd => ResultingEvent(XAddEvent(c.from)) case c:AddValueCmdSendingAckBackUsingDMInSuccessHandler => ResultingEvent { XAddEvent(c.from) }.onSuccess { log.info(s"Success-handler: ending ack as DM back to ${sender.path} ") sendAsDM(s"ack-${c.from}", sender.path) } } /** * Always accepts a snapshot offer and makes a snapshot. * If that is a success it deletes the events. */ override def onSnapshotOffer(offer: SnapshotOffer): Unit = { state = offer.snapshot.asInstanceOf[XState] } override def acceptSnapshotRequest(req: SaveSnapshotOfCurrentState): Boolean = { true } override def onSnapshotSuccess(success: SaveSnapshotSuccess): Unit = { log.error("Snapshot succeeded") } override def onSnapshotFailure(failure: SaveSnapshotFailure): Unit = { log.error(s"Taking snapshot failed $failure") throw new Exception("Err",failure.cause) } override def onDeleteMessagesSuccess(success: DeleteMessagesSuccess): Unit = { log.error(s"Deleting messages succeeded $success") } override def onDeleteMessagesFailure(failure: DeleteMessagesFailure): Unit = { log.error(s"Deleting messages failed $failure") } // Used as prefix/base when constructing the persistenceId to use - the unique ID is extracted runtime from actorPath which is construced by Sharding-coordinator override def persistenceIdBase(): String = "/x/" }
{ "content_hash": "cd06cc843dacf0a792bc1cee0f277ea1", "timestamp": "", "source": "github", "line_count": 305, "max_line_length": 177, "avg_line_length": 30.81967213114754, "alnum_prop": 0.691063829787234, "repo_name": "mbknor/akka-tools", "id": "5d487c4608398e2badee26a137b879bda9062f96", "size": "9400", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "akka-tools-persistence/src/test/scala/no/nextgentel/oss/akkatools/aggregate/aggregateTest_usingAggregateStateBase/GeneralAggregateBaseTest_usingAggregateStateBase.scala", "mode": "33261", "license": "mit", "language": [ { "name": "Scala", "bytes": "213655" } ], "symlink_target": "" }
int main(int argc, char * argv[]) { @autoreleasepool { return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); } }
{ "content_hash": "a24b9398b3d7aa8cb3137d361499185b", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 90, "avg_line_length": 26.333333333333332, "alnum_prop": 0.6582278481012658, "repo_name": "xtreme-daniel-crampton/broken-navigation", "id": "e5eec18bc1bff670c00984edb427c811a3ca877b", "size": "347", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "BrokenNavigation/main.m", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "3910" } ], "symlink_target": "" }
package com.voxelwind.server.network.rcon; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufUtil; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.MessageToByteEncoder; import java.nio.ByteOrder; public class RconEncoder extends MessageToByteEncoder<RconMessage> { @Override protected void encode(ChannelHandlerContext ctx, RconMessage message, ByteBuf buf) throws Exception { ByteBuf leBuf = buf.order(ByteOrder.LITTLE_ENDIAN); // 4 bytes ID, 4 bytes type, 2 bytes of terminating zero(!) int fullLength = 10 + message.getBody().length(); leBuf.writeInt(fullLength); leBuf.writeInt(message.getId()); leBuf.writeInt(message.getType()); ByteBufUtil.writeUtf8(leBuf, message.getBody()); // 2 null bytes leBuf.writeByte(0); leBuf.writeByte(0); } }
{ "content_hash": "72c70787504ee953d0745d9acb62c37e", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 105, "avg_line_length": 35.24, "alnum_prop": 0.7094211123723042, "repo_name": "MylesIsCool/voxelwind", "id": "d407f03425f18d4ee07ebe50dd71d5f50482a9ac", "size": "881", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "server/src/main/java/com/voxelwind/server/network/rcon/RconEncoder.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "513973" }, { "name": "JavaScript", "bytes": "1410" } ], "symlink_target": "" }
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "87a677967c7123a6a0ad3b6c3e90c8c9", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.23076923076923, "alnum_prop": 0.6917293233082706, "repo_name": "mdoering/backbone", "id": "2afb2baa647cd8297002c922fd4a6739acb0168f", "size": "189", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Liliopsida/Alismatales/Ruppiaceae/Ruppia/Ruppia maritima/ Syn. Ruppia rostellata brachypus/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
@interface PodsDummy_ILGHttpConstants_OSX : NSObject @end @implementation PodsDummy_ILGHttpConstants_OSX @end
{ "content_hash": "310a07acbe1827e6d22f2f7c897aaff9", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 52, "avg_line_length": 27.5, "alnum_prop": 0.8454545454545455, "repo_name": "brockboland/VOKMockUrlProtocol", "id": "220850f6ecc05c52d12d3dc7c900f5bf03314659", "size": "144", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "Example/Pods/Target Support Files/ILGHttpConstants-OSX/ILGHttpConstants-OSX-dummy.m", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "72691" }, { "name": "Ruby", "bytes": "4062" }, { "name": "Shell", "bytes": "25617" } ], "symlink_target": "" }
var brook = require('./brook.js'), meb = new brook.MemoryEventBrook(); meb.eventCleanTimer(3600); function get_ip (req) { var ipaddr = req.header('x-forwarded-for'); if (ipaddr) ipAddress = ipaddr.split(',')[0]; if (!ipaddr) ipaddr = req.connection.remoteAddress; return ipaddr; } function _apis (app) { app.get('/api/v1/test', function (req, rep) { rep.send('Hello ' + get_ip(req) +'!'); }); app.post('/api/v1/create', function (req, rep) { var eid = meb.eventCreate( req.body.name, get_ip(req) ); rep.header("Content-Type", "application/json"); rep.send(JSON.stringify({eid: eid})); }); app.post('/api/v1/delete', function (req, rep) { var r = meb.eventDelete( req.body.eid, get_ip(req) ); rep.header("Content-Type", "application/json"); if (r) rep.send(JSON.stringify({status: 'done'})); else rep.send(JSON.stringify({status: 'fail'})); }); app.post('/api/v1/listen', function (req, rep) { var r = meb.eventListen( req.body.eid, req.body.url ); rep.header("Content-Type", "application/json"); if (r) rep.send(JSON.stringify({status: 'done'})); else rep.send(JSON.stringify({status: 'fail'})); }); app.post('/api/v1/contribute', function (req, rep) { var r = meb.eventContribute( req.body.eid, get_ip(req), req.body.ip ); rep.header("Content-Type", "application/json"); if (r) rep.send(JSON.stringify({status: 'done'})); else rep.send(JSON.stringify({status: 'fail'})); }); app.post('/api/v1/leave', function (req, rep) { var r = meb.eventLeave( req.body.eid, get_ip(req), req.body.url, req.body.ip ); rep.header("Content-Type", "application/json"); if (r) rep.send(JSON.stringify({status: 'done'})); else rep.send(JSON.stringify({status: 'fail'})); }); app.post('/api/v1/fire', function (req, rep) { var r = meb.eventFire( req.body.eid, get_ip(req), req.body.data, req.body.duration, req.body.klass, req.body.version ); rep.header("Content-Type", "application/json"); if (r) rep.send(JSON.stringify({status: 'done'})); else rep.send(JSON.stringify({status: 'fail'})); }); app.post('/api/v1/query', function (req, rep) { var query = meb.eventQuery( req.body.eid, req.body.dt_a, req.body.dt_b, req.body.klasses ); rep.header("Content-Type", "application/json"); rep.send(JSON.stringify({eid: req.body.eid, query: query})); }); } module.exports = _apis;
{ "content_hash": "9dff88f6cecd67c32cb14929c58ee21d", "timestamp": "", "source": "github", "line_count": 90, "max_line_length": 64, "avg_line_length": 28.755555555555556, "alnum_prop": 0.5873261205564142, "repo_name": "dna2github/dna2oldmemory", "id": "76433bfc7f813164081eff908fd857eb878233bb", "size": "2588", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "dna2poem/tiny/brook/apis.js", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "16432" }, { "name": "C#", "bytes": "143745" }, { "name": "CSS", "bytes": "104" }, { "name": "HTML", "bytes": "9637" }, { "name": "Java", "bytes": "155260" }, { "name": "JavaScript", "bytes": "37336" }, { "name": "Python", "bytes": "92020" }, { "name": "Shell", "bytes": "2277" } ], "symlink_target": "" }
module SenorArmando module Plugins # Sends metrics to a remote statsd-compatible server class StatsdSender < EventMachine::Connection DEFAULT_HOST = '127.0.0.1' DEFAULT_PORT = 8125 DEFAULT_FRAC = 1.0 # def initialize options={} @name = options[:name] || File.basename(Goliath::Application.app_file, '.rb') @host = options[:host] || DEFAULT_HOST @port = options[:port] || DEFAULT_PORT @logger = options[:logger] || Logger.new end def name metric=[] [@name, metric].flatten.reject{|x| x.to_s.empty? }.join(".") end def count metric, val=1, sampling_frac=nil if sampling_frac && (rand < sampling_frac.to_F) send_to_statsd "#{name(metric)}:#{val}|c|@#{sampling_frac}" else send_to_statsd "#{name(metric)}:#{val}|c" end end def timing metric, val send_to_statsd "#{name(metric)}:#{val}|ms" end protected def send_to_statsd metric send_datagram metric, @host, @port end # Called automatically to start the plugin def self.open options={} EventMachine::open_datagram_socket('', 0, self, options) end end # Sends metrics to a remote statsd-compatible server # # @example # plugin SenorArmando::Plugins::StatsdPlugin # # You might also enjoy using the SenorArmando::Rack::StatsdLogger middleware. # class StatsdPlugin attr_reader :agent # Called by the framework to initialize the plugin # # @param port [Integer] Unused # @param config [Hash] The server configuration data # @param status [Hash] A status hash # @param logger [Log4R::Logger] The logger # @return [SenorArmando::Plugins::StatsdPlugin] An instance of the SenorArmando::Plugins::StatsdPlugin plugin def initialize(port, config, status, logger) @status = status @config = config[:statsd_logger] || {} @config[:logger] = logger @last = Time.now.to_f end @@recent_latency = 0 def self.recent_latency @@recent_latency end def agent @@agent ||= StatsdSender.open(@config) end def self.agent @@agent end # Called automatically to start the plugin def run agent EM.add_periodic_timer(1) do @@recent_latency = (Time.now.to_f - @last) agent.timing 'reactor.latency', @@recent_latency @last = Time.now.to_f end end end end end
{ "content_hash": "e8d4fff9aca7bdff957de965e76e4456", "timestamp": "", "source": "github", "line_count": 95, "max_line_length": 115, "avg_line_length": 27.294736842105262, "alnum_prop": 0.5873505591978403, "repo_name": "infochimps-labs/senor_armando", "id": "b42ee92f3755dfddb61f76a321bd5d51c32f47e2", "size": "2593", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/senor_armando/plugins/statsd_plugin.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "107057" } ], "symlink_target": "" }
""" Installs and configures AMQP """ from packstack.installer import basedefs from packstack.installer import validators from packstack.installer import processors from packstack.installer import utils from packstack.modules.common import filtered_hosts from packstack.modules.documentation import update_params_usage from packstack.modules.ospluginutils import appendManifestFile from packstack.modules.ospluginutils import createFirewallResources from packstack.modules.ospluginutils import getManifestTemplate from packstack.modules.ospluginutils import generate_ssl_cert # ------------- AMQP Packstack Plugin Initialization -------------- PLUGIN_NAME = "AMQP" PLUGIN_NAME_COLORED = utils.color_text(PLUGIN_NAME, 'blue') def initConfig(controller): params = [ {"CMD_OPTION": "amqp-backend", "PROMPT": "Set the AMQP service backend", "OPTION_LIST": ["rabbitmq"], "VALIDATORS": [validators.validate_options], "DEFAULT_VALUE": "rabbitmq", "MASK_INPUT": False, "LOOSE_VALIDATION": False, "CONF_NAME": "CONFIG_AMQP_BACKEND", "USE_DEFAULT": False, "NEED_CONFIRM": False, "CONDITION": False, "DEPRECATES": ['CONFIG_AMQP_SERVER']}, {"CMD_OPTION": "amqp-host", "PROMPT": "Enter the host for the AMQP service", "OPTION_LIST": [], "VALIDATORS": [validators.validate_ssh], "DEFAULT_VALUE": utils.get_localhost_ip(), "MASK_INPUT": False, "LOOSE_VALIDATION": True, "CONF_NAME": "CONFIG_AMQP_HOST", "USE_DEFAULT": False, "NEED_CONFIRM": False, "CONDITION": False}, {"CMD_OPTION": "amqp-enable-ssl", "PROMPT": "Enable SSL for the AMQP service?", "OPTION_LIST": ["y", "n"], "VALIDATORS": [validators.validate_options], "DEFAULT_VALUE": "n", "MASK_INPUT": False, "LOOSE_VALIDATION": False, "CONF_NAME": "CONFIG_AMQP_ENABLE_SSL", "USE_DEFAULT": False, "NEED_CONFIRM": False, "CONDITION": False}, {"CMD_OPTION": "amqp-enable-auth", "PROMPT": "Enable Authentication for the AMQP service?", "OPTION_LIST": ["y", "n"], "VALIDATORS": [validators.validate_options], "DEFAULT_VALUE": "n", "MASK_INPUT": False, "LOOSE_VALIDATION": False, "CONF_NAME": "CONFIG_AMQP_ENABLE_AUTH", "USE_DEFAULT": False, "NEED_CONFIRM": False, "CONDITION": False}, ] update_params_usage(basedefs.PACKSTACK_DOC, params, sectioned=False) group = {"GROUP_NAME": "AMQP", "DESCRIPTION": "AMQP Config parameters", "PRE_CONDITION": False, "PRE_CONDITION_MATCH": True, "POST_CONDITION": False, "POST_CONDITION_MATCH": True} controller.addGroup(group, params) params = [ {"CMD_OPTION": "amqp-nss-certdb-pw", "PROMPT": "Enter the password for NSS certificate database", "OPTION_LIST": [], "VALIDATORS": [validators.validate_not_empty], "DEFAULT_VALUE": "PW_PLACEHOLDER", "PROCESSORS": [processors.process_password], "MASK_INPUT": True, "LOOSE_VALIDATION": True, "CONF_NAME": "CONFIG_AMQP_NSS_CERTDB_PW", "USE_DEFAULT": False, "NEED_CONFIRM": True, "CONDITION": False}, ] update_params_usage(basedefs.PACKSTACK_DOC, params, sectioned=False) group = {"GROUP_NAME": "AMQPSSL", "DESCRIPTION": "AMQP Config SSL parameters", "PRE_CONDITION": "CONFIG_AMQP_ENABLE_SSL", "PRE_CONDITION_MATCH": "y", "POST_CONDITION": False, "POST_CONDITION_MATCH": True} controller.addGroup(group, params) params = [ {"CMD_OPTION": "amqp-auth-user", "PROMPT": "Enter the user for amqp authentication", "OPTION_LIST": [], "VALIDATORS": [validators.validate_not_empty], "DEFAULT_VALUE": "amqp_user", "MASK_INPUT": False, "LOOSE_VALIDATION": True, "CONF_NAME": "CONFIG_AMQP_AUTH_USER", "USE_DEFAULT": False, "NEED_CONFIRM": False, "CONDITION": False}, {"CMD_OPTION": "amqp-auth-password", "PROMPT": "Enter the password for user authentication", "OPTION_LIST": ["y", "n"], "VALIDATORS": [validators.validate_not_empty], "PROCESSORS": [processors.process_password], "DEFAULT_VALUE": "PW_PLACEHOLDER", "MASK_INPUT": True, "LOOSE_VALIDATION": True, "CONF_NAME": "CONFIG_AMQP_AUTH_PASSWORD", "USE_DEFAULT": False, "NEED_CONFIRM": True, "CONDITION": False}, ] update_params_usage(basedefs.PACKSTACK_DOC, params, sectioned=False) group = {"GROUP_NAME": "AMQPAUTH", "DESCRIPTION": "AMQP Config Athentication parameters", "PRE_CONDITION": "CONFIG_AMQP_ENABLE_AUTH", "PRE_CONDITION_MATCH": "y", "POST_CONDITION": False, "POST_CONDITION_MATCH": True} controller.addGroup(group, params) def initSequences(controller): amqpsteps = [ {'title': 'Adding AMQP manifest entries', 'functions': [create_manifest]} ] controller.addSequence("Installing AMQP", [], [], amqpsteps) # ------------------------ step functions ------------------------- def create_manifest(config, messages): server = utils.ScriptRunner(config['CONFIG_AMQP_HOST']) if config['CONFIG_AMQP_ENABLE_SSL'] == 'y': config['CONFIG_AMQP_SSL_ENABLED'] = True config['CONFIG_AMQP_PROTOCOL'] = 'ssl' config['CONFIG_AMQP_CLIENTS_PORT'] = "5671" amqp_host = config['CONFIG_AMQP_HOST'] service = 'AMQP' ssl_key_file = '/etc/pki/tls/private/ssl_amqp.key' ssl_cert_file = '/etc/pki/tls/certs/ssl_amqp.crt' cacert = config['CONFIG_AMQP_SSL_CACERT_FILE'] = ( config['CONFIG_SSL_CACERT'] ) generate_ssl_cert(config, amqp_host, service, ssl_key_file, ssl_cert_file) else: # Set default values config['CONFIG_AMQP_CLIENTS_PORT'] = "5672" config['CONFIG_AMQP_SSL_ENABLED'] = False config['CONFIG_AMQP_PROTOCOL'] = 'tcp' if config['CONFIG_AMQP_ENABLE_AUTH'] == 'n': config['CONFIG_AMQP_AUTH_PASSWORD'] = 'guest' config['CONFIG_AMQP_AUTH_USER'] = 'guest' manifestfile = "%s_amqp.pp" % config['CONFIG_AMQP_HOST'] manifestdata = getManifestTemplate('amqp') if config['CONFIG_IP_VERSION'] == 'ipv6': config['CONFIG_AMQP_HOST_URL'] = "[%s]" % config['CONFIG_AMQP_HOST'] else: config['CONFIG_AMQP_HOST_URL'] = config['CONFIG_AMQP_HOST'] fw_details = dict() # All hosts should be able to talk to amqp for host in filtered_hosts(config, exclude=False): key = "amqp_%s" % host fw_details.setdefault(key, {}) fw_details[key]['host'] = "%s" % host fw_details[key]['service_name'] = "amqp" fw_details[key]['chain'] = "INPUT" fw_details[key]['ports'] = ['5671', '5672'] fw_details[key]['proto'] = "tcp" config['FIREWALL_AMQP_RULES'] = fw_details manifestdata += createFirewallResources('FIREWALL_AMQP_RULES') appendManifestFile(manifestfile, manifestdata, 'pre')
{ "content_hash": "d9140a538cf46f52976fe35d0b66b598", "timestamp": "", "source": "github", "line_count": 198, "max_line_length": 76, "avg_line_length": 37.42929292929293, "alnum_prop": 0.5879098637160977, "repo_name": "imcsk8/packstack", "id": "bc822100bc810d982c6734ba0f87cfae7797e907", "size": "7981", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "packstack/plugins/amqp_002.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Puppet", "bytes": "54266" }, { "name": "Python", "bytes": "392836" }, { "name": "Ruby", "bytes": "15291" }, { "name": "Shell", "bytes": "551" } ], "symlink_target": "" }
package Paws::CodePipeline::TransitionState; use Moose; has DisabledReason => (is => 'ro', isa => 'Str', request_name => 'disabledReason', traits => ['NameInRequest']); has Enabled => (is => 'ro', isa => 'Bool', request_name => 'enabled', traits => ['NameInRequest']); has LastChangedAt => (is => 'ro', isa => 'Str', request_name => 'lastChangedAt', traits => ['NameInRequest']); has LastChangedBy => (is => 'ro', isa => 'Str', request_name => 'lastChangedBy', traits => ['NameInRequest']); 1; ### main pod documentation begin ### =head1 NAME Paws::CodePipeline::TransitionState =head1 USAGE This class represents one of two things: =head3 Arguments in a call to a service Use the attributes of this class as arguments to methods. You shouldn't make instances of this class. Each attribute should be used as a named argument in the calls that expect this type of object. As an example, if Att1 is expected to be a Paws::CodePipeline::TransitionState object: $service_obj->Method(Att1 => { DisabledReason => $value, ..., LastChangedBy => $value }); =head3 Results returned from an API call Use accessors for each attribute. If Att1 is expected to be an Paws::CodePipeline::TransitionState object: $result = $service_obj->Method(...); $result->Att1->DisabledReason =head1 DESCRIPTION Represents information about the state of transitions between one stage and another stage. =head1 ATTRIBUTES =head2 DisabledReason => Str The user-specified reason why the transition between two stages of a pipeline was disabled. =head2 Enabled => Bool Whether the transition between stages is enabled (true) or disabled (false). =head2 LastChangedAt => Str The timestamp when the transition state was last changed. =head2 LastChangedBy => Str The ID of the user who last changed the transition state. =head1 SEE ALSO This class forms part of L<Paws>, describing an object used in L<Paws::CodePipeline> =head1 BUGS and CONTRIBUTIONS The source code is located here: https://github.com/pplu/aws-sdk-perl Please report bugs to: https://github.com/pplu/aws-sdk-perl/issues =cut
{ "content_hash": "2f477422a9a81f12f12676ccb1d310d3", "timestamp": "", "source": "github", "line_count": 77, "max_line_length": 114, "avg_line_length": 27.51948051948052, "alnum_prop": 0.7243983010854177, "repo_name": "ioanrogers/aws-sdk-perl", "id": "3d41a9673fa8f9174517ac36f1e021cabd83b432", "size": "2119", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "auto-lib/Paws/CodePipeline/TransitionState.pm", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Makefile", "bytes": "1292" }, { "name": "Perl", "bytes": "20360380" }, { "name": "Perl 6", "bytes": "99393" }, { "name": "Shell", "bytes": "445" } ], "symlink_target": "" }
module Messenger module Bot class Request def self.post(url, data) url = URI.parse(url) http = Net::HTTP.new(url.host, 443) http.use_ssl = true begin request = Net::HTTP::Post.new(url.request_uri) request["Content-Type"] = "application/json" request.body = data.to_json response = http.request(request) body = JSON(response.body) return { ret: body["error"].nil?, body: body } rescue => e raise e end end def self.get(url, data = {}) url = URI.parse(url) http = Net::HTTP.new(url.host, 443) http.use_ssl = true begin request = Net::HTTP::Get.new(url.request_uri) request["Content-Type"] = "application/json" response = http.request(request) body = JSON(response.body) return { ret: body["error"].nil?, body: body } rescue => e raise e end end def self.delete(url, data) url = URI.parse(url) http = Net::HTTP.new(url.host, 443) http.use_ssl = true begin request = Net::HTTP::Delete.new(url.request_uri) request["Content-Type"] = "application/json" request.body = data.to_json response = http.request(request) body = JSON(response.body) return { ret: body["error"].nil?, body: body } rescue => e raise e end end end end end
{ "content_hash": "05328141536aaa6045705bf1d2a478f3", "timestamp": "", "source": "github", "line_count": 52, "max_line_length": 58, "avg_line_length": 29.192307692307693, "alnum_prop": 0.5250329380764164, "repo_name": "jun85664396/messenger-bot-rails", "id": "caf896e5aacb91f23a456e3253ccad1eb5e8c7bf", "size": "1518", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/messenger/bot/request.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "9308" }, { "name": "Shell", "bytes": "131" } ], "symlink_target": "" }
int main(int argc, char **argv) { SPTracer::Log::Info("SPTracer started"); // config file std::string configFile = argc > 1 ? argv[1] : "sptracer.cfg"; SPTracer::Log::Info("Config file: " + configFile); // create application App app(configFile); // check that application is initialized if (!app.IsInitialized()) { return 1; } // run the application return app.Run(); }
{ "content_hash": "313542b44cd1ab737fbac1b3231bba7f", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 62, "avg_line_length": 19.4, "alnum_prop": 0.6623711340206185, "repo_name": "bogoms/sptracer", "id": "d12c8b3a9c5e7c68eec7f27530370c37b52dce8f", "size": "432", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "SPTracer/src/main.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "178163" } ], "symlink_target": "" }
@interface RTextComposerViewController () @property (nonatomic, retain) UITextView *textView; @property (nonatomic, retain) UIView *toolbarView; @end @implementation RTextComposerViewController //@synthesize rightBarButtonItem = _rightBarButtonItem; - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // Custom initialization self.maxLength = INFINITY; [self updateCounter]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(adjustViewForKeyboard:) name:UIKeyboardDidShowNotification object:nil]; } return self; } - (NSString *)text { return self.textView.text; } - (UITextView *)textView { if (!_textView) { _textView = [[UITextView alloc] initWithFrame:[self frameForMainContent]]; _textView.delegate = self; //TODO should inquery its delegate about font size, content inset, text color //to prevent horizontal scrolling, we treat left and right insets as margin not padding if (self.delegate && [self.delegate respondsToSelector:@selector(insetsForTextViewInTextComposerViewController:)]) { UIEdgeInsets insets = [self.delegate insetsForTextViewInTextComposerViewController:self]; _textView.contentInset = UIEdgeInsetsMake(insets.top , 0, insets.bottom, 0); } else { _textView.contentInset = UIEdgeInsetsMake(10, 0, 10, 0); } if (self.delegate && [self.delegate respondsToSelector:@selector(fontForTextViewInTextComposerViewController:)]) { _textView.font = [self.delegate fontForTextViewInTextComposerViewController:self]; } else { _textView.font = [UIFont systemFontOfSize:14]; } if (self.delegate && [self.delegate respondsToSelector:@selector(colorForTextViewInTextComposerViewController:)]) { _textView.textColor = [self.delegate colorForTextViewInTextComposerViewController:self]; } else { _textView.textColor = [UIColor grayColor]; } [self.view addSubview:_textView]; } return _textView; } - (UIView *)toolbarView { if (!_toolbarView) { if (self.delegate && [self.delegate respondsToSelector:@selector(viewForToolbarInTextComposerViewController:)]) { _toolbarView = [self.delegate viewForToolbarInTextComposerViewController:self]; [self.view addSubview:_toolbarView]; } } return _toolbarView; } - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. //delegate is possibly assgined after intialization [self.textView becomeFirstResponder]; } - (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; [self.textView becomeFirstResponder]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } - (void)updateCounter { self.wordCount = self.textView.text.length; } - (void)adjustViewForKeyboard:(NSNotification *)notification { CGRect kFrame = [[notification.userInfo valueForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue]; CGRect maxFrame = [self frameForMainContent]; CGFloat toolbarHeight = 0; if (self.delegate && [self.delegate respondsToSelector:@selector(heightForToolbarInTextComposerViewController:)]) { toolbarHeight = [self.delegate heightForToolbarInTextComposerViewController:self]; } self.textView.frame = CGRectMake(0, maxFrame.origin.y, maxFrame.size.width, maxFrame.size.height - kFrame.size.height - toolbarHeight); self.toolbarView.frame = CGRectMake(0, maxFrame.origin.y + maxFrame.size.height - kFrame.size.height - toolbarHeight, maxFrame.size.width, toolbarHeight); } - (void)resetContent { self.textView.text = @""; [self updateCounter]; } - (void)textViewDidChange:(UITextView *)textView { [self updateCounter]; } - (BOOL)textViewShouldBeginEditing:(UITextView *)textView { //when text.length == ComposerTotalSize, we shouldn't allow futher editing actions return textView.text.length < self.maxLength; } @end
{ "content_hash": "1c4da194fa3257a6dca7eaaf2c2bbf2d", "timestamp": "", "source": "github", "line_count": 128, "max_line_length": 158, "avg_line_length": 33.625, "alnum_prop": 0.6988847583643123, "repo_name": "RobinQu/RUIKitchen", "id": "0fd7fe4e5d4d77c2afe25cdeb9dba3b8104e539e", "size": "4501", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Classes/RTextComposerViewController.m", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "23309" }, { "name": "Ruby", "bytes": "552" } ], "symlink_target": "" }
package com.baidu.rigel.biplatform.queryrouter.queryplugin.jdbc.service.impl; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; import com.baidu.rigel.biplatform.queryrouter.handle.model.QueryHandler; import com.baidu.rigel.biplatform.queryrouter.queryplugin.service.CountNumService; import com.baidu.rigel.biplatform.queryrouter.queryplugin.service.JoinTableDataService; import com.baidu.rigel.biplatform.queryrouter.queryplugin.sql.SqlExpression; import com.baidu.rigel.biplatform.queryrouter.queryplugin.sql.model.ColumnType; import com.baidu.rigel.biplatform.queryrouter.queryplugin.sql.model.PlaneTableQuestionModel; import com.baidu.rigel.biplatform.queryrouter.queryplugin.sql.model.SqlColumn; /** * * SQLDataQueryService的实现类 * * @author luowenlei * */ @Service("jdbcCountNumServiceImpl") @Scope("prototype") public class JdbcCountNumServiceImpl implements CountNumService { /** * JoinTableDataService */ @Resource(name = "jdbcJoinTableDataServiceImpl") private JoinTableDataService joinTableDataService; /** * getTotalRecordSize * * @param questionModel * questionModel * @param QueryExpression * sqlExpression * @return DataModel DataModel */ public int getTotalRecordSize(PlaneTableQuestionModel planeQuestionModel, QueryHandler newQueryRequest) { // 按照tablename, 组织sqlColumnList,以便于按表查询所有的字段信息 HashMap<String, List<SqlColumn>> tables = new HashMap<String, List<SqlColumn>>(); SqlExpression sqlExpression = newQueryRequest.getSqlExpression(); for (SqlColumn sqlColumn : newQueryRequest.getSqlExpression().getQueryMeta().getAllColumns()) { if (sqlColumn.getSourceTableName().equals(sqlColumn.getTableName())) { // 过滤事实表及退化维 continue; } if (sqlColumn.getType() == ColumnType.JOIN) { if (tables.get(sqlColumn.getTableName()) == null) { tables.put(sqlColumn.getTableName(), new ArrayList<SqlColumn>()); } tables.get(sqlColumn.getTableName()).add(sqlColumn); } } // 查询jointable中的主表的id信息 Map<String, List<Object>> values = joinTableDataService.getJoinTableData( planeQuestionModel, tables, newQueryRequest.getJdbcHandler()); // set total count sql sqlExpression.generateCountSql(planeQuestionModel, sqlExpression.getQueryMeta().getAllColumns(), sqlExpression.getNeedColums(), values); return newQueryRequest.getJdbcHandler().queryForInt( sqlExpression.getCountSqlQuery().toCountSql(), sqlExpression.getCountSqlQuery().getWhere().getValues()); } }
{ "content_hash": "96fbcecbe9a8293a22464c1ecfac5bf0", "timestamp": "", "source": "github", "line_count": 78, "max_line_length": 104, "avg_line_length": 39.32051282051282, "alnum_prop": 0.677535050537985, "repo_name": "sdgdsffdsfff/bi-platform", "id": "1811c878c546479aceff1a76f637bf0f9869579f", "size": "3787", "binary": false, "copies": "1", "ref": "refs/heads/branch_1.7.0", "path": "queryrouter/src/main/java/com/baidu/rigel/biplatform/queryrouter/queryplugin/jdbc/service/impl/JdbcCountNumServiceImpl.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "923847" }, { "name": "HTML", "bytes": "259528" }, { "name": "Java", "bytes": "5353820" }, { "name": "JavaScript", "bytes": "15825643" }, { "name": "Shell", "bytes": "3420" } ], "symlink_target": "" }
NAME="alan" #******************************************************************************* # Main Code #******************************************************************************* #Install Prereqs sudo apt-get install gfortran g++ python-pip python-dev zlib1g-dev libhdf5-serial-dev libnetcdf-dev pip install numpy pip install netCDF4 requests_toolbelt condorpy pip install tethys_dataset_services sudo apt-get install git cd /home/$NAME/ mkdir condor ecmwf logs scripts rapid rapid/input rapid/output cd scripts git clone https://github.com/CI-WATER/erfp_data_process_ubuntu_aws.git cd erfp_data_process_ubuntu_aws git submodule init git submodule update #install RAPID prereqs cd /home/$NAME/ mkdir installz work cd installz wget "http://ftp.mcs.anl.gov/pub/petsc/release-snapshots/petsc-3.3-p7.tar.gz" wget "http://www.mcs.anl.gov/research/projects/tao/download/tao-2.1-p2.tar.gz" wget "http://www.unidata.ucar.edu/downloads/netcdf/ftp/netcdf-3.6.3.tar.gz" tar -xzf netcdf-3.6.3.tar.gz mkdir netcdf-3.6.3-install cd netcdf-3.6.3 ./configure --prefix=/home/$NAME/installz/netcdf-3.6.3-install make check > check.log make install > install.log cd .. tar -xzf petsc-3.3-p7.tar.gz cd petsc-3.3-p7 ./configure PETSC_DIR=$PWD PETSC_ARCH=linux-gcc-cxx --download-f-blas-lapack=1 --download-mpich=1 --with-cc=gcc --with-cxx=g++ --with-fc=gfortran --with-clanguage=cxx --with-debugging=0 make PETSC_DIR=$PWD PETSC_ARCH=linux-gcc-cxx all make PETSC_DIR=$PWD PETSC_ARCH=linux-gcc-cxx test cd .. tar -xzf tao-2.1-p2.tar.gz cd tao-2.1-p2 make TAO_DIR=$PWD PETSC_DIR=/home/$NAME/installz/petsc-3.3-p7 PETSC_ARCH=linux-gcc-cxx all > make.log make TAO_DIR=$PWD PETSC_DIR=/home/$NAME/installz/petsc-3.3-p7 PETSC_ARCH=linux-gcc-cxx tao_testfortran > fortran.log export TACC_NETCDF_LIB='/home/$NAME/installz/netcdf-3.6.3-install/lib' export TACC_NETCDF_INC='/home/$NAME/installz/netcdf-3.6.3-install/include' export PETSC_DIR='/home/$NAME/installz/petsc-3.3-p7' #export PETSC_ARCH='linux-gcc-cxx-O3' export PETSC_ARCH='linux-gcc-cxx' #export PETSC_ARCH='linux-gcc-cxx-debug’ export TAO_DIR='/home/$NAME/installz/tao-2.1-p2' export PATH=$PATH:/$PETSC_DIR/$PETSC_ARCH/bin export PATH=$PATH:/home/$NAME/installz/netcdf-3.6.3-install/bin #install RAPID cd /home/$USER/work/ git clone https://github.com/c-h-david/rapid.git cd rapid/src/ make rapid #install HTCONDOR apt-get install -y libvirt0 libdate-manip-perl vim wget http://ciwckan.chpc.utah.edu/dataset/be272798-f2a7-4b27-9dc8-4a131f0bb3f0/resource/86aa16c9-0575-44f7-a143-a050cd72f4c8/download/condor8.2.8312769ubuntu14.04amd64.deb dpkg -i condor8.2.8312769ubuntu14.04amd64.deb #use this if master node and comment out following two lines #echo CONDOR_HOST = \$\(IP_ADDRESS\) echo CONDOR_HOST = 10.8.123.71 >> /etc/condor/condor_config.local echo DAEMON_LIST = MASTER, SCHEDD, STARTD >> /etc/condor/condor_config.local echo ALLOW_ADMINISTRATOR = \$\(CONDOR_HOST\), 10.8.123.* >> /etc/condor/condor_config.local echo ALLOW_OWNER = \$\(FULL_HOSTNAME\), \$\(ALLOW_ADMINISTRATOR\), \$\(CONDOR_HOST\), 10.8.123.* >> /etc/condor/condor_config.local echo ALLOW_READ = \$\(FULL_HOSTNAME\), \$\(CONDOR_HOST\), 10.8.123.* >> /etc/condor/condor_config.local echo ALLOW_WRITE = \$\(FULL_HOSTNAME\), \$\(CONDOR_HOST\), 10.8.123.* >> /etc/condor/condor_config.local echo START = True >> /etc/condor/condor_config.local echo SUSPEND = False >> /etc/condor/condor_config.local echo CONTINUE = True >> /etc/condor/condor_config.local echo PREEMPT = False >> /etc/condor/condor_config.local echo KILL = False >> /etc/condor/condor_config.local echo WANT_SUSPEND = False >> /etc/condor/condor_config.local echo WANT_VACATE = False >> /etc/condor/condor_config.local . /etc/init.d/condor start #NOTE: if you forgot to change lines for master node, change CONDOR_HOST = $(IP_ADDRESS) # and run $ . /etc/init.d/condor restart as ROOT
{ "content_hash": "3b29e279d7df33b1cd289d750be1c0ce", "timestamp": "", "source": "github", "line_count": 81, "max_line_length": 185, "avg_line_length": 47.67901234567901, "alnum_prop": 0.7159502848265148, "repo_name": "CI-WATER/erfp_era_interim_process", "id": "83f0bb8fcf5a403938d483552dfc7de6a86a9737", "size": "4485", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "install_rapid_htcondor.sh", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "85260" }, { "name": "Shell", "bytes": "4597" } ], "symlink_target": "" }
/** * @file * * @brief * * @date 22.06.2012 * @author Anton Bondarev */ #ifndef MIPS_ASM_IPL_H_ #define MIPS_ASM_IPL_H_ #include <asm/mipsregs.h> typedef unsigned int __ipl_t; static inline void ipl_init(void) { unsigned int c0_reg; /* read status registers for cleaning interrupts mask */ c0_reg = mips_read_c0_status(); // c0_reg &= ~(ST0_IM); /* clear all interrupts mask */ c0_reg |= ST0_IE; /* global enable interrupt */ mips_write_c0_status(c0_reg); /* write back status register */ /* read cause register for cleaning all pending bits */ // c0_reg = mips_read_c0_cause(); // c0_reg &= ~(ST0_IM); /* clear all interrupts pending bits */ // mips_write_c0_cause(c0_reg); /* write back cause register */ } static inline __ipl_t ipl_save(void) { unsigned int c0_reg; /* read mips status register */ c0_reg = mips_read_c0_status(); /* write back status register with cleaned irq mask*/ mips_write_c0_status(c0_reg & ~(ST0_IE)); /* return previous interrupt mask */ return c0_reg; } static inline void ipl_restore(__ipl_t ipl) { unsigned int c0_reg; /* read status registers for cleaning interrupts mask */ c0_reg = mips_read_c0_status(); if((ipl & ST0_IE) && !(c0_reg & ST0_IE)) { c0_reg |= ST0_IE; /* restore interrupts mask */ mips_write_c0_status(c0_reg); /* enable interrupts */ } } #endif /* MIPS_ASM_IPL_H_ */
{ "content_hash": "482948f4781dd898aedbb6673de40039", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 73, "avg_line_length": 25.6, "alnum_prop": 0.6292613636363636, "repo_name": "abusalimov/embox", "id": "2e47d51cab633a7aef7255fc0e8abc7700cbc5b8", "size": "1408", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/arch/mips/kernel/ipl_impl.h", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Assembly", "bytes": "107155" }, { "name": "Awk", "bytes": "763" }, { "name": "Batchfile", "bytes": "1242" }, { "name": "C", "bytes": "4966488" }, { "name": "C++", "bytes": "315751" }, { "name": "CSS", "bytes": "1546" }, { "name": "HTML", "bytes": "38874" }, { "name": "JavaScript", "bytes": "7932" }, { "name": "Lua", "bytes": "22656" }, { "name": "Makefile", "bytes": "558580" }, { "name": "Objective-C", "bytes": "16502" }, { "name": "Protocol Buffer", "bytes": "208" }, { "name": "Python", "bytes": "1207" }, { "name": "QMake", "bytes": "488" }, { "name": "Shell", "bytes": "38918" } ], "symlink_target": "" }
import { Component } from '@angular/core'; @Component({ selector: 'ng-component', templateUrl: './primary.component.html', styleUrls: ['./primary.component.scss'], }) export class PrimaryAngularComponent {}
{ "content_hash": "068eee4bbe7d1ec0b746c6fa3cb64a4d", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 42, "avg_line_length": 26.75, "alnum_prop": 0.7102803738317757, "repo_name": "dherges/ng-packagr", "id": "6ce5169470583409653244dc061fd55f895b286f", "size": "214", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "integration/watch/resources/src/primary.component.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2883" }, { "name": "HTML", "bytes": "1063" }, { "name": "JavaScript", "bytes": "5501" }, { "name": "Shell", "bytes": "1796" }, { "name": "TypeScript", "bytes": "228543" } ], "symlink_target": "" }
 using System; using System.Collections.Generic; using LuaInterface; using UnityEngine; namespace SLua { public partial class LuaDelegation : LuaObject { static internal int checkDelegate(IntPtr l,int p,out System.Func<UnityEngine.UI.ILayoutElement,System.Single> ua) { int op = extractFunction(l,p); if(LuaDLL.lua_isnil(l,-1)) { ua=null; return op; } else if (LuaDLL.lua_isuserdata(l, p)==1) { ua = (System.Func<UnityEngine.UI.ILayoutElement,System.Single>)checkObj(l, p); return op; } LuaDelegate ld; checkType(l, -1, out ld); if(ld.d!=null) { ua = (System.Func<UnityEngine.UI.ILayoutElement,System.Single>)ld.d; return op; } LuaDLL.lua_pop(l,1); ua = (UnityEngine.UI.ILayoutElement a1) => { int error = pushTry(l); pushValue(l,a1); ld.call(1, error); float ret; checkType(l,error+1,out ret); LuaDLL.lua_settop(l, error-1); return ret; }; ld.d=ua; return op; } } }
{ "content_hash": "023c2207642c30249dcad3e74a53151f", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 123, "avg_line_length": 25.043478260869566, "alnum_prop": 0.5477430555555556, "repo_name": "zhukunqian/unity5-slua", "id": "477074c08ff45e2cdde295b6e8a218d638282680", "size": "1154", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Assets/Slua/LuaObject/Unity/LuaSystem_Func_UnityEngine_UI_ILayoutElement_float.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "9586" }, { "name": "C#", "bytes": "2355390" }, { "name": "Lua", "bytes": "131" } ], "symlink_target": "" }
<!-- Copyright 2017 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <kd-graph-metrics [metrics]="cumulativeMetrics" *ngIf="showMetrics"></kd-graph-metrics> <kd-card role="table" [hidden]="isHidden()"> <div title fxLayout="row"> <ng-container *ngIf="title; else defaultTitle">{{ title }}</ng-container> <ng-template #defaultTitle i18n>Replica Sets</ng-template> </div> <div description><span class="kd-muted-light" i18n>Items:&nbsp;</span>{{ totalItems }}</div> <div actions> <kd-card-list-filter></kd-card-list-filter> </div> <div content [hidden]="showZeroState()"> <div kdLoadingSpinner [isLoading]="isLoading"></div> <mat-table [dataSource]="getData()" [trackBy]="trackByResource" matSort matSortActive="created" matSortDisableClear matSortDirection="asc" multiTemplateDataRows> <ng-container matColumnDef="statusicon"> <mat-header-cell *matHeaderCellDef></mat-header-cell> <mat-cell *matCellDef="let replicaSet; let index = index"> <mat-icon [ngClass]="getStatus(replicaSet).iconClass" [matTooltip]="getStatus(replicaSet).iconTooltip"> <ng-container *ngIf="showHoverIcon(index, replicaSet); else showStatus"> remove_red_eye </ng-container> <ng-template #showStatus> {{ getStatus(replicaSet).iconName }} </ng-template> </mat-icon> </mat-cell> </ng-container> <ng-container matColumnDef="statusDetail"> <mat-cell *matCellDef="let replicaSet"> <kd-row-detail [events]="getEvents(replicaSet)"></kd-row-detail> </mat-cell> </ng-container> <ng-container matColumnDef="name"> <mat-header-cell *matHeaderCellDef mat-sort-header disableClear="true" class="col-stretch-xl" i18n>Name</mat-header-cell> <mat-cell *matCellDef="let replicaSet" class="col-stretch-xl"> <a (click)="$event.stopPropagation()" [routerLink]="getDetailsHref(replicaSet.objectMeta.name, replicaSet.objectMeta.namespace)" queryParamsHandling="preserve"> {{ replicaSet.objectMeta.name }} </a> </mat-cell> </ng-container> <ng-container *ngIf="shouldShowColumn('namespace')" matColumnDef="namespace"> <mat-header-cell *matHeaderCellDef class="col-stretch-l col-min-90" i18n>Namespace</mat-header-cell> <mat-cell *matCellDef="let replicaSet" class="col-stretch-l col-min-90">{{ replicaSet.objectMeta.namespace }}</mat-cell> </ng-container> <ng-container matColumnDef="images"> <mat-header-cell *matHeaderCellDef class="col-stretch-xl" i18n>Images</mat-header-cell> <mat-cell *matCellDef="let replicaSet" class="col-stretch-xl"> <kd-chips [map]="replicaSet.containerImages"></kd-chips> </mat-cell> </ng-container> <ng-container matColumnDef="labels"> <mat-header-cell *matHeaderCellDef class="col-stretch-xl" i18n>Labels</mat-header-cell> <mat-cell *matCellDef="let replicaSet" class="col-stretch-xl"> <kd-chips [map]="replicaSet.objectMeta.labels"></kd-chips> </mat-cell> </ng-container> <ng-container matColumnDef="pods"> <mat-header-cell *matHeaderCellDef class="col-stretch-m" i18n>Pods</mat-header-cell> <mat-cell *matCellDef="let replicaSet" class="col-stretch-m"> {{ replicaSet.podInfo.running }} / {{ replicaSet.podInfo.desired }} </mat-cell> </ng-container> <ng-container matColumnDef="created"> <mat-header-cell *matHeaderCellDef mat-sort-header disableClear="true" class="col-stretch-m" i18n>Created</mat-header-cell> <mat-cell *matCellDef="let replicaSet" class="col-stretch-m"> <kd-date [date]="replicaSet.objectMeta.creationTimestamp" relative></kd-date> </mat-cell> </ng-container> <ng-container *ngFor="let col of getActionColumns()" [matColumnDef]="col.name"> <mat-header-cell *matHeaderCellDef></mat-header-cell> <mat-cell *matCellDef="let rs"> <kd-dynamic-cell [component]="col.component" [resource]="rs"></kd-dynamic-cell> </mat-cell> </ng-container> <mat-header-row *matHeaderRowDef="getColumns()"></mat-header-row> <mat-row (mouseover)="onRowOver(index, row)" (mouseleave)="onRowLeave()" (click)="expand(index, row)" [ngClass]="{'kd-no-bottom-border': isRowExpanded(index, row), 'kd-clickable': hasErrors(row)}" *matRowDef="let row; columns: getColumns(); let index = index"></mat-row> <mat-row class="kd-detail-row" [ngClass]="{'kd-hidden': !isRowExpanded(index, row)}" *matRowDef="let row; columns: ['statusDetail']; let index = index"></mat-row> </mat-table> <div [hidden]="totalItems <= itemsPerPage"> <mat-paginator [length]="totalItems" [pageSize]="itemsPerPage" hidePageSize showFirstLastButtons></mat-paginator> </div> </div> <div content [hidden]="!showZeroState()"> <kd-list-zero-state></kd-list-zero-state> </div> </kd-card>
{ "content_hash": "016724aa9e27f483a62973d1da7fc748", "timestamp": "", "source": "github", "line_count": 164, "max_line_length": 115, "avg_line_length": 39.19512195121951, "alnum_prop": 0.5717174859987555, "repo_name": "floreks/dashboard", "id": "f5e70a319a3cf75a65864f43324e9f3f5d5baf4f", "size": "6428", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "modules/web/src/common/components/resourcelist/replicaset/template.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "8601" }, { "name": "Go", "bytes": "1250484" }, { "name": "HTML", "bytes": "451845" }, { "name": "JavaScript", "bytes": "3927" }, { "name": "Makefile", "bytes": "17982" }, { "name": "SCSS", "bytes": "67993" }, { "name": "Shell", "bytes": "17925" }, { "name": "Smarty", "bytes": "3598" }, { "name": "TypeScript", "bytes": "846321" } ], "symlink_target": "" }
<?php /* Safe sample input : use proc_open to read /tmp/tainted.txt SANITIZE : use in_array to check if $tainted is in the white list construction : use of sprintf via a %s with simple quote */ /*Copyright 2015 Bertrand STIVALET Permission is hereby granted, without written agreement or royalty fee, to use, copy, modify, and distribute this software and its documentation for any purpose, provided that the above copyright notice and the following three paragraphs appear in all copies of this software. IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.*/ $descriptorspec = array( 0 => array("pipe", "r"), 1 => array("pipe", "w"), 2 => array("file", "/tmp/error-output.txt", "a") ); $cwd = '/tmp'; $process = proc_open('more /tmp/tainted.txt', $descriptorspec, $pipes, $cwd, NULL); if (is_resource($process)) { fclose($pipes[0]); $tainted = stream_get_contents($pipes[1]); fclose($pipes[1]); $return_value = proc_close($process); } $legal_table = array("safe1", "safe2"); if (in_array($tainted, $legal_table, true)) { $tainted = $tainted; } else { $tainted = $legal_table[0]; } $var = http_redirect(sprintf("'%s'.php", $tainted)); ?>
{ "content_hash": "64ac1be3f6c869126f0860bd16545dcc", "timestamp": "", "source": "github", "line_count": 71, "max_line_length": 83, "avg_line_length": 24.070422535211268, "alnum_prop": 0.7173785839672323, "repo_name": "stivalet/PHP-Vulnerability-test-suite", "id": "b92c216c74591ca021132043e01f53c2815e9170", "size": "1709", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "URF/CWE_601/safe/CWE_601__proc_open__whitelist_using_array__http_redirect_file_name-sprintf_%s_simple_quote.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "64184004" } ], "symlink_target": "" }
#if FEATURE_BREAKITERATOR using ICU4N.Text; using Lucene.Net.Analysis; using Lucene.Net.Attributes; using Lucene.Net.Diagnostics; using Lucene.Net.Documents; using Lucene.Net.Index; using Lucene.Net.Index.Extensions; using Lucene.Net.Support; using Lucene.Net.Util; using NUnit.Framework; using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using Directory = Lucene.Net.Store.Directory; namespace Lucene.Net.Search.PostingsHighlight { /// <summary> /// LUCENENET specific - Modified the behavior of the PostingsHighlighter in Java to return the /// org.ibm.icu.BreakIterator version 60.1 instead of java.text.BreakIterator and modified the original Lucene /// tests to pass, then ported to .NET. The only change required was that of the TestEmptyHighlights method /// which breaks the sentence in a different place than in the JDK. /// <para/> /// Although the ICU <see cref="BreakIterator"/> acts slightly different than the JDK's verision, using the default /// behavior of the ICU <see cref="BreakIterator"/> is the most logical default to use in .NET. It is the same /// default that was chosen in Apache Harmony. /// </summary> [SuppressCodecs("MockFixedIntBlock", "MockVariableIntBlock", "MockSep", "MockRandom", "Lucene3x")] public class TestICUPostingsHighlighter : LuceneTestCase { [Test, LuceneNetSpecific] public void TestBasics() { Directory dir = NewDirectory(); IndexWriterConfig iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)); iwc.SetMergePolicy(NewLogMergePolicy()); RandomIndexWriter iw = new RandomIndexWriter(Random, dir, iwc); FieldType offsetsType = new FieldType(TextField.TYPE_STORED); offsetsType.IndexOptions = (IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS); Field body = new Field("body", "", offsetsType); Document doc = new Document(); doc.Add(body); body.SetStringValue("This is a test. Just a test highlighting from postings. Feel free to ignore."); iw.AddDocument(doc); body.SetStringValue("Highlighting the first term. Hope it works."); iw.AddDocument(doc); IndexReader ir = iw.GetReader(); iw.Dispose(); IndexSearcher searcher = NewSearcher(ir); ICUPostingsHighlighter highlighter = new ICUPostingsHighlighter(); Query query = new TermQuery(new Term("body", "highlighting")); TopDocs topDocs = searcher.Search(query, null, 10, Sort.INDEXORDER); assertEquals(2, topDocs.TotalHits); String[] snippets = highlighter.Highlight("body", query, searcher, topDocs); assertEquals(2, snippets.Length); assertEquals("Just a test <b>highlighting</b> from postings. ", snippets[0]); assertEquals("<b>Highlighting</b> the first term. ", snippets[1]); ir.Dispose(); dir.Dispose(); } [Test, LuceneNetSpecific] public void TestFormatWithMatchExceedingContentLength2() { String bodyText = "123 TEST 01234 TEST"; String[] snippets = formatWithMatchExceedingContentLength(bodyText); assertEquals(1, snippets.Length); assertEquals("123 <b>TEST</b> 01234 TE", snippets[0]); } [Test, LuceneNetSpecific] public void TestFormatWithMatchExceedingContentLength3() { String bodyText = "123 5678 01234 TEST TEST"; String[] snippets = formatWithMatchExceedingContentLength(bodyText); assertEquals(1, snippets.Length); assertEquals("123 5678 01234 TE", snippets[0]); } [Test, LuceneNetSpecific] public void TestFormatWithMatchExceedingContentLength() { String bodyText = "123 5678 01234 TEST"; String[] snippets = formatWithMatchExceedingContentLength(bodyText); assertEquals(1, snippets.Length); // LUCENE-5166: no snippet assertEquals("123 5678 01234 TE", snippets[0]); } private String[] formatWithMatchExceedingContentLength(String bodyText) { int maxLength = 17; Analyzer analyzer = new MockAnalyzer(Random); Directory dir = NewDirectory(); IndexWriterConfig iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, analyzer); iwc.SetMergePolicy(NewLogMergePolicy()); RandomIndexWriter iw = new RandomIndexWriter(Random, dir, iwc); FieldType fieldType = new FieldType(TextField.TYPE_STORED); fieldType.IndexOptions = (IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS); Field body = new Field("body", bodyText, fieldType); Document doc = new Document(); doc.Add(body); iw.AddDocument(doc); IndexReader ir = iw.GetReader(); iw.Dispose(); IndexSearcher searcher = NewSearcher(ir); Query query = new TermQuery(new Term("body", "test")); TopDocs topDocs = searcher.Search(query, null, 10, Sort.INDEXORDER); assertEquals(1, topDocs.TotalHits); ICUPostingsHighlighter highlighter = new ICUPostingsHighlighter(maxLength); String[] snippets = highlighter.Highlight("body", query, searcher, topDocs); ir.Dispose(); dir.Dispose(); return snippets; } // simple test highlighting last word. [Test, LuceneNetSpecific] public void TestHighlightLastWord() { Directory dir = NewDirectory(); IndexWriterConfig iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)); iwc.SetMergePolicy(NewLogMergePolicy()); RandomIndexWriter iw = new RandomIndexWriter(Random, dir, iwc); FieldType offsetsType = new FieldType(TextField.TYPE_STORED); offsetsType.IndexOptions = (IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS); Field body = new Field("body", "", offsetsType); Document doc = new Document(); doc.Add(body); body.SetStringValue("This is a test"); iw.AddDocument(doc); IndexReader ir = iw.GetReader(); iw.Dispose(); IndexSearcher searcher = NewSearcher(ir); ICUPostingsHighlighter highlighter = new ICUPostingsHighlighter(); Query query = new TermQuery(new Term("body", "test")); TopDocs topDocs = searcher.Search(query, null, 10, Sort.INDEXORDER); assertEquals(1, topDocs.TotalHits); String[] snippets = highlighter.Highlight("body", query, searcher, topDocs); assertEquals(1, snippets.Length); assertEquals("This is a <b>test</b>", snippets[0]); ir.Dispose(); dir.Dispose(); } // simple test with one sentence documents. [Test, LuceneNetSpecific] public void TestOneSentence() { Directory dir = NewDirectory(); // use simpleanalyzer for more natural tokenization (else "test." is a token) IndexWriterConfig iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random, MockTokenizer.SIMPLE, true)); iwc.SetMergePolicy(NewLogMergePolicy()); RandomIndexWriter iw = new RandomIndexWriter(Random, dir, iwc); FieldType offsetsType = new FieldType(TextField.TYPE_STORED); offsetsType.IndexOptions = (IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS); Field body = new Field("body", "", offsetsType); Document doc = new Document(); doc.Add(body); body.SetStringValue("This is a test."); iw.AddDocument(doc); body.SetStringValue("Test a one sentence document."); iw.AddDocument(doc); IndexReader ir = iw.GetReader(); iw.Dispose(); IndexSearcher searcher = NewSearcher(ir); ICUPostingsHighlighter highlighter = new ICUPostingsHighlighter(); Query query = new TermQuery(new Term("body", "test")); TopDocs topDocs = searcher.Search(query, null, 10, Sort.INDEXORDER); assertEquals(2, topDocs.TotalHits); String[] snippets = highlighter.Highlight("body", query, searcher, topDocs); assertEquals(2, snippets.Length); assertEquals("This is a <b>test</b>.", snippets[0]); assertEquals("<b>Test</b> a one sentence document.", snippets[1]); ir.Dispose(); dir.Dispose(); } // simple test with multiple values that make a result longer than maxLength. [Test, LuceneNetSpecific] public void TestMaxLengthWithMultivalue() { Directory dir = NewDirectory(); // use simpleanalyzer for more natural tokenization (else "test." is a token) IndexWriterConfig iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random, MockTokenizer.SIMPLE, true)); iwc.SetMergePolicy(NewLogMergePolicy()); RandomIndexWriter iw = new RandomIndexWriter(Random, dir, iwc); FieldType offsetsType = new FieldType(TextField.TYPE_STORED); offsetsType.IndexOptions = (IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS); Document doc = new Document(); for (int i = 0; i < 3; i++) { Field body = new Field("body", "", offsetsType); body.SetStringValue("This is a multivalued field"); doc.Add(body); } iw.AddDocument(doc); IndexReader ir = iw.GetReader(); iw.Dispose(); IndexSearcher searcher = NewSearcher(ir); ICUPostingsHighlighter highlighter = new ICUPostingsHighlighter(40); Query query = new TermQuery(new Term("body", "field")); TopDocs topDocs = searcher.Search(query, null, 10, Sort.INDEXORDER); assertEquals(1, topDocs.TotalHits); String[] snippets = highlighter.Highlight("body", query, searcher, topDocs); assertEquals(1, snippets.Length); assertTrue("Snippet should have maximum 40 characters plus the pre and post tags", snippets[0].Length == (40 + "<b></b>".Length)); ir.Dispose(); dir.Dispose(); } [Test, LuceneNetSpecific] public void TestMultipleFields() { Directory dir = NewDirectory(); IndexWriterConfig iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random, MockTokenizer.SIMPLE, true)); iwc.SetMergePolicy(NewLogMergePolicy()); RandomIndexWriter iw = new RandomIndexWriter(Random, dir, iwc); FieldType offsetsType = new FieldType(TextField.TYPE_STORED); offsetsType.IndexOptions = (IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS); Field body = new Field("body", "", offsetsType); Field title = new Field("title", "", offsetsType); Document doc = new Document(); doc.Add(body); doc.Add(title); body.SetStringValue("This is a test. Just a test highlighting from postings. Feel free to ignore."); title.SetStringValue("I am hoping for the best."); iw.AddDocument(doc); body.SetStringValue("Highlighting the first term. Hope it works."); title.SetStringValue("But best may not be good enough."); iw.AddDocument(doc); IndexReader ir = iw.GetReader(); iw.Dispose(); IndexSearcher searcher = NewSearcher(ir); ICUPostingsHighlighter highlighter = new ICUPostingsHighlighter(); BooleanQuery query = new BooleanQuery(); query.Add(new TermQuery(new Term("body", "highlighting")), Occur.SHOULD); query.Add(new TermQuery(new Term("title", "best")), Occur.SHOULD); TopDocs topDocs = searcher.Search(query, null, 10, Sort.INDEXORDER); assertEquals(2, topDocs.TotalHits); IDictionary<String, String[]> snippets = highlighter.HighlightFields(new String[] { "body", "title" }, query, searcher, topDocs); assertEquals(2, snippets.size()); assertEquals("Just a test <b>highlighting</b> from postings. ", snippets["body"][0]); assertEquals("<b>Highlighting</b> the first term. ", snippets["body"][1]); assertEquals("I am hoping for the <b>best</b>.", snippets["title"][0]); assertEquals("But <b>best</b> may not be good enough.", snippets["title"][1]); ir.Dispose(); dir.Dispose(); } [Test, LuceneNetSpecific] public void TestMultipleTerms() { Directory dir = NewDirectory(); IndexWriterConfig iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)); iwc.SetMergePolicy(NewLogMergePolicy()); RandomIndexWriter iw = new RandomIndexWriter(Random, dir, iwc); FieldType offsetsType = new FieldType(TextField.TYPE_STORED); offsetsType.IndexOptions = (IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS); Field body = new Field("body", "", offsetsType); Document doc = new Document(); doc.Add(body); body.SetStringValue("This is a test. Just a test highlighting from postings. Feel free to ignore."); iw.AddDocument(doc); body.SetStringValue("Highlighting the first term. Hope it works."); iw.AddDocument(doc); IndexReader ir = iw.GetReader(); iw.Dispose(); IndexSearcher searcher = NewSearcher(ir); ICUPostingsHighlighter highlighter = new ICUPostingsHighlighter(); BooleanQuery query = new BooleanQuery(); query.Add(new TermQuery(new Term("body", "highlighting")), Occur.SHOULD); query.Add(new TermQuery(new Term("body", "just")), Occur.SHOULD); query.Add(new TermQuery(new Term("body", "first")), Occur.SHOULD); TopDocs topDocs = searcher.Search(query, null, 10, Sort.INDEXORDER); assertEquals(2, topDocs.TotalHits); String[] snippets = highlighter.Highlight("body", query, searcher, topDocs); assertEquals(2, snippets.Length); assertEquals("<b>Just</b> a test <b>highlighting</b> from postings. ", snippets[0]); assertEquals("<b>Highlighting</b> the <b>first</b> term. ", snippets[1]); ir.Dispose(); dir.Dispose(); } [Test, LuceneNetSpecific] public void TestMultiplePassages() { Directory dir = NewDirectory(); IndexWriterConfig iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random, MockTokenizer.SIMPLE, true)); iwc.SetMergePolicy(NewLogMergePolicy()); RandomIndexWriter iw = new RandomIndexWriter(Random, dir, iwc); FieldType offsetsType = new FieldType(TextField.TYPE_STORED); offsetsType.IndexOptions = (IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS); Field body = new Field("body", "", offsetsType); Document doc = new Document(); doc.Add(body); body.SetStringValue("This is a test. Just a test highlighting from postings. Feel free to ignore."); iw.AddDocument(doc); body.SetStringValue("This test is another test. Not a good sentence. Test test test test."); iw.AddDocument(doc); IndexReader ir = iw.GetReader(); iw.Dispose(); IndexSearcher searcher = NewSearcher(ir); ICUPostingsHighlighter highlighter = new ICUPostingsHighlighter(); Query query = new TermQuery(new Term("body", "test")); TopDocs topDocs = searcher.Search(query, null, 10, Sort.INDEXORDER); assertEquals(2, topDocs.TotalHits); String[] snippets = highlighter.Highlight("body", query, searcher, topDocs, 2); assertEquals(2, snippets.Length); assertEquals("This is a <b>test</b>. Just a <b>test</b> highlighting from postings. ", snippets[0]); assertEquals("This <b>test</b> is another <b>test</b>. ... <b>Test</b> <b>test</b> <b>test</b> <b>test</b>.", snippets[1]); ir.Dispose(); dir.Dispose(); } [Test, LuceneNetSpecific] public void TestUserFailedToIndexOffsets() { Directory dir = NewDirectory(); IndexWriterConfig iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random, MockTokenizer.SIMPLE, true)); iwc.SetMergePolicy(NewLogMergePolicy()); RandomIndexWriter iw = new RandomIndexWriter(Random, dir, iwc); FieldType positionsType = new FieldType(TextField.TYPE_STORED); positionsType.IndexOptions = (IndexOptions.DOCS_AND_FREQS_AND_POSITIONS); Field body = new Field("body", "", positionsType); Field title = new StringField("title", "", Field.Store.YES); Document doc = new Document(); doc.Add(body); doc.Add(title); body.SetStringValue("This is a test. Just a test highlighting from postings. Feel free to ignore."); title.SetStringValue("test"); iw.AddDocument(doc); body.SetStringValue("This test is another test. Not a good sentence. Test test test test."); title.SetStringValue("test"); iw.AddDocument(doc); IndexReader ir = iw.GetReader(); iw.Dispose(); IndexSearcher searcher = NewSearcher(ir); ICUPostingsHighlighter highlighter = new ICUPostingsHighlighter(); Query query = new TermQuery(new Term("body", "test")); TopDocs topDocs = searcher.Search(query, null, 10, Sort.INDEXORDER); assertEquals(2, topDocs.TotalHits); try { highlighter.Highlight("body", query, searcher, topDocs, 2); fail("did not hit expected exception"); } #pragma warning disable 168 catch (ArgumentException iae) #pragma warning restore 168 { // expected } try { highlighter.Highlight("title", new TermQuery(new Term("title", "test")), searcher, topDocs, 2); fail("did not hit expected exception"); } #pragma warning disable 168 catch (ArgumentException iae) #pragma warning restore 168 { // expected } ir.Dispose(); dir.Dispose(); } [Test, LuceneNetSpecific] public void TestBuddhism() { String text = "This eight-volume set brings together seminal papers in Buddhist studies from a vast " + "range of academic disciplines published over the last forty years. With a new introduction " + "by the editor, this collection is a unique and unrivalled research resource for both " + "student and scholar. Coverage includes: - Buddhist origins; early history of Buddhism in " + "South and Southeast Asia - early Buddhist Schools and Doctrinal History; Theravada Doctrine " + "- the Origins and nature of Mahayana Buddhism; some Mahayana religious topics - Abhidharma " + "and Madhyamaka - Yogacara, the Epistemological tradition, and Tathagatagarbha - Tantric " + "Buddhism (Including China and Japan); Buddhism in Nepal and Tibet - Buddhism in South and " + "Southeast Asia, and - Buddhism in China, East Asia, and Japan."; Directory dir = NewDirectory(); Analyzer analyzer = new MockAnalyzer(Random, MockTokenizer.SIMPLE, true); RandomIndexWriter iw = new RandomIndexWriter( #if FEATURE_INSTANCE_TESTDATA_INITIALIZATION this, #endif Random, dir, analyzer); FieldType positionsType = new FieldType(TextField.TYPE_STORED); positionsType.IndexOptions = (IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS); Field body = new Field("body", text, positionsType); Document document = new Document(); document.Add(body); iw.AddDocument(document); IndexReader ir = iw.GetReader(); iw.Dispose(); IndexSearcher searcher = NewSearcher(ir); PhraseQuery query = new PhraseQuery(); query.Add(new Term("body", "buddhist")); query.Add(new Term("body", "origins")); TopDocs topDocs = searcher.Search(query, 10); assertEquals(1, topDocs.TotalHits); ICUPostingsHighlighter highlighter = new ICUPostingsHighlighter(); String[] snippets = highlighter.Highlight("body", query, searcher, topDocs, 2); assertEquals(1, snippets.Length); assertTrue(snippets[0].Contains("<b>Buddhist</b> <b>origins</b>")); ir.Dispose(); dir.Dispose(); } [Test, LuceneNetSpecific] public void TestCuriousGeorge() { String text = "It’s the formula for success for preschoolers—Curious George and fire trucks! " + "Curious George and the Firefighters is a story based on H. A. and Margret Rey’s " + "popular primate and painted in the original watercolor and charcoal style. " + "Firefighters are a famously brave lot, but can they withstand a visit from one curious monkey?"; Directory dir = NewDirectory(); Analyzer analyzer = new MockAnalyzer(Random, MockTokenizer.SIMPLE, true); RandomIndexWriter iw = new RandomIndexWriter( #if FEATURE_INSTANCE_TESTDATA_INITIALIZATION this, #endif Random, dir, analyzer); FieldType positionsType = new FieldType(TextField.TYPE_STORED); positionsType.IndexOptions = (IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS); Field body = new Field("body", text, positionsType); Document document = new Document(); document.Add(body); iw.AddDocument(document); IndexReader ir = iw.GetReader(); iw.Dispose(); IndexSearcher searcher = NewSearcher(ir); PhraseQuery query = new PhraseQuery(); query.Add(new Term("body", "curious")); query.Add(new Term("body", "george")); TopDocs topDocs = searcher.Search(query, 10); assertEquals(1, topDocs.TotalHits); ICUPostingsHighlighter highlighter = new ICUPostingsHighlighter(); String[] snippets = highlighter.Highlight("body", query, searcher, topDocs, 2); assertEquals(1, snippets.Length); assertFalse(snippets[0].Contains("<b>Curious</b>Curious")); ir.Dispose(); dir.Dispose(); } [Test, LuceneNetSpecific] public void TestCambridgeMA() { String text; using (TextReader r = new StreamReader(this.GetType().getResourceAsStream("CambridgeMA.utf8"), Encoding.UTF8)) { text = r.ReadLine(); } Store.Directory dir = NewDirectory(); Analyzer analyzer = new MockAnalyzer(Random, MockTokenizer.SIMPLE, true); RandomIndexWriter iw = new RandomIndexWriter( #if FEATURE_INSTANCE_TESTDATA_INITIALIZATION this, #endif Random, dir, analyzer); FieldType positionsType = new FieldType(TextField.TYPE_STORED); positionsType.IndexOptions = (IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS); Field body = new Field("body", text, positionsType); Document document = new Document(); document.Add(body); iw.AddDocument(document); IndexReader ir = iw.GetReader(); iw.Dispose(); IndexSearcher searcher = NewSearcher(ir); BooleanQuery query = new BooleanQuery(); query.Add(new TermQuery(new Term("body", "porter")), Occur.SHOULD); query.Add(new TermQuery(new Term("body", "square")), Occur.SHOULD); query.Add(new TermQuery(new Term("body", "massachusetts")), Occur.SHOULD); TopDocs topDocs = searcher.Search(query, 10); assertEquals(1, topDocs.TotalHits); ICUPostingsHighlighter highlighter = new ICUPostingsHighlighter(int.MaxValue - 1); String[] snippets = highlighter.Highlight("body", query, searcher, topDocs, 2); assertEquals(1, snippets.Length); assertTrue(snippets[0].Contains("<b>Square</b>")); assertTrue(snippets[0].Contains("<b>Porter</b>")); ir.Dispose(); dir.Dispose(); } [Test, LuceneNetSpecific] public void TestPassageRanking() { Directory dir = NewDirectory(); IndexWriterConfig iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random, MockTokenizer.SIMPLE, true)); iwc.SetMergePolicy(NewLogMergePolicy()); RandomIndexWriter iw = new RandomIndexWriter(Random, dir, iwc); FieldType offsetsType = new FieldType(TextField.TYPE_STORED); offsetsType.IndexOptions = (IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS); Field body = new Field("body", "", offsetsType); Document doc = new Document(); doc.Add(body); body.SetStringValue("This is a test. Just highlighting from postings. This is also a much sillier test. Feel free to test test test test test test test."); iw.AddDocument(doc); IndexReader ir = iw.GetReader(); iw.Dispose(); IndexSearcher searcher = NewSearcher(ir); ICUPostingsHighlighter highlighter = new ICUPostingsHighlighter(); Query query = new TermQuery(new Term("body", "test")); TopDocs topDocs = searcher.Search(query, null, 10, Sort.INDEXORDER); assertEquals(1, topDocs.TotalHits); String[] snippets = highlighter.Highlight("body", query, searcher, topDocs, 2); assertEquals(1, snippets.Length); assertEquals("This is a <b>test</b>. ... Feel free to <b>test</b> <b>test</b> <b>test</b> <b>test</b> <b>test</b> <b>test</b> <b>test</b>.", snippets[0]); ir.Dispose(); dir.Dispose(); } [Test, LuceneNetSpecific] public void TestBooleanMustNot() { Directory dir = NewDirectory(); Analyzer analyzer = new MockAnalyzer(Random, MockTokenizer.SIMPLE, true); RandomIndexWriter iw = new RandomIndexWriter( #if FEATURE_INSTANCE_TESTDATA_INITIALIZATION this, #endif Random, dir, analyzer); FieldType positionsType = new FieldType(TextField.TYPE_STORED); positionsType.IndexOptions = (IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS); Field body = new Field("body", "This sentence has both terms. This sentence has only terms.", positionsType); Document document = new Document(); document.Add(body); iw.AddDocument(document); IndexReader ir = iw.GetReader(); iw.Dispose(); IndexSearcher searcher = NewSearcher(ir); BooleanQuery query = new BooleanQuery(); query.Add(new TermQuery(new Term("body", "terms")), Occur.SHOULD); BooleanQuery query2 = new BooleanQuery(); query.Add(query2, Occur.SHOULD); query2.Add(new TermQuery(new Term("body", "both")), Occur.MUST_NOT); TopDocs topDocs = searcher.Search(query, 10); assertEquals(1, topDocs.TotalHits); ICUPostingsHighlighter highlighter = new ICUPostingsHighlighter(int.MaxValue - 1); String[] snippets = highlighter.Highlight("body", query, searcher, topDocs, 2); assertEquals(1, snippets.Length); assertFalse(snippets[0].Contains("<b>both</b>")); ir.Dispose(); dir.Dispose(); } [Test, LuceneNetSpecific] public void TestHighlightAllText() { Directory dir = NewDirectory(); IndexWriterConfig iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random, MockTokenizer.SIMPLE, true)); iwc.SetMergePolicy(NewLogMergePolicy()); RandomIndexWriter iw = new RandomIndexWriter(Random, dir, iwc); FieldType offsetsType = new FieldType(TextField.TYPE_STORED); offsetsType.IndexOptions = (IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS); Field body = new Field("body", "", offsetsType); Document doc = new Document(); doc.Add(body); body.SetStringValue("This is a test. Just highlighting from postings. This is also a much sillier test. Feel free to test test test test test test test."); iw.AddDocument(doc); IndexReader ir = iw.GetReader(); iw.Dispose(); IndexSearcher searcher = NewSearcher(ir); ICUPostingsHighlighter highlighter = new WholeBreakIteratorPostingsHighlighter(10000); Query query = new TermQuery(new Term("body", "test")); TopDocs topDocs = searcher.Search(query, null, 10, Sort.INDEXORDER); assertEquals(1, topDocs.TotalHits); String[] snippets = highlighter.Highlight("body", query, searcher, topDocs, 2); assertEquals(1, snippets.Length); assertEquals("This is a <b>test</b>. Just highlighting from postings. This is also a much sillier <b>test</b>. Feel free to <b>test</b> <b>test</b> <b>test</b> <b>test</b> <b>test</b> <b>test</b> <b>test</b>.", snippets[0]); ir.Dispose(); dir.Dispose(); } internal class WholeBreakIteratorPostingsHighlighter : ICUPostingsHighlighter { public WholeBreakIteratorPostingsHighlighter() : base() { } public WholeBreakIteratorPostingsHighlighter(int maxLength) : base(maxLength) { } protected override BreakIterator GetBreakIterator(string field) { return new WholeBreakIterator(); } } [Test, LuceneNetSpecific] public void TestSpecificDocIDs() { Directory dir = NewDirectory(); IndexWriterConfig iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)); iwc.SetMergePolicy(NewLogMergePolicy()); RandomIndexWriter iw = new RandomIndexWriter(Random, dir, iwc); FieldType offsetsType = new FieldType(TextField.TYPE_STORED); offsetsType.IndexOptions = (IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS); Field body = new Field("body", "", offsetsType); Document doc = new Document(); doc.Add(body); body.SetStringValue("This is a test. Just a test highlighting from postings. Feel free to ignore."); iw.AddDocument(doc); body.SetStringValue("Highlighting the first term. Hope it works."); iw.AddDocument(doc); IndexReader ir = iw.GetReader(); iw.Dispose(); IndexSearcher searcher = NewSearcher(ir); ICUPostingsHighlighter highlighter = new ICUPostingsHighlighter(); Query query = new TermQuery(new Term("body", "highlighting")); TopDocs topDocs = searcher.Search(query, null, 10, Sort.INDEXORDER); assertEquals(2, topDocs.TotalHits); ScoreDoc[] hits = topDocs.ScoreDocs; int[] docIDs = new int[2]; docIDs[0] = hits[0].Doc; docIDs[1] = hits[1].Doc; String[] snippets = highlighter.HighlightFields(new String[] { "body" }, query, searcher, docIDs, new int[] { 1 })["body"]; assertEquals(2, snippets.Length); assertEquals("Just a test <b>highlighting</b> from postings. ", snippets[0]); assertEquals("<b>Highlighting</b> the first term. ", snippets[1]); ir.Dispose(); dir.Dispose(); } [Test, LuceneNetSpecific] public void TestCustomFieldValueSource() { Directory dir = NewDirectory(); IndexWriterConfig iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random, MockTokenizer.SIMPLE, true)); iwc.SetMergePolicy(NewLogMergePolicy()); RandomIndexWriter iw = new RandomIndexWriter(Random, dir, iwc); Document doc = new Document(); FieldType offsetsType = new FieldType(TextField.TYPE_NOT_STORED); offsetsType.IndexOptions = (IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS); String text = "This is a test. Just highlighting from postings. This is also a much sillier test. Feel free to test test test test test test test."; Field body = new Field("body", text, offsetsType); doc.Add(body); iw.AddDocument(doc); IndexReader ir = iw.GetReader(); iw.Dispose(); IndexSearcher searcher = NewSearcher(ir); ICUPostingsHighlighter highlighter = new LoadFieldValuesPostingsHighlighter(10000, text); Query query = new TermQuery(new Term("body", "test")); TopDocs topDocs = searcher.Search(query, null, 10, Sort.INDEXORDER); assertEquals(1, topDocs.TotalHits); String[] snippets = highlighter.Highlight("body", query, searcher, topDocs, 2); assertEquals(1, snippets.Length); assertEquals("This is a <b>test</b>. Just highlighting from postings. This is also a much sillier <b>test</b>. Feel free to <b>test</b> <b>test</b> <b>test</b> <b>test</b> <b>test</b> <b>test</b> <b>test</b>.", snippets[0]); ir.Dispose(); dir.Dispose(); } internal class LoadFieldValuesPostingsHighlighter : WholeBreakIteratorPostingsHighlighter { private readonly string text; public LoadFieldValuesPostingsHighlighter(int maxLength, string text) : base(maxLength) { this.text = text; } protected override IList<string[]> LoadFieldValues(IndexSearcher searcher, string[] fields, int[] docids, int maxLength) { if (Debugging.AssertsEnabled) { Debugging.Assert(fields.Length == 1); Debugging.Assert(docids.Length == 1); } String[][] contents = RectangularArrays.ReturnRectangularArray<string>(1, 1); //= new String[1][1]; contents[0][0] = text; return contents; } } /** Make sure highlighter returns first N sentences if * there were no hits. */ [Test, LuceneNetSpecific] public void TestEmptyHighlights() { Directory dir = NewDirectory(); IndexWriterConfig iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)); iwc.SetMergePolicy(NewLogMergePolicy()); RandomIndexWriter iw = new RandomIndexWriter(Random, dir, iwc); FieldType offsetsType = new FieldType(TextField.TYPE_STORED); offsetsType.IndexOptions = (IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS); Document doc = new Document(); Field body = new Field("body", "test this is. another sentence this test has. far away is that planet.", offsetsType); doc.Add(body); iw.AddDocument(doc); IndexReader ir = iw.GetReader(); iw.Dispose(); IndexSearcher searcher = NewSearcher(ir); ICUPostingsHighlighter highlighter = new ICUPostingsHighlighter(); Query query = new TermQuery(new Term("body", "highlighting")); int[] docIDs = new int[] { 0 }; String[] snippets = highlighter.HighlightFields(new String[] { "body" }, query, searcher, docIDs, new int[] { 2 })["body"]; assertEquals(1, snippets.Length); assertEquals("test this is. another sentence this test has. far away is that planet.", snippets[0]); ir.Dispose(); dir.Dispose(); } /** Make sure highlighter we can customize how emtpy * highlight is returned. */ [Test, LuceneNetSpecific] public void TestCustomEmptyHighlights() { Directory dir = NewDirectory(); IndexWriterConfig iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)); iwc.SetMergePolicy(NewLogMergePolicy()); RandomIndexWriter iw = new RandomIndexWriter(Random, dir, iwc); FieldType offsetsType = new FieldType(TextField.TYPE_STORED); offsetsType.IndexOptions = (IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS); Document doc = new Document(); Field body = new Field("body", "test this is. another sentence this test has. far away is that planet.", offsetsType); doc.Add(body); iw.AddDocument(doc); IndexReader ir = iw.GetReader(); iw.Dispose(); IndexSearcher searcher = NewSearcher(ir); ICUPostingsHighlighter highlighter = new GetEmptyHighlightPostingsHighlighter(); Query query = new TermQuery(new Term("body", "highlighting")); int[] docIDs = new int[] { 0 }; String[] snippets = highlighter.HighlightFields(new String[] { "body" }, query, searcher, docIDs, new int[] { 2 })["body"]; assertEquals(1, snippets.Length); assertNull(snippets[0]); ir.Dispose(); dir.Dispose(); } internal class GetEmptyHighlightPostingsHighlighter : ICUPostingsHighlighter { protected override Passage[] GetEmptyHighlight(string fieldName, BreakIterator bi, int maxPassages) { return new Passage[0]; } } /** Make sure highlighter returns whole text when there * are no hits and BreakIterator is null. */ [Test, LuceneNetSpecific] public void TestEmptyHighlightsWhole() { Directory dir = NewDirectory(); IndexWriterConfig iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)); iwc.SetMergePolicy(NewLogMergePolicy()); RandomIndexWriter iw = new RandomIndexWriter(Random, dir, iwc); FieldType offsetsType = new FieldType(TextField.TYPE_STORED); offsetsType.IndexOptions = (IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS); Document doc = new Document(); Field body = new Field("body", "test this is. another sentence this test has. far away is that planet.", offsetsType); doc.Add(body); iw.AddDocument(doc); IndexReader ir = iw.GetReader(); iw.Dispose(); IndexSearcher searcher = NewSearcher(ir); ICUPostingsHighlighter highlighter = new WholeBreakIteratorPostingsHighlighter(10000); Query query = new TermQuery(new Term("body", "highlighting")); int[] docIDs = new int[] { 0 }; String[] snippets = highlighter.HighlightFields(new String[] { "body" }, query, searcher, docIDs, new int[] { 2 })["body"]; assertEquals(1, snippets.Length); assertEquals("test this is. another sentence this test has. far away is that planet.", snippets[0]); ir.Dispose(); dir.Dispose(); } /** Make sure highlighter is OK with entirely missing * field. */ [Test, LuceneNetSpecific] public void TestFieldIsMissing() { Directory dir = NewDirectory(); IndexWriterConfig iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)); iwc.SetMergePolicy(NewLogMergePolicy()); RandomIndexWriter iw = new RandomIndexWriter(Random, dir, iwc); FieldType offsetsType = new FieldType(TextField.TYPE_STORED); offsetsType.IndexOptions = (IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS); Document doc = new Document(); Field body = new Field("body", "test this is. another sentence this test has. far away is that planet.", offsetsType); doc.Add(body); iw.AddDocument(doc); IndexReader ir = iw.GetReader(); iw.Dispose(); IndexSearcher searcher = NewSearcher(ir); ICUPostingsHighlighter highlighter = new ICUPostingsHighlighter(); Query query = new TermQuery(new Term("bogus", "highlighting")); int[] docIDs = new int[] { 0 }; String[] snippets = highlighter.HighlightFields(new String[] { "bogus" }, query, searcher, docIDs, new int[] { 2 })["bogus"]; assertEquals(1, snippets.Length); assertNull(snippets[0]); ir.Dispose(); dir.Dispose(); } [Test, LuceneNetSpecific] public void TestFieldIsJustSpace() { Directory dir = NewDirectory(); IndexWriterConfig iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)); iwc.SetMergePolicy(NewLogMergePolicy()); RandomIndexWriter iw = new RandomIndexWriter(Random, dir, iwc); FieldType offsetsType = new FieldType(TextField.TYPE_STORED); offsetsType.IndexOptions = (IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS); Document doc = new Document(); doc.Add(new Field("body", " ", offsetsType)); doc.Add(new Field("id", "id", offsetsType)); iw.AddDocument(doc); doc = new Document(); doc.Add(new Field("body", "something", offsetsType)); iw.AddDocument(doc); IndexReader ir = iw.GetReader(); iw.Dispose(); IndexSearcher searcher = NewSearcher(ir); ICUPostingsHighlighter highlighter = new ICUPostingsHighlighter(); int docID = searcher.Search(new TermQuery(new Term("id", "id")), 1).ScoreDocs[0].Doc; Query query = new TermQuery(new Term("body", "highlighting")); int[] docIDs = new int[1]; docIDs[0] = docID; String[] snippets = highlighter.HighlightFields(new String[] { "body" }, query, searcher, docIDs, new int[] { 2 })["body"]; assertEquals(1, snippets.Length); assertEquals(" ", snippets[0]); ir.Dispose(); dir.Dispose(); } [Test, LuceneNetSpecific] public void TestFieldIsEmptyString() { Directory dir = NewDirectory(); IndexWriterConfig iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)); iwc.SetMergePolicy(NewLogMergePolicy()); RandomIndexWriter iw = new RandomIndexWriter(Random, dir, iwc); FieldType offsetsType = new FieldType(TextField.TYPE_STORED); offsetsType.IndexOptions = (IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS); Document doc = new Document(); doc.Add(new Field("body", "", offsetsType)); doc.Add(new Field("id", "id", offsetsType)); iw.AddDocument(doc); doc = new Document(); doc.Add(new Field("body", "something", offsetsType)); iw.AddDocument(doc); IndexReader ir = iw.GetReader(); iw.Dispose(); IndexSearcher searcher = NewSearcher(ir); ICUPostingsHighlighter highlighter = new ICUPostingsHighlighter(); int docID = searcher.Search(new TermQuery(new Term("id", "id")), 1).ScoreDocs[0].Doc; Query query = new TermQuery(new Term("body", "highlighting")); int[] docIDs = new int[1]; docIDs[0] = docID; String[] snippets = highlighter.HighlightFields(new String[] { "body" }, query, searcher, docIDs, new int[] { 2 })["body"]; assertEquals(1, snippets.Length); assertNull(snippets[0]); ir.Dispose(); dir.Dispose(); } [Test, LuceneNetSpecific] public void TestMultipleDocs() { Directory dir = NewDirectory(); IndexWriterConfig iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)); iwc.SetMergePolicy(NewLogMergePolicy()); RandomIndexWriter iw = new RandomIndexWriter(Random, dir, iwc); FieldType offsetsType = new FieldType(TextField.TYPE_STORED); offsetsType.IndexOptions = (IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS); int numDocs = AtLeast(100); for (int i = 0; i < numDocs; i++) { Document doc = new Document(); String content = "the answer is " + i; if ((i & 1) == 0) { content += " some more terms"; } doc.Add(new Field("body", content, offsetsType)); doc.Add(NewStringField("id", "" + i, Field.Store.YES)); iw.AddDocument(doc); if (Random.nextInt(10) == 2) { iw.Commit(); } } IndexReader ir = iw.GetReader(); iw.Dispose(); IndexSearcher searcher = NewSearcher(ir); ICUPostingsHighlighter highlighter = new ICUPostingsHighlighter(); Query query = new TermQuery(new Term("body", "answer")); TopDocs hits = searcher.Search(query, numDocs); assertEquals(numDocs, hits.TotalHits); String[] snippets = highlighter.Highlight("body", query, searcher, hits); assertEquals(numDocs, snippets.Length); for (int hit = 0; hit < numDocs; hit++) { Document doc = searcher.Doc(hits.ScoreDocs[hit].Doc); int id = int.Parse(doc.Get("id"), CultureInfo.InvariantCulture); String expected = "the <b>answer</b> is " + id; if ((id & 1) == 0) { expected += " some more terms"; } assertEquals(expected, snippets[hit]); } ir.Dispose(); dir.Dispose(); } [Test, LuceneNetSpecific] public void TestMultipleSnippetSizes() { Directory dir = NewDirectory(); IndexWriterConfig iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random, MockTokenizer.SIMPLE, true)); iwc.SetMergePolicy(NewLogMergePolicy()); RandomIndexWriter iw = new RandomIndexWriter(Random, dir, iwc); FieldType offsetsType = new FieldType(TextField.TYPE_STORED); offsetsType.IndexOptions = (IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS); Field body = new Field("body", "", offsetsType); Field title = new Field("title", "", offsetsType); Document doc = new Document(); doc.Add(body); doc.Add(title); body.SetStringValue("This is a test. Just a test highlighting from postings. Feel free to ignore."); title.SetStringValue("This is a test. Just a test highlighting from postings. Feel free to ignore."); iw.AddDocument(doc); IndexReader ir = iw.GetReader(); iw.Dispose(); IndexSearcher searcher = NewSearcher(ir); ICUPostingsHighlighter highlighter = new ICUPostingsHighlighter(); BooleanQuery query = new BooleanQuery(); query.Add(new TermQuery(new Term("body", "test")), Occur.SHOULD); query.Add(new TermQuery(new Term("title", "test")), Occur.SHOULD); IDictionary<String, String[]> snippets = highlighter.HighlightFields(new String[] { "title", "body" }, query, searcher, new int[] { 0 }, new int[] { 1, 2 }); String titleHighlight = snippets["title"][0]; String bodyHighlight = snippets["body"][0]; assertEquals("This is a <b>test</b>. ", titleHighlight); assertEquals("This is a <b>test</b>. Just a <b>test</b> highlighting from postings. ", bodyHighlight); ir.Dispose(); dir.Dispose(); } [Test, LuceneNetSpecific] public void TestEncode() { Directory dir = NewDirectory(); IndexWriterConfig iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)); iwc.SetMergePolicy(NewLogMergePolicy()); RandomIndexWriter iw = new RandomIndexWriter(Random, dir, iwc); FieldType offsetsType = new FieldType(TextField.TYPE_STORED); offsetsType.IndexOptions = (IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS); Field body = new Field("body", "", offsetsType); Document doc = new Document(); doc.Add(body); body.SetStringValue("This is a test. Just a test highlighting from <i>postings</i>. Feel free to ignore."); iw.AddDocument(doc); IndexReader ir = iw.GetReader(); iw.Dispose(); IndexSearcher searcher = NewSearcher(ir); ICUPostingsHighlighter highlighter = new GetFormatterPostingsHighlighter(); Query query = new TermQuery(new Term("body", "highlighting")); TopDocs topDocs = searcher.Search(query, null, 10, Sort.INDEXORDER); assertEquals(1, topDocs.TotalHits); String[] snippets = highlighter.Highlight("body", query, searcher, topDocs); assertEquals(1, snippets.Length); assertEquals("Just&#32;a&#32;test&#32;<b>highlighting</b>&#32;from&#32;&lt;i&gt;postings&lt;&#x2F;i&gt;&#46;&#32;", snippets[0]); ir.Dispose(); dir.Dispose(); } internal class GetFormatterPostingsHighlighter : ICUPostingsHighlighter { protected override PassageFormatter GetFormatter(string field) { return new DefaultPassageFormatter("<b>", "</b>", "... ", true); } } /** customizing the gap separator to force a sentence break */ [Test, LuceneNetSpecific] public void TestGapSeparator() { Directory dir = NewDirectory(); // use simpleanalyzer for more natural tokenization (else "test." is a token) IndexWriterConfig iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random, MockTokenizer.SIMPLE, true)); iwc.SetMergePolicy(NewLogMergePolicy()); RandomIndexWriter iw = new RandomIndexWriter(Random, dir, iwc); FieldType offsetsType = new FieldType(TextField.TYPE_STORED); offsetsType.IndexOptions = (IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS); Document doc = new Document(); Field body1 = new Field("body", "", offsetsType); body1.SetStringValue("This is a multivalued field"); doc.Add(body1); Field body2 = new Field("body", "", offsetsType); body2.SetStringValue("This is something different"); doc.Add(body2); iw.AddDocument(doc); IndexReader ir = iw.GetReader(); iw.Dispose(); IndexSearcher searcher = NewSearcher(ir); ICUPostingsHighlighter highlighter = new GetMultiValuedSeparatorPostingsHighlighter(); Query query = new TermQuery(new Term("body", "field")); TopDocs topDocs = searcher.Search(query, null, 10, Sort.INDEXORDER); assertEquals(1, topDocs.TotalHits); String[] snippets = highlighter.Highlight("body", query, searcher, topDocs); assertEquals(1, snippets.Length); assertEquals("This is a multivalued <b>field</b>\u2029", snippets[0]); ir.Dispose(); dir.Dispose(); } internal class GetMultiValuedSeparatorPostingsHighlighter : ICUPostingsHighlighter { protected override char GetMultiValuedSeparator(string field) { if (Debugging.AssertsEnabled) Debugging.Assert(field.Equals("body", StringComparison.Ordinal)); return '\u2029'; } } // LUCENE-4906 [Test, LuceneNetSpecific] public void TestObjectFormatter() { Directory dir = NewDirectory(); IndexWriterConfig iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)); iwc.SetMergePolicy(NewLogMergePolicy()); RandomIndexWriter iw = new RandomIndexWriter(Random, dir, iwc); FieldType offsetsType = new FieldType(TextField.TYPE_STORED); offsetsType.IndexOptions = (IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS); Field body = new Field("body", "", offsetsType); Document doc = new Document(); doc.Add(body); body.SetStringValue("This is a test. Just a test highlighting from postings. Feel free to ignore."); iw.AddDocument(doc); IndexReader ir = iw.GetReader(); iw.Dispose(); IndexSearcher searcher = NewSearcher(ir); ICUPostingsHighlighter highlighter = new ObjectFormatterPostingsHighlighter(); Query query = new TermQuery(new Term("body", "highlighting")); TopDocs topDocs = searcher.Search(query, null, 10, Sort.INDEXORDER); assertEquals(1, topDocs.TotalHits); int[] docIDs = new int[1]; docIDs[0] = topDocs.ScoreDocs[0].Doc; IDictionary<String, Object[]> snippets = highlighter.HighlightFieldsAsObjects(new String[] { "body" }, query, searcher, docIDs, new int[] { 1 }); Object[] bodySnippets = snippets["body"]; assertEquals(1, bodySnippets.Length); assertTrue(Arrays.Equals(new String[] { "blah blah", "Just a test <b>highlighting</b> from postings. " }, (String[])bodySnippets[0])); ir.Dispose(); dir.Dispose(); } internal class ObjectFormatterPostingsHighlighter : ICUPostingsHighlighter { protected override PassageFormatter GetFormatter(string field) { return new PassageFormatterHelper(); } internal class PassageFormatterHelper : PassageFormatter { PassageFormatter defaultFormatter = new DefaultPassageFormatter(); public override object Format(Passage[] passages, string content) { // Just turns the String snippet into a length 2 // array of String return new String[] { "blah blah", defaultFormatter.Format(passages, content).toString() }; } } } } } #endif
{ "content_hash": "7df5f04209f8a62d72d47d090c48e4be", "timestamp": "", "source": "github", "line_count": 1233, "max_line_length": 238, "avg_line_length": 45.63503649635037, "alnum_prop": 0.5993993033340442, "repo_name": "sisve/lucenenet", "id": "1c15d4d70ed3cbffb7e2e9987171267f9558b410", "size": "57137", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/dotnet/Lucene.Net.Tests.ICU/Search/PostingsHighlight/TestICUPostingsHighlighter.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "4805" }, { "name": "C#", "bytes": "41089129" }, { "name": "Gnuplot", "bytes": "2444" }, { "name": "HTML", "bytes": "79746" }, { "name": "PowerShell", "bytes": "73932" }, { "name": "XSLT", "bytes": "21773" } ], "symlink_target": "" }
import yaml from transcoder.output import OutputManager class DiagnosticOutputManager(OutputManager): """Output manager for representing messages in diagnostic notation""" @staticmethod def output_type_identifier(): return 'diag' def write_record(self, record_type_name, record): print(yaml.dump(record))
{ "content_hash": "e4dd05ccdadbe0675a29149948abce89", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 74, "avg_line_length": 24.5, "alnum_prop": 0.7230320699708455, "repo_name": "GoogleCloudPlatform/market-data-transcoder", "id": "3d1cc6eccddf13cd8eb1f6142afda7e227638372", "size": "1158", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "transcoder/output/diag/DiagnosticOutputManager.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "377" }, { "name": "Python", "bytes": "153101" } ], "symlink_target": "" }
""" This file contains classes related to loading and saving a set of connection objects to an XML file. It defines the following classes: - ExtConnection - DBConnection - ExtConnectionList """ from __future__ import division import os import tempfile import unittest from vistrails.core.utils import VistrailsInternalError, abstract from vistrails.core.utils.enum import enum from vistrails.core.utils.uxml import named_elements, XMLWrapper ################################################################################ ConnectionType = enum('ConnectionType', ['DB', 'HTTP', 'Unknown'], "Enumeration of Connection Types") class ExtConnection(object): """Stores Information for an External Connection""" parseDispatch = {} def __init__(self, id=-1, name='', host='', type=ConnectionType.Unknown): """__init__(id: int, name: str, host: str, type: ConnectionType) -> ExtConnection It creates an external connection. Ignoring the connection type, every connection should have at least a name, a hostname and an id """ self.id = id self.name = name self.host = host self.type = type def serialize(self, dom, element): abstract() @staticmethod def parse(element): type = str(element.getAttribute('type')) return ExtConnection.parseDispatch[type](element) class DBConnection(ExtConnection): """Stores Information for Database Connection """ def __init__(self, id=-1, name='', host='', port=0, user='', passwd='', database='', dbtype=''): """__init__(id: int, name: str, host: str, port: int, username: str, passwd: str, database: str, type:ConnectionType)->DBConnection It creates a DBConnection Object """ ExtConnection.__init__(self, id, name, host, ConnectionType.DB) self.port = port self.user = user self.passwd = passwd self.database = database self.dbtype = dbtype def serialize(self, dom, element): """serialize(dom, element) -> None Convert this object to an XML representation. """ conn = dom.createElement('connection') conn.setAttribute('id', str(self.id)) conn.setAttribute('name', str(self.name)) conn.setAttribute('host', str(self.host)) conn.setAttribute('port',str(self.port)) conn.setAttribute('user', str(self.user)) conn.setAttribute('passwd', str(self.passwd)) conn.setAttribute('database', str(self.database)) conn.setAttribute('type', str(self.type)) conn.setAttribute('dbtype', str(self.dbtype)) element.appendChild(conn) def __str__(self): """ __str__() -> str - Writes itself as a string """ return """<<id= '%s' name='%s' type='%s' host='%s' user='%s' database='%s' dbtype='%s'>>""" % ( self.id, self.name, self.type, self.host, self.user, self.database, self.dbtype) @staticmethod def parse(element): """ parse(element) -> DBConnection Parse an XML object representing a DBConnection and returns a DBConnection object. """ conn = DBConnection() conn.type = ConnectionType.DB conn.id = int(element.getAttribute('id')) conn.name = str(element.getAttribute('name')) conn.host = str(element.getAttribute('host')) conn.port = int(element.getAttribute('port')) conn.user = str(element.getAttribute('user')) conn.passwd = str(element.getAttribute('passwd')) conn.database = str(element.getAttribute('database')) conn.dbtype = str(element.getAttribute('dbtype')) return conn def __eq__(self, other): """ __eq__(other: DBConnection) -> boolean Returns True if self and other have the same attributes. Used by == operator. """ if other is None: return False if self.type != other.type: return False if self.id != other.id: return False if self.name != other.name: return False if self.host != other.host: return False if self.port != other.port: return False if self.user != other.user: return False if self.passwd != other.passwd: return False if self.database != other.database: return False if self.dbtype != other.dbtype: return False return True def __ne__(self, other): return not (self == other) ExtConnection.parseDispatch[str(ConnectionType.DB)] = DBConnection.parse class ExtConnectionList(XMLWrapper): """Class to store and manage a list of connections. """ _instance = None @staticmethod def getInstance(*args, **kwargs): if ExtConnectionList._instance is None: obj = ExtConnectionList(*args, **kwargs) ExtConnectionList._instance = obj return ExtConnectionList._instance def __init__(self, filename=''): """ __init__() -> ExtConnectionList """ if not ExtConnectionList._instance: self.__connections = {} self.changed = False self.current_id = 1 self.filename = filename self.load_connections() ExtConnectionList._instance = self else: raise RuntimeError, 'Only one instance of ExtConnectionList is \ allowed!' def load_connections(self): """load_connections()-> None Load connections from its internal filename """ if os.path.exists(self.filename): self.parse(self.filename) def add_connection(self, conn): """add_connection(conn: ExtConnection) -> None Adds a connection to the list """ if self.__connections.has_key(conn.id): msg = "External Connection '%s' with repeated id" % conn.name raise VistrailsInternalError(msg) self.__connections[conn.id] = conn self.current_id = max(self.current_id, conn.id+1) self.serialize() def get_connection(self, id): """get_connection(id: int) -> ExtConnection Returns connection object associated with id """ if self.__connections.has_key(id): return self.__connections[id] else: return None def has_connection(self, id): """has_connection(id: int) -> Boolean Returns True if connection with id exists """ return self.__connections.has_key(id) def find_db_connection(self, host, port, db): """find_db_connection(host: str, port: int, db: str) -> id Returns the id of the first connection that matches the provided parameters. It will return -1 if not found """ for conn in self.__connections.itervalues(): if conn.host == host and conn.port == port and conn.database == db: return conn.id return -1 def set_connection(self, id, conn): """set_connection(id: int, conn: ExtConnection)- > None Updates the connection with id to be conn """ if self.__connections.has_key(id): self.__connections[id] = conn self.serialize() def remove_connection(self, id): """remove_connection(id: int) -> None Remove connection with id 'id' """ if self.__connections.has_key(id): del self.__connections[id] self.serialize() def clear(self): """ clear() -> None Remove current connections """ self.__connections.clear() self.current_id = 1 def count(self): """count() -> int - Returns the number of connections """ return len(self.__connections) def items(self): """ items() -> - Returns the connections """ return self.__connections.items() def parse(self, filename): """parse(filename: str) -> None Loads a list of connections from a XML file, appending it to self.__connections. """ self.open_file(filename) root = self.dom.documentElement for element in named_elements(root, 'connection'): self.add_connection(ExtConnection.parse(element)) self.refresh_current_id() def serialize(self): """serialize(filename:str) -> None Writes connection list to given filename. """ dom = self.create_document('connections') root = dom.documentElement for conn in self.__connections.values(): conn.serialize(dom, root) self.write_document(root, self.filename) def refresh_current_id(self): """refresh_current_id() -> None Recomputes the next unused id from scratch """ self.current_id = max([0] + self.__connections.keys()) + 1 def get_fresh_id(self): """get_fresh_id() -> int - Returns an unused id. """ return self.current_id ############################################################################### class TestConnectionList(unittest.TestCase): def test1(self): """ Exercising writing and reading a file """ fd, filename = tempfile.mkstemp(prefix='vt_', suffix='_connections.xml') os.close(fd) try: conns = ExtConnectionList.getInstance() conns.filename = filename conns.clear() conn = DBConnection() conn.id = 1 conn.name = 'test' conn.host = 'somehost.com' conn.port = 1234 conn.user = 'nobody' conn.passwd = '123' conn.database = 'anydatabase' conn.dbtype = 'MySQL' conns.add_connection(conn) #reading it again conns.clear() self.assertEquals(conns.count(),0) conns.load_connections() self.assertEquals(conns.count(),1) newconn = conns.get_connection(1) self.assertEqual(conn, newconn) finally: #remove created file os.unlink(filename) if __name__ == '__main__': unittest.main()
{ "content_hash": "2558259ebeb8a109fbafef6af48e4449", "timestamp": "", "source": "github", "line_count": 316, "max_line_length": 82, "avg_line_length": 33.18037974683544, "alnum_prop": 0.5642346208869814, "repo_name": "hjanime/VisTrails", "id": "8c18a8246b2aca8650fa233a04fdba9ea1eab11c", "size": "12398", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "vistrails/core/external_connection.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "1421" }, { "name": "Inno Setup", "bytes": "19550" }, { "name": "Makefile", "bytes": "768" }, { "name": "Mako", "bytes": "66613" }, { "name": "PHP", "bytes": "49302" }, { "name": "Python", "bytes": "19803915" }, { "name": "R", "bytes": "782836" }, { "name": "Ruby", "bytes": "875" }, { "name": "Shell", "bytes": "35024" }, { "name": "TeX", "bytes": "145333" }, { "name": "XSLT", "bytes": "1090" } ], "symlink_target": "" }
package javax.sip.header; import javax.sip.SipException; /** * This Exception is thrown when a user attempts decrement the Hop count when * the message as already reached its max number of forwards. * * @author BEA Systems, NIST * @version 1.2 */ public class TooManyHopsException extends SipException { /** * Constructs a new <code>TooManyHopsException</code> */ public TooManyHopsException(){ super(); } /** * Constructs a new <code>TooManyHopsException</code> with * the specified error message. * * @param message the detail of the error message */ public TooManyHopsException(String message) { super(message); } /** * Constructs a new <code>TooManyHopsException</code> with the * specified error message and specialized cause that triggered this error * condition. * * @param message the detail of the error message * @param cause the specialized cause that triggered this exception */ public TooManyHopsException(String message, Throwable cause) { super(message, cause); } }
{ "content_hash": "507a7c472394aa8c3a8755ac61b52bdf", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 77, "avg_line_length": 24.41304347826087, "alnum_prop": 0.6687444345503116, "repo_name": "fhg-fokus-nubomedia/signaling-plane", "id": "b695794e86b1c16f9cd2856627ddd0f7c1d448f9", "size": "1949", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "modules/lib-sip/src/main/java/javax/sip/header/TooManyHopsException.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "12152" }, { "name": "Groff", "bytes": "22" }, { "name": "HTML", "bytes": "2637100" }, { "name": "Java", "bytes": "5622899" }, { "name": "JavaScript", "bytes": "3448641" }, { "name": "Python", "bytes": "161709" }, { "name": "Shell", "bytes": "8658" } ], "symlink_target": "" }
<?php namespace Pantheon\Terminus\Collections; use Pantheon\Terminus\Models\OrganizationUpstream; /** * Class OrganizationUpstreams * @package Pantheon\Terminus\Collections */ class OrganizationUpstreams extends OrganizationOwnedCollection { const PRETTY_NAME = 'upstreams'; /** * @var string */ protected $collected_class = OrganizationUpstream::class; /** * @var string */ protected $url = 'organizations/{organization_id}/upstreams'; /** * Filters an array of Upstreams by their label * * @param string $regex Non-delimited PHP regex to filter site names by * @return Upstreams */ public function filterByName($regex = '(.*)') { return $this->filterByRegex('label', $regex); } }
{ "content_hash": "59d492a5f903e044b6e29ee674d1b39e", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 75, "avg_line_length": 23.575757575757574, "alnum_prop": 0.6593830334190232, "repo_name": "pantheon-systems/cli", "id": "6ab437f75250773eb724d85bcb95eff5121c8fa0", "size": "778", "binary": false, "copies": "3", "ref": "refs/heads/CMS-933", "path": "src/Collections/OrganizationUpstreams.php", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "42" }, { "name": "Cucumber", "bytes": "67364" }, { "name": "HTML", "bytes": "1384" }, { "name": "PHP", "bytes": "483025" }, { "name": "Shell", "bytes": "16794" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace XOMNI.SDK.Model.Private.Catalog { [Flags] public enum DynamicAttributeTypeOptions : byte { NotInitialized = 0, Retrievable = 1, Filterable = 2, Searchable = 4, Facetable = 8, Sortable = 16, } }
{ "content_hash": "c0c32ef28dd1e87e636dce0599d891b2", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 50, "avg_line_length": 19.77777777777778, "alnum_prop": 0.6207865168539326, "repo_name": "nseckinoral/xomni-sdk-dotnet", "id": "c8f7dc604e49106b9e2963fb41c20e3d4595318e", "size": "358", "binary": false, "copies": "1", "ref": "refs/heads/dev", "path": "src/XOMNI.SDK.Model.Private/Catalog/DynamicAttributeTypeOptions.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "1192844" } ], "symlink_target": "" }
/* * Do not modify this file. This file is generated from the cloudfront-2015-04-17.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.CloudFront.Model { /// <summary> /// The returned result of the corresponding request. /// </summary> public partial class GetStreamingDistributionConfigResponse : AmazonWebServiceResponse { private string _eTag; private StreamingDistributionConfig _streamingDistributionConfig; /// <summary> /// Gets and sets the property ETag. The current version of the configuration. For example: /// E2QWRUHAPOMQZL. /// </summary> public string ETag { get { return this._eTag; } set { this._eTag = value; } } // Check to see if ETag property is set internal bool IsSetETag() { return this._eTag != null; } /// <summary> /// Gets and sets the property StreamingDistributionConfig. The streaming distribution's /// configuration information. /// </summary> public StreamingDistributionConfig StreamingDistributionConfig { get { return this._streamingDistributionConfig; } set { this._streamingDistributionConfig = value; } } // Check to see if StreamingDistributionConfig property is set internal bool IsSetStreamingDistributionConfig() { return this._streamingDistributionConfig != null; } } }
{ "content_hash": "59035e23988329e2e059e67d9c555a7f", "timestamp": "", "source": "github", "line_count": 58, "max_line_length": 108, "avg_line_length": 28.96551724137931, "alnum_prop": 0.638095238095238, "repo_name": "mwilliamson-firefly/aws-sdk-net", "id": "05d1df2771637eb51b9fe3b2d2f259e5fda51aea", "size": "2267", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "sdk/src/Services/CloudFront/Generated/Model/GetStreamingDistributionConfigResponse.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "73553647" }, { "name": "CSS", "bytes": "18119" }, { "name": "HTML", "bytes": "24362" }, { "name": "JavaScript", "bytes": "6576" }, { "name": "PowerShell", "bytes": "12587" }, { "name": "XSLT", "bytes": "7010" } ], "symlink_target": "" }
const assert = require('assert') module.exports = async function (request, email, password) { const { header, statusCode } = await request .post('/api/session') .set('Accept', 'application/json') .send({ email, password: password || 'testing' }) assert.strictEqual(statusCode, 204) const cookie = header['set-cookie'].join(';') return cookie }
{ "content_hash": "7a18ba9811969f50ca0e709114beb37f", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 60, "avg_line_length": 26.285714285714285, "alnum_prop": 0.6657608695652174, "repo_name": "BanManagement/BanManager-WebUI", "id": "2649085d0879cf385d5bf193fa6174a78dc42831", "size": "368", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "server/test/lib/get-auth-password.js", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "31" }, { "name": "CSS", "bytes": "8553" }, { "name": "Dockerfile", "bytes": "1507" }, { "name": "JavaScript", "bytes": "1253411" } ], "symlink_target": "" }
import jinja2 import os import webapp2 from google.appengine.ext import ndb def guestbook_key(guestbook_name='default_guestbook'): return ndb.Key('Guestbook', guestbook_name) jinja_environment = jinja2.Environment( loader=jinja2.FileSystemLoader(os.path.dirname(__file__)), extensions=['jinja2.ext.autoescape'], autoescape=True) class Greeting(ndb.Model): content = ndb.StringProperty() date = ndb.DateTimeProperty(auto_now_add=True) class MainPage(webapp2.RequestHandler): def get(self): greetings_query = Greeting.query( ancestor=guestbook_key()).order(-Greeting.date) greetings = greetings_query.fetch(10) template = jinja_environment.get_template('index.html') self.response.out.write(template.render(entries=greetings)) def post(self): greeting = Greeting(parent=guestbook_key()) greeting.content = self.request.get('entry') greeting.put() self.redirect('/') class Clear(webapp2.RequestHandler): def post(self): greetings_query = Greeting.query( ancestor=guestbook_key()).fetch(keys_only=True) ndb.delete_multi(greetings_query) self.redirect('/') application = webapp2.WSGIApplication([ ('/', MainPage), ('/clear', Clear), ], debug=True)
{ "content_hash": "82b8a4f37a87a993d2a713345aef25e7", "timestamp": "", "source": "github", "line_count": 48, "max_line_length": 67, "avg_line_length": 28.333333333333332, "alnum_prop": 0.6507352941176471, "repo_name": "GoogleCloudPlatformTraining/cp100-appengine-datastore-python", "id": "d3506d36cd4852de7725f91c9e982235a7b4e751", "size": "1977", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "guestbook.py", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "1076" }, { "name": "Python", "bytes": "1977" } ], "symlink_target": "" }
try: import pkg_resources except ImportError: pkg_resources = None def is_namespace(modname): # pylint: disable=no-member; astroid issue #290, modifying globals at runtime. return (pkg_resources is not None and modname in pkg_resources._namespace_packages)
{ "content_hash": "91f38514e96f33e704848e0e8731c1e0", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 82, "avg_line_length": 28.7, "alnum_prop": 0.710801393728223, "repo_name": "rvmoura96/projeto-almoxarifado", "id": "79ff4e0a66e399d68fbdb904c751affb7781f6fe", "size": "346", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "myvenv/Lib/site-packages/astroid/interpreter/_import/util.py", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "1298" }, { "name": "C", "bytes": "426659" }, { "name": "C++", "bytes": "237226" }, { "name": "CSS", "bytes": "47496" }, { "name": "DTrace", "bytes": "863" }, { "name": "HTML", "bytes": "106823" }, { "name": "JavaScript", "bytes": "115482" }, { "name": "PowerShell", "bytes": "8175" }, { "name": "Python", "bytes": "11286094" }, { "name": "Shell", "bytes": "182" }, { "name": "Tcl", "bytes": "1295070" } ], "symlink_target": "" }
import Subscription from './subscription'; import Operation from 'orbit/operation'; import Orbit from 'orbit/main'; import { lookupTransformation } from 'orbit-firebase/transformations'; export default Subscription.extend({ init: function(path, listener){ this.path = path; this.listener = listener; this.schema = listener._schema; }, activate: function(){ var _this = this, listener = this.listener, path = this.path, splitPath = this.path.split("/"), type = splitPath[0], recordId = splitPath[1], attribute = splitPath[2]; return listener._enableListener(path, "value", function(snapshot){ var splitPath = path.split('/'); var model = splitPath[0]; var attribute = splitPath[2]; var attrType = _this.schema.models[model].attributes[attribute].type; var transformation = lookupTransformation(attrType); var serialized = snapshot.val(); var deserialized = transformation.deserialize(serialized); listener._emitDidTransform(new Operation({ op: 'replace', path: path, value: deserialized })); return Orbit.resolve(); }); }, update: function(){ return Orbit.resolve(); } });
{ "content_hash": "3528a4d3b9080853cc02b43e98c022bd", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 97, "avg_line_length": 29.28205128205128, "alnum_prop": 0.7005253940455342, "repo_name": "lytbulb/orbit-firebase", "id": "862aa1c441155a83d79ea93c295380bc35a55c49", "size": "1142", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/orbit-firebase/subscriptions/attribute-subscription.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "448" }, { "name": "JavaScript", "bytes": "385130" }, { "name": "Shell", "bytes": "793" } ], "symlink_target": "" }
module MarionetteDust module Generators module Helpers def asset_path File.join('app', 'assets') end def javascript_path File.join(asset_path, 'javascripts') end def entities_path File.join(javascript_path, "entities") end def apps_path File.join(javascript_path, "apps") end def template_path File.join(asset_path, "templates") end def singular_file_name "#{file_name.singularize}#{extension}" end def plural_file_name "#{file_name.pluralize}#{extension}" end def asset_file_name(type) "#{@submodule_name.downcase.singularize}_#{type}#{extension}" end def singular_entity_name file_name.singularize.camelize end def plural_entity_name file_name.pluralize.camelize end def sub_app_name [file_name.camelize, "App"].join("") end def sub_app_file_name [file_name.singularize.downcase, "_app", "#{extension}"].join("") end def sub_app_scope @submodule_name.camelize end def extension @ext ||= options.coffeescript ? ".js.coffee" : ".js" end def app_name rails_app_name.camelize end def rails_app_name Rails.application.class.name.split('::').first end def trackeable_directory(path) empty_directory path template ".gitkeep", "#{path}/.gitkeep" end end end end
{ "content_hash": "1624239d070f697a59e3fcd1e18983a0", "timestamp": "", "source": "github", "line_count": 75, "max_line_length": 73, "avg_line_length": 20.44, "alnum_prop": 0.5727332028701891, "repo_name": "roperzh/marionette_dust-rails", "id": "d026027c7aabafda16f80d0975b73ea00e3aff5f", "size": "1533", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/generators/md/helpers.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CoffeeScript", "bytes": "1424" }, { "name": "JavaScript", "bytes": "1697" }, { "name": "Ruby", "bytes": "15032" } ], "symlink_target": "" }
module.exports = { after: require("./after"), apply: require("./apply"), ary: require("./ary"), attempt: require("./attempt"), before: require("./before"), call: require("./call"), debounce: require("./debounce"), delay: require("./delay"), iterate: require("./iterate"), memoize: require("./memoize"), mock: require("./mock"), negate: require("./negate"), once: require("./once"), parallel: require("./parallel"), throttle: require("./throttle"), waterfall: require("./waterfall"), wrap: require("./wrap") };
{ "content_hash": "85f1a644f9c294237df3349a6cb5f8e2", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 38, "avg_line_length": 30.36842105263158, "alnum_prop": 0.5753899480069324, "repo_name": "rl189020/expandjs", "id": "98cd01df1adfb6a2003b141d17174ddd4ec5c661", "size": "577", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "lib/function/index.js", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "HTML", "bytes": "731" }, { "name": "JavaScript", "bytes": "1419082" } ], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.9.1"/> <title>V8 API Reference Guide for node.js v5.9.0 - v5.9.1: Class Members</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { init_search(); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">V8 API Reference Guide for node.js v5.9.0 - v5.9.1 </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.9.1 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> <li><a href="examples.html"><span>Examples</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&#160;List</span></a></li> <li><a href="classes.html"><span>Class&#160;Index</span></a></li> <li><a href="inherits.html"><span>Class&#160;Hierarchy</span></a></li> <li class="current"><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </div> <div id="navrow3" class="tabs2"> <ul class="tablist"> <li class="current"><a href="functions.html"><span>All</span></a></li> <li><a href="functions_func.html"><span>Functions</span></a></li> <li><a href="functions_vars.html"><span>Variables</span></a></li> <li><a href="functions_type.html"><span>Typedefs</span></a></li> <li><a href="functions_enum.html"><span>Enumerations</span></a></li> </ul> </div> <div id="navrow4" class="tabs3"> <ul class="tablist"> <li><a href="functions.html#index_a"><span>a</span></a></li> <li><a href="functions_b.html#index_b"><span>b</span></a></li> <li class="current"><a href="functions_c.html#index_c"><span>c</span></a></li> <li><a href="functions_d.html#index_d"><span>d</span></a></li> <li><a href="functions_e.html#index_e"><span>e</span></a></li> <li><a href="functions_f.html#index_f"><span>f</span></a></li> <li><a href="functions_g.html#index_g"><span>g</span></a></li> <li><a href="functions_h.html#index_h"><span>h</span></a></li> <li><a href="functions_i.html#index_i"><span>i</span></a></li> <li><a href="functions_j.html#index_j"><span>j</span></a></li> <li><a href="functions_k.html#index_k"><span>k</span></a></li> <li><a href="functions_l.html#index_l"><span>l</span></a></li> <li><a href="functions_m.html#index_m"><span>m</span></a></li> <li><a href="functions_n.html#index_n"><span>n</span></a></li> <li><a href="functions_o.html#index_o"><span>o</span></a></li> <li><a href="functions_p.html#index_p"><span>p</span></a></li> <li><a href="functions_r.html#index_r"><span>r</span></a></li> <li><a href="functions_s.html#index_s"><span>s</span></a></li> <li><a href="functions_t.html#index_t"><span>t</span></a></li> <li><a href="functions_u.html#index_u"><span>u</span></a></li> <li><a href="functions_v.html#index_v"><span>v</span></a></li> <li><a href="functions_w.html#index_w"><span>w</span></a></li> <li><a href="functions_~.html#index_~"><span>~</span></a></li> </ul> </div> </div><!-- top --> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div class="contents"> <div class="textblock">Here is a list of all documented class members with links to the class documentation for each member:</div> <h3><a class="anchor" id="index_c"></a>- c -</h3><ul> <li>CachedDataVersionTag() : <a class="el" href="classv8_1_1ScriptCompiler.html#aea78877b0dccde1e587ee1ddeda1c155">v8::ScriptCompiler</a> </li> <li>CallDelayedOnForegroundThread() : <a class="el" href="classv8_1_1Platform.html#a72bff12d95fbf2118279b0e8f53f8a4b">v8::Platform</a> </li> <li>CallIdleOnForegroundThread() : <a class="el" href="classv8_1_1Platform.html#ae495999016432391f04d323452084b12">v8::Platform</a> </li> <li>CallOnBackgroundThread() : <a class="el" href="classv8_1_1Platform.html#aa715e6839c1954b4e23b9d2df00bd3ea">v8::Platform</a> </li> <li>CallOnForegroundThread() : <a class="el" href="classv8_1_1Platform.html#a8fa13959f919d1d3ff170bceea939915">v8::Platform</a> </li> <li>CancelTerminateExecution() : <a class="el" href="classv8_1_1Isolate.html#a75cbe037e7657a7c7bd65e2edf0164d5">v8::Isolate</a> </li> <li>CanContinue() : <a class="el" href="classv8_1_1TryCatch.html#a2ec467d4653d26c064d749cab98791cb">v8::TryCatch</a> </li> <li>CanMakeExternal() : <a class="el" href="classv8_1_1String.html#a0fe076838af046506ffebbfadcde812a">v8::String</a> </li> <li>Clear() : <a class="el" href="classv8_1_1Local.html#a6fcf63af6bdd697ddd7c3acd16c69899">v8::Local&lt; T &gt;</a> , <a class="el" href="classv8_1_1PersistentValueMapBase.html#a1bf074e7a7c24713c9a3d40ddce89e74">v8::PersistentValueMapBase&lt; K, V, Traits &gt;</a> , <a class="el" href="classv8_1_1PersistentValueVector.html#ad07f449c2004b4f3d91e58cabde99a53">v8::PersistentValueVector&lt; V, Traits &gt;</a> </li> <li>ClearObjectIds() : <a class="el" href="classv8_1_1HeapProfiler.html#a8a90c630543ed1875cbf9166239ff8d3">v8::HeapProfiler</a> </li> <li>Clone() : <a class="el" href="classv8_1_1Object.html#a5018c9d085aa71f65530cf1e073a04ad">v8::Object</a> </li> <li>code_event_handler : <a class="el" href="structv8_1_1Isolate_1_1CreateParams.html#a783e3eba90ce6e2800bdd69197bbccdd">v8::Isolate::CreateParams</a> </li> <li>CompileModule() : <a class="el" href="classv8_1_1ScriptCompiler.html#a42373c4d7c20048db0dd9482410d48d6">v8::ScriptCompiler</a> </li> <li>Concat() : <a class="el" href="classv8_1_1String.html#ae72b61a78cef5d2916a87d9032c7fd34">v8::String</a> </li> <li>ConfigureDefaults() : <a class="el" href="classv8_1_1ResourceConstraints.html#aeeaaee4017e8d5f8f0439af2af2ed3a5">v8::ResourceConstraints</a> </li> <li>constraints : <a class="el" href="structv8_1_1Isolate_1_1CreateParams.html#a2c570b306aa8c1c24cfe70e8eee50fa1">v8::Isolate::CreateParams</a> </li> <li>Contains() : <a class="el" href="classv8_1_1PersistentValueMapBase.html#a8c68e5f99c4042541c6d32232c97282a">v8::PersistentValueMapBase&lt; K, V, Traits &gt;</a> </li> <li>ContainsOnlyOneByte() : <a class="el" href="classv8_1_1String.html#a4ae1fe1175bd5b96bfa53f5f5ee835e9">v8::String</a> </li> <li>ContextDisposedNotification() : <a class="el" href="classv8_1_1Isolate.html#a4b5216bbb1792211422aee575d02f442">v8::Isolate</a> </li> <li>CopyContents() : <a class="el" href="classv8_1_1ArrayBufferView.html#aa728e762ed43194f3a5e05e792fff64e">v8::ArrayBufferView</a> </li> <li>counter_lookup_callback : <a class="el" href="structv8_1_1Isolate_1_1CreateParams.html#a10441abadd0b83a938303c92e7444fb6">v8::Isolate::CreateParams</a> </li> <li>create_histogram_callback : <a class="el" href="structv8_1_1Isolate_1_1CreateParams.html#a11acf5fb9cdbc4c8bf15baf542507b49">v8::Isolate::CreateParams</a> </li> <li>CreateMessage() : <a class="el" href="classv8_1_1Exception.html#a366e09958653d62729e796a9b4d74f59">v8::Exception</a> </li> <li>CreateSnapshotDataBlob() : <a class="el" href="classv8_1_1V8.html#a0afd98f054412cf57318c0657e9a393f">v8::V8</a> </li> <li>CreationContext() : <a class="el" href="classv8_1_1Object.html#af6966283a7d7e20779961eed434db04d">v8::Object</a> </li> <li>CurrentStackTrace() : <a class="el" href="classv8_1_1StackTrace.html#a030e8de1b13d720bb2bfac5cb8bc914b">v8::StackTrace</a> </li> </ul> </div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.9.1 </small></address> </body> </html>
{ "content_hash": "032c02265d485b0de6b7ba8e0adde3cd", "timestamp": "", "source": "github", "line_count": 215, "max_line_length": 154, "avg_line_length": 46.716279069767445, "alnum_prop": 0.6737355635205098, "repo_name": "v8-dox/v8-dox.github.io", "id": "969dabb7626bef9988559fb2129065e878f3369a", "size": "10044", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "b6c355d/html/functions_c.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <!-- $Revision: 322115 $ --> <refentry xmlns="http://docbook.org/ns/docbook" xml:id="imagickdraw.clone"> <refnamediv> <refname>ImagickDraw::clone</refname> <refpurpose>Makes an exact copy of the specified ImagickDraw object</refpurpose> </refnamediv> <refsect1 role="description"> &reftitle.description; <methodsynopsis> <type>ImagickDraw</type><methodname>ImagickDraw::clone</methodname> <void/> </methodsynopsis> &warn.undocumented.func; <para> Makes an exact copy of the specified ImagickDraw object. </para> </refsect1> <refsect1 role="returnvalues"> &reftitle.returnvalues; <para> What the function returns, first on success, then on failure. See also the &amp;return.success; entity </para> </refsect1> </refentry> <!-- Keep this comment at the end of the file Local variables: mode: sgml sgml-omittag:t sgml-shorttag:t sgml-minimize-attributes:nil sgml-always-quote-attributes:t sgml-indent-step:1 sgml-indent-data:t indent-tabs-mode:nil sgml-parent-document:nil sgml-default-dtd-file:"~/.phpdoc/manual.ced" sgml-exposed-tags:nil sgml-local-catalogs:nil sgml-local-ecat-files:nil End: vim600: syn=xml fen fdm=syntax fdl=2 si vim: et tw=78 syn=sgml vi: ts=1 sw=1 -->
{ "content_hash": "8410b8690d2145de79928828d36cf50c", "timestamp": "", "source": "github", "line_count": 50, "max_line_length": 82, "avg_line_length": 25.18, "alnum_prop": 0.7307386814932486, "repo_name": "mziyut/.vim", "id": "3daaf6de9a7a65beab274f76809a3ea3969d324b", "size": "1259", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "dict/.neocomplete-php/phpdoc/en/reference/imagick/imagickdraw/clone.xml", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "2223" }, { "name": "Ruby", "bytes": "939" }, { "name": "Shell", "bytes": "582" }, { "name": "Vim script", "bytes": "22415" } ], "symlink_target": "" }