repo_name
stringlengths
4
116
path
stringlengths
3
942
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
hjobrien/desktop
app/src/ui/changes/commit-message.tsx
8310
import * as React from 'react' import { AutocompletingTextArea, AutocompletingInput, IAutocompletionProvider, } from '../autocompletion' import { CommitIdentity } from '../../models/commit-identity' import { ICommitMessage } from '../../lib/app-state' import { Dispatcher } from '../../lib/dispatcher' import { IGitHubUser } from '../../lib/databases/github-user-database' import { Repository } from '../../models/repository' import { Button } from '../lib/button' import { Avatar } from '../lib/avatar' import { Loading } from '../lib/loading' import { structuralEquals } from '../../lib/equality' interface ICommitMessageProps { readonly onCreateCommit: (message: ICommitMessage) => Promise<boolean> readonly branch: string | null readonly commitAuthor: CommitIdentity | null readonly gitHubUser: IGitHubUser | null readonly anyFilesSelected: boolean readonly commitMessage: ICommitMessage | null readonly contextualCommitMessage: ICommitMessage | null readonly repository: Repository readonly dispatcher: Dispatcher readonly autocompletionProviders: ReadonlyArray<IAutocompletionProvider<any>> readonly isCommitting: boolean } interface ICommitMessageState { readonly summary: string readonly description: string | null /** The last contextual commit message we've received. */ readonly lastContextualCommitMessage: ICommitMessage | null } export class CommitMessage extends React.Component< ICommitMessageProps, ICommitMessageState > { public constructor(props: ICommitMessageProps) { super(props) this.state = { summary: '', description: '', lastContextualCommitMessage: null, } } public componentWillMount() { this.receiveProps(this.props, true) } public componentWillUnmount() { // We're unmounting, likely due to the user switching to the history tab. // Let's persist our commit message in the dispatcher. this.props.dispatcher.setCommitMessage(this.props.repository, this.state) } public componentWillReceiveProps(nextProps: ICommitMessageProps) { this.receiveProps(nextProps, false) } private receiveProps(nextProps: ICommitMessageProps, initializing: boolean) { // If we're switching away from one repository to another we'll persist // our commit message in the dispatcher. if (nextProps.repository.id !== this.props.repository.id) { this.props.dispatcher.setCommitMessage(this.props.repository, this.state) } // This is rather gnarly. We want to persist the commit message (summary, // and description) in the dispatcher on a per-repository level (git-store). // // Our dispatcher is asynchronous and only emits and update on animation // frames. This is a great thing for performance but it gets real messy // when you throw text boxes into the mix. If we went for a traditional // approach of persisting the textbox values in the dispatcher and updating // the virtual dom when we get new props there's an interim state which // means that the browser can't keep track of the cursor for us, see: // // http://stackoverflow.com/a/28922465 // // So in order to work around that we keep the text values in the component // state. Whenever they get updated we submit the update to the dispatcher // but we disregard the message that flows to us on the subsequent animation // frame unless we have switched repositories. // // Then there's the case when we're being mounted (think switching between // history and changes tabs. In that case we have to rely on what's in the // dispatcher since we don't have any state of our own. const nextContextualCommitMessage = nextProps.contextualCommitMessage const lastContextualCommitMessage = this.state.lastContextualCommitMessage // If the contextual commit message changed, we'll use it as our commit // message. if ( nextContextualCommitMessage && (!lastContextualCommitMessage || !structuralEquals( nextContextualCommitMessage, lastContextualCommitMessage )) ) { this.setState({ summary: nextContextualCommitMessage.summary, description: nextContextualCommitMessage.description, lastContextualCommitMessage: nextContextualCommitMessage, }) } else if ( initializing || this.props.repository.id !== nextProps.repository.id ) { // We're either initializing (ie being mounted) or someone has switched // repositories. If we receive a message we'll take it if (nextProps.commitMessage) { // Don't update dispatcher here, we're receiving it, could cause never- // ending loop. this.setState({ summary: nextProps.commitMessage.summary, description: nextProps.commitMessage.description, lastContextualCommitMessage: nextContextualCommitMessage, }) } else { // No message, assume clean slate this.setState({ summary: '', description: null, lastContextualCommitMessage: nextContextualCommitMessage, }) } } else { this.setState({ lastContextualCommitMessage: nextContextualCommitMessage, }) } } private clearCommitMessage() { this.setState({ summary: '', description: null }) } private onSummaryChanged = (summary: string) => { this.setState({ summary }) } private onDescriptionChanged = (description: string) => { this.setState({ description }) } private onSubmit = () => { this.createCommit() } private async createCommit() { if (!this.canCommit) { return } const success = await this.props.onCreateCommit({ // We know that summary is non-null thanks to canCommit summary: this.state.summary!, description: this.state.description, }) if (success) { this.clearCommitMessage() } } private canCommit(): boolean { return ( this.props.anyFilesSelected && this.state.summary !== null && this.state.summary.length > 0 ) } private onKeyDown = (event: React.KeyboardEvent<Element>) => { const isShortcutKey = __DARWIN__ ? event.metaKey : event.ctrlKey if (isShortcutKey && event.key === 'Enter' && this.canCommit()) { this.createCommit() event.preventDefault() } } private renderAvatar() { const commitAuthor = this.props.commitAuthor const avatarTitle = commitAuthor ? `Committing as ${commitAuthor.name} <${commitAuthor.email}>` : undefined let avatarUser = undefined if (commitAuthor && this.props.gitHubUser) { avatarUser = { email: commitAuthor.email, name: commitAuthor.name, avatarURL: this.props.gitHubUser.avatarURL, } } return <Avatar user={avatarUser} title={avatarTitle} /> } public render() { const branchName = this.props.branch ? this.props.branch : 'master' const buttonEnabled = this.canCommit() && !this.props.isCommitting const loading = this.props.isCommitting ? <Loading /> : undefined return ( <div id="commit-message" role="group" aria-label="Create commit"> <div className="summary"> {this.renderAvatar()} <AutocompletingInput className="summary-field" placeholder="Summary" value={this.state.summary} onValueChanged={this.onSummaryChanged} onKeyDown={this.onKeyDown} autocompletionProviders={this.props.autocompletionProviders} /> </div> <AutocompletingTextArea className="description-field" placeholder="Description" value={this.state.description || ''} onValueChanged={this.onDescriptionChanged} onKeyDown={this.onKeyDown} autocompletionProviders={this.props.autocompletionProviders} /> <Button type="submit" className="commit-button" onClick={this.onSubmit} disabled={!buttonEnabled} > {loading} <span title={`Commit to ${branchName}`}> {loading ? 'Committing' : 'Commit'} to <strong>{branchName}</strong> </span> </Button> </div> ) } }
mit
rikzuiderlicht/concrete5
concrete/js/ckeditor4/vendor/plugins/a11yhelp/dialogs/lang/cs.js
4851
/* Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.plugins.setLang("a11yhelp","cs",{title:"Instrukce pro přístupnost",contents:"Obsah nápovědy. Pro uzavření tohoto dialogu stiskněte klávesu ESC.",legend:[{name:"Obecné",items:[{name:"Panel nástrojů editoru",legend:"Stiskněte${toolbarFocus} k procházení panelu nástrojů. Přejděte na další a předchozí skupiny pomocí TAB a SHIFT+TAB. Přechod na další a předchozí tlačítko panelu nástrojů je pomocí ŠIPKA VPRAVO nebo ŠIPKA VLEVO. Stisknutím mezerníku nebo klávesy ENTER tlačítko aktivujete."},{name:"Dialogové okno editoru", legend:"Uvnitř dialogového okna stiskněte TAB pro přesunutí na další prvek okna, stiskněte SHIFT+TAB pro přesun na předchozí prvek okna, stiskněte ENTER pro odeslání dialogu, stiskněte ESC pro jeho zrušení. Pro dialogová okna, která mají mnoho karet stiskněte ALT+F10 pro zaměření seznamu karet, nebo TAB, pro posun podle pořadí karet.Při zaměření seznamu karet se můžete jimi posouvat pomocí ŠIPKY VPRAVO a VLEVO."},{name:"Kontextové menu editoru",legend:"Stiskněte ${contextMenu} nebo klávesu APPLICATION k otevření kontextového menu. Pak se přesuňte na další možnost menu pomocí TAB nebo ŠIPKY DOLŮ. Přesuňte se na předchozí možnost pomocí SHIFT+TAB nebo ŠIPKY NAHORU. Stiskněte MEZERNÍK nebo ENTER pro zvolení možnosti menu. Podmenu současné možnosti otevřete pomocí MEZERNÍKU nebo ENTER či ŠIPKY DOLEVA. Kontextové menu uzavřete stiskem ESC."}, {name:"Rámeček seznamu editoru",legend:"Uvnitř rámečku seznamu se přesunete na další položku menu pomocí TAB nebo ŠIPKA DOLŮ. Na předchozí položku se přesunete SHIFT+TAB nebo ŠIPKA NAHORU. Stiskněte MEZERNÍK nebo ENTER pro zvolení možnosti seznamu. Stiskněte ESC pro uzavření seznamu."},{name:"Lišta cesty prvku v editoru",legend:"Stiskněte ${elementsPathFocus} pro procházení lišty cesty prvku. Na další tlačítko prvku se přesunete pomocí TAB nebo ŠIPKA VPRAVO. Na předchozí tlačítko se přesunete pomocí SHIFT+TAB nebo ŠIPKA VLEVO. Stiskněte MEZERNÍK nebo ENTER pro vybrání prvku v editoru."}]}, {name:"Příkazy",items:[{name:" Příkaz Zpět",legend:"Stiskněte ${undo}"},{name:" Příkaz Znovu",legend:"Stiskněte ${redo}"},{name:" Příkaz Tučné",legend:"Stiskněte ${bold}"},{name:" Příkaz Kurzíva",legend:"Stiskněte ${italic}"},{name:" Příkaz Podtržení",legend:"Stiskněte ${underline}"},{name:" Příkaz Odkaz",legend:"Stiskněte ${link}"},{name:" Příkaz Skrýt panel nástrojů",legend:"Stiskněte ${toolbarCollapse}"},{name:"Příkaz pro přístup k předchozímu prostoru zaměření",legend:"Stiskněte ${accessPreviousSpace} pro přístup k nejbližšímu nedosažitelnému prostoru zaměření před stříškou, například: dva přilehlé prvky HR. Pro dosažení vzdálených prostorů zaměření tuto kombinaci kláves opakujte."}, {name:"Příkaz pro přístup k dalšímu prostoru zaměření",legend:"Stiskněte ${accessNextSpace} pro přístup k nejbližšímu nedosažitelnému prostoru zaměření po stříšce, například: dva přilehlé prvky HR. Pro dosažení vzdálených prostorů zaměření tuto kombinaci kláves opakujte."},{name:" Nápověda přístupnosti",legend:"Stiskněte ${a11yHelp}"},{name:"Vložit jako čistý text",legend:"Stiskněte ${pastetext}",legendEdge:"Stiskněte ${pastetext} a pak ${paste}"}]}],tab:"Tabulátor",pause:"Pauza",capslock:"Caps lock", escape:"Escape",pageUp:"Stránka nahoru",pageDown:"Stránka dolů",leftArrow:"Šipka vlevo",upArrow:"Šipka nahoru",rightArrow:"Šipka vpravo",downArrow:"Šipka dolů",insert:"Vložit",leftWindowKey:"Levá klávesa Windows",rightWindowKey:"Pravá klávesa Windows",selectKey:"Vyberte klávesu",numpad0:"Numerická klávesa 0",numpad1:"Numerická klávesa 1",numpad2:"Numerická klávesa 2",numpad3:"Numerická klávesa 3",numpad4:"Numerická klávesa 4",numpad5:"Numerická klávesa 5",numpad6:"Numerická klávesa 6",numpad7:"Numerická klávesa 7", numpad8:"Numerická klávesa 8",numpad9:"Numerická klávesa 9",multiply:"Numerická klávesa násobení",add:"Přidat",subtract:"Numerická klávesa odečítání",decimalPoint:"Desetinná tečka",divide:"Numerická klávesa dělení",f1:"F1",f2:"F2",f3:"F3",f4:"F4",f5:"F5",f6:"F6",f7:"F7",f8:"F8",f9:"F9",f10:"F10",f11:"F11",f12:"F12",numLock:"Num lock",scrollLock:"Scroll lock",semiColon:"Středník",equalSign:"Rovnítko",comma:"Čárka",dash:"Pomlčka",period:"Tečka",forwardSlash:"Lomítko",graveAccent:"Přízvuk",openBracket:"Otevřená hranatá závorka", backSlash:"Obrácené lomítko",closeBracket:"Uzavřená hranatá závorka",singleQuote:"Jednoduchá uvozovka"});
mit
jalcine/website
src/_posts/2016-07-10-jordan-year.markdown
1752
--- layout: post title: 2016 - Jordan Year date: 2016-07-10 04:00:00 PDT excerpt: > This is more of a rant that an actual post. At the same time, maybe this blog is one giant rant. byline: The year of the swish. category: reflection tags: - age - god-damnit --- **The Jordan Year**. The ever-fabled year when .. what happens? Every year I get older, and every time I try to ignore it. It happens. I'm over it. I'm thankful for my parents putting up with me through school and thereafter, for everyone who has helped mold me into the person I am today. And I know I'm not supposed to know (or shouldn't expect to) where I'm headed but I still feel lost. I feel like I'm supposed to know my **objective** by now. Not because of a message passed down by some higher plane, but because lots of people approach me as if I do. I fuck up a lot. A lot of these mistakes I make are so avoidable, I do my best to forget them. Then deja vu occurs. Why can't I accept the fact that I'm not as perfect as I keep letting myself to believe? That I'm not some magician-esque kind of guy? It's the side effects of believing too much into all of the hype people give you. People really can only see an exterior to a person, especially on the Internet. Unless, of course, you begin to bleed and peel like this. You start tearing at the layers of the skin that've been applied to them. You begin to debunk each and every compliment that comes their way. Until you just really begin to stop giving a fuck about what the world "expects" them to do. Until I begin accepting me for who I am. **The problem is, I still don't know who that is**. I'm learning that it's okay not to know. As long as I do my absolute best, I don't think I can do too much wrong.
mit
jddeeds/jddeeds.github.io
node_modules/tinyliquid/lib/context.js
16661
/** * Context Object * * @author Zongmin Lei<[email protected]> */ var utils = require('./utils'); var parser = require('./parser'); var filters = require('./filters'); var vm = require('./vm'); var OPCODE = require('./opcode'); var debug = utils.debug('Context'); var merge = utils.merge; /** * Context * * @param {Object} options * - {Object} filters * - {Object} asyncFilters * - {Object} locals * - {Object} syncLocals * - {Object} asyncLocals * - {Object} blocks * - {Boolean} isLayout default:false * - {Integer} timeout unit:ms, default:120000 * - {Object} parent */ var Context = module.exports = exports = function (options) { options = options || {}; this._locals = {}; this._syncLocals = {}; this._asyncLocals = {}; this._asyncLocals2 = []; this._filters = merge(filters, options.filters); this._asyncFilters = {}; this._cycles = {}; this._buffer = ''; this._forloops = []; this._isInForloop = false; this._tablerowloops = []; this._isInTablerowloop = false; this._includeFileHandler = null; this._position = {line: 0, column: 0}; this._astCache = {}; this._filenameStack = []; this._filterCache = {}; this._blocks = {}; this._isLayout = !!options.isLayout; // default configuration options = merge({ timeout: 120000 }, options); this.options = options; // parent this._parent = options.parent || null; // initialize the configuration var me = this; var set = function (name) { if (options[name] && typeof(options[name]) === 'object') { Object.keys(options[name]).forEach(function (i) { me['_' + name][i] = options[name][i]; }); } }; set('locals'); set('syncLocals'); set('asyncLocals'); set('asyncLocals2'); set('filters'); set('blocks'); if (options.asyncFilters && typeof options.asyncFilters === 'object') { Object.keys(options.asyncFilters).forEach(function (i) { me.setAsyncFilter(i, options.asyncFilters[i]); }); } }; /** * Copy the configuration from other context object * * @param {Object} from * @return {Object} */ Context.prototype.from = function (from) { var me = this; var set = function (name) { if (from[name] && typeof(from[name]) === 'object') { for (var i in from[name]) { if (i in me[name]) continue; me[name][i] = from[name][i]; } } else if (typeof(from[name] === 'function')) { if (!me[name]) { me[name] = from[name]; } } } set('_locals'); set('_syncLocals'); set('_asyncLocals'); set('_asyncLocals2'); set('_filters'); set('_asyncFilters'); set('options'); set('_onErrorHandler'); set('_includeFileHandler'); set('_filterCache'); set('_blocks'); if (Array.isArray(from._filenameStack)) { me._filenameStack = from._filenameStack.slice(); } for (var i in from) { if (i in me) continue; me[i] = from[i]; } me._isInForloop = from._isInForloop; me._forloops = from._forloops.slice(); me._isInTablerowloop = from._isInTablerowloop; me._tablerowloops = from._tablerowloops; me._isLayout = from._isLayout; return this; }; /* constants */ Context.prototype.STATIC_LOCALS = 0; // normal locals Context.prototype.SYNC_LOCALS = 1; // get value from a sync function Context.prototype.ASYNC_LOCALS = 2; // get value from a async function Context.prototype.SYNC_FILTER = 0; // normal filter Context.prototype.ASYNC_FILTER = 1; // async filter /** * Set Timeout * * @param {Integer} ms */ Context.prototype.setTimeout = function (ms) { ms = parseInt(ms, 10); if (ms > 0) this.options.timeout = ms; }; /** * Run AST * * @param {Array} astList * @param {Function} callback */ Context.prototype.run = function (astList, callback) { return vm.run(astList, this, callback); }; /** * Register normal locals * * @param {String} name * @param {Function} val */ Context.prototype.setLocals = function (name, val) { this._locals[name] = val; if (this._parent) { this._parent.setLocals(name, val); } }; /** * Register sync locals * * @param {String} name * @param {Function} val */ Context.prototype.setSyncLocals = function (name, fn) { this._syncLocals[name] = fn; }; /** * Register async locals * * @param {String} name * @param {Function} fn */ Context.prototype.setAsyncLocals = function (name, fn) { if (name instanceof RegExp) { var name2 = name.toString(); // remove the same name for (var i = 0, len = this._asyncLocals2; i < len; i++) { var item = this._asyncLocals2[i]; if (item[0].toString() === name2) { this._asyncLocals2.splice(i, 1); break; } } this._asyncLocals2.push([name, fn]); } else { this._asyncLocals[name] = fn; } }; /** * Register normal filter * * @param {String} name * @param {Function} fn */ Context.prototype.setFilter = function (name, fn) { this._filters[name.trim()] = fn; }; /** * Register async filter * * @param {String} name * @param {Function} fn */ Context.prototype.setAsyncFilter = function (name, fn) { if (fn.enableCache) fn = utils.wrapFilterCache(name, fn); this._asyncFilters[name.trim()] = fn; }; /** * Set layout file * * @param {String} filename */ Context.prototype.setLayout = function (filename) { this._layout = filename; }; /** * Set block * * @param {String} name * @param {String} buf */ Context.prototype.setBlock = function (name, buf) { this._blocks[name] = buf; if (this._parent) { this._parent.setBlock(name, buf); } }; /** * Set block if empty * * @param {String} name * @param {String} buf */ Context.prototype.setBlockIfEmpty = function (name, buf) { if (!(name in this._blocks)) { this._blocks[name] = buf; } }; /** * Get block * * @param {String} name * @return {String} */ Context.prototype.getBlock = function (name) { return this._blocks[name] || null; }; /** * Get locals * * @param {String} name * @return {Array} [type, value, isAllowCache] return null if the locals not found */ Context.prototype.getLocals = function (name) { if (name in this._locals) return [this.STATIC_LOCALS, this._locals[name]]; if (name in this._syncLocals) return [this.SYNC_LOCALS, this._syncLocals[name], true]; if (name in this._asyncLocals) return [this.ASYNC_LOCALS, this._asyncLocals[name], true]; for (var i = 0, len = this._asyncLocals2.length; i < len; i++) { var item = this._asyncLocals2[i]; if (item[0].test(name)) { return [this.ASYNC_LOCALS, item[1], true]; } } return null; }; /** * Fetch Single Locals * * @param {String} name * @param {Function} callback */ Context.prototype.fetchSingleLocals = function (name, callback) { var me = this; var info = me.getLocals(name); if (!info) return callback(null, info); switch (info[0]) { case me.STATIC_LOCALS: callback(null, info[1]); break; case me.SYNC_LOCALS: var v = info[1](name, me); if (info[2]) me.setLocals(name, v); callback(null, v); break; case me.ASYNC_LOCALS: info[1](name, function (err, v) { if (err) return callback(err); if (info[2]) me.setLocals(name, v); callback(null, v); }, me); break; default: callback(me.throwLocalsUndefinedError(name)); } }; /** * Fetch locals * * @param {Array|String} list * @param {Function} callback */ Context.prototype.fetchLocals = function (list, callback) { var me = this; if (Array.isArray(list)) { var values = []; utils.asyncEach(list, function (name, i, done) { me.fetchSingleLocals(name, function (err, val) { if (err) { values[i] = err; } else { values[i] = val; } done(); }); }, callback, null, values); } else { me.fetchSingleLocals(list, callback); } }; /** * Get filter * * @param {String} name * @return {Array} [type, function] return null if the filter not found */ Context.prototype.getFilter = function (name) { name = name.trim(); if (name in this._filters) return [this.SYNC_FILTER, this._filters[name]]; if (name in this._asyncFilters) return [this.ASYNC_FILTER, this._asyncFilters[name]]; return null; }; /** * Call filter * * @param {String} method * @param {Array} args * @param {Function} callback */ Context.prototype.callFilter = function (method, args, callback) { if (arguments.length < 3) { callback = args; args = []; } var info = this.getFilter(method); if (!info) return callback(this.throwFilterUndefinedError(method)); if (info[0] === this.ASYNC_FILTER) { args.push(callback); args.push(this); info[1].apply(null, args); } else { args.push(this); callback(null, info[1].apply(null, args)); } }; /** * Print HTML * * @param {Object} str */ Context.prototype.print = function (str) { this._buffer += (str === null || typeof(str) === 'undefined') ? '' : str; }; /** * Set buffer * * @param {String} buf */ Context.prototype.setBuffer = function (buf) { this._buffer = buf; }; /** * Get buffer * * @return {String} */ Context.prototype.getBuffer = function () { return this._buffer; }; /** * Clear buffer * * @return {String} */ Context.prototype.clearBuffer = function () { var buf = this.getBuffer(); this.setBuffer(''); return buf; }; /** * Set cycle * * @param {String} name * @param {Array} list */ Context.prototype.setCycle = function (name, list) { this._cycles[name] = {index: 0, length: list.length, list: list}; }; /** * Get the index of the cycle * * @param {String} name * @return {Integer} */ Context.prototype.getCycleIndex = function (name) { var cycle = this._cycles[name]; if (cycle) { cycle.index++; if (cycle.index >= cycle.length) cycle.index = 0; return cycle.index; } else { return null; } }; /** * Enter a forloop * * @param {Integer} length * @param {String} itemName */ Context.prototype.forloopEnter = function (length, itemName) { this._forloops.push({ length: length, itemName: itemName }); this._isInForloop = true; }; /** * Set the forloop item value * * @param {Object} item * @param {Integer} index */ Context.prototype.forloopItem = function (item, index) { var loop = this._forloops[this._forloops.length - 1]; loop.item = item; loop.index = index; }; /** * Set the forloop information * * @return {Object} */ Context.prototype.forloopInfo = function () { return this._forloops[this._forloops.length - 1]; }; /** * Exit the current forloop */ Context.prototype.forloopEnd = function () { this._forloops.pop(); if (this._forloops.length < 1) { this._isInForloop = false; } }; /** * Enter a tablerowloop * * @param {Integer} length * @param {String} itemName * @param {Integer} columns */ Context.prototype.tablerowloopEnter = function (length, itemName, columns) { this._tablerowloops.push({ length: length, itemName: itemName, columns: columns }); this._isInTablerowloop = true; }; /** * Set the tablerowloop item value * * @param {Object} item * @param {Integer} index * @param {Integer} colIndex */ Context.prototype.tablerowloopItem = function (item, index, colIndex) { var loop = this._tablerowloops[this._tablerowloops.length - 1]; loop.item = item; loop.index = index; loop.colIndex = colIndex; }; /** * Get the tablerow information * * @return {Object} */ Context.prototype.tablerowloopInfo = function () { return this._tablerowloops[this._tablerowloops.length - 1]; }; /** * Exit the current tablerowloop */ Context.prototype.tablerowloopEnd = function () { this._tablerowloops.pop(); if (this._tablerowloops.length < 1) { this._isInTablerowloop = false; } }; /** * Include a template file * * @param {String} name * @param {Array} localsAst * @param {Array} headerAst * @param {Function} callback */ Context.prototype.include = function (name, localsAst, headerAst, callback) { if (typeof headerAst === 'function') { callback = headerAst; headerAst = null; } var me = this; if (typeof(this._includeFileHandler) === 'function') { this._includeFileHandler(name, function (err, astList) { if (err) return callback(err); // all include files run on new context var c = new Context({parent: me}); c.from(me); function start () { c.run(astList, function (err) { //console.log(err, c.getBuffer(), headerAst); me.print(c.clearBuffer()); callback(err); }); } if (headerAst && headerAst.length > 0) { astList = [me._position.line, me._position.column,OPCODE.LIST, headerAst, astList]; } if (localsAst) { me.run(localsAst, function (err, locals) { if (err) locals = {}; Object.keys(locals).forEach(function (n) { c._locals[n] = locals[n]; }); start(); }); } else { start(); } }); } else { return callback(new Error('please set an include file handler')); } }; /** * Extends layout * * @param {String} name * @param {Function} callback */ Context.prototype.extends = function (name, callback) { if (typeof(this._includeFileHandler) === 'function') { this._includeFileHandler(name, callback); } else { return callback(new Error('please set an include file handler')); } }; /** * Set the include file handler * * @param {Function} fn format: function (name, callback) * callback format: function (err, astList) */ Context.prototype.onInclude = function (fn) { this._includeFileHandler = fn; }; /** * Throw locals undefined error * * @param {String} name * @return {Object} */ Context.prototype.throwLocalsUndefinedError = function (name) { debug('Locals ' + name + ' is undefined'); return null; }; /** * Throw loop item undefined error * * @param {String} name * @return {Object} */ Context.prototype.throwLoopItemUndefinedError = function (name) { debug('Loop item ' + name + ' is undefined'); return null; }; /** * Throw forloop/tablerow locals undefined error * * @param {String} name * @return {Object} */ Context.prototype.throwLoopLocalsUndefinedError = function (name) { debug('Loop locals ' + name + ' is undefined'); return null; }; /** * Throw filter undefined error * * @param {String} name * @return {Object} */ Context.prototype.throwFilterUndefinedError = function (name) { var err = new Error('Filter ' + name + ' is undefined ' + this.getCurrentPosition(true)); err.code = 'UNDEFINED_FILTER'; err = this.wrapCurrentPosition(err); return err; } /** * Throw unknown opcode error * * @param {String} code * @return {Object} */ Context.prototype.throwUnknownOpcodeError = function (code) { var err = new Error('Unknown opcode ' + code + ' ' + this.getCurrentPosition(true)); err.code = 'UNKNOWN_OPCODE'; err = this.wrapCurrentPosition(err); return err; }; /** * Throw unknown tag error * * @param {String} name * @param {String} body * @return {Object} */ Context.prototype.throwUnknownTagError = function (name, body) { var err = new Error('Unknown tag "' + (name + ' ' + body).trim() + '" ' + this.getCurrentPosition(true)); err.code = 'UNKNOWN_TAG'; err = this.wrapCurrentPosition(err); return err; }; /** * Set current position * * @param {Integer} line * @param {Integer} column */ Context.prototype.setCurrentPosition = function (line, column) { this._position.line = line; this._position.column = column; }; /** * Get current position * * @param {Boolean} getString * @return {Object} */ Context.prototype.getCurrentPosition = function (getString) { if (getString) { return 'at line ' + this._position.line + ', column ' + this._position.column; } else { return this._position; } }; /** * Wrap current position on a error object * * @param {Object} err * @return {Object} */ Context.prototype.wrapCurrentPosition = function (err) { err = err || {}; err.line = this._position.line; err.column = this._position.column; return err; }; /** * Push Filename * * @param {String} filename * @return {String} */ Context.prototype.pushFilename = function (filename) { this._filenameStack.push(filename); return filename; }; /** * Pop Filename * * @return {String} */ Context.prototype.popFilename = function () { return this._filenameStack.pop(); }; /** * Get filename * * @return {String} */ Context.prototype.getFilename = function () { return this._filenameStack[this._filenameStack.length - 1]; };
mit
dbrgn/coreutils
tests/cut.rs
1741
#[macro_use] mod common; use common::util::*; static UTIL_NAME: &'static str = "cut"; static INPUT: &'static str = "lists.txt"; #[test] fn test_prefix() { let (at, mut ucmd) = testing(UTIL_NAME); let result = ucmd.args(&["-c", "-10", INPUT]).run(); assert_eq!(result.stdout, at.read("lists_prefix.expected")); } #[test] fn test_char_range() { let (at, mut ucmd) = testing(UTIL_NAME); let result = ucmd.args(&["-c", "4-10", INPUT]).run(); assert_eq!(result.stdout, at.read("lists_char_range.expected")); } #[test] fn test_column_to_end_of_line() { let (at, mut ucmd) = testing(UTIL_NAME); let result = ucmd.args(&["-d", ":", "-f", "5-", INPUT]).run(); assert_eq!(result.stdout, at.read("lists_column_to_end_of_line.expected")); } #[test] fn test_specific_field() { let (at, mut ucmd) = testing(UTIL_NAME); let result = ucmd.args(&["-d", " ", "-f", "3", INPUT]).run(); assert_eq!(result.stdout, at.read("lists_specific_field.expected")); } #[test] fn test_multiple_fields() { let (at, mut ucmd) = testing(UTIL_NAME); let result = ucmd.args(&["-d", ":", "-f", "1,3", INPUT]).run(); assert_eq!(result.stdout, at.read("lists_multiple_fields.expected")); } #[test] fn test_tail() { let (at, mut ucmd) = testing(UTIL_NAME); let result = ucmd.args(&["-d", ":", "--complement", "-f", "1", INPUT]).run(); assert_eq!(result.stdout, at.read("lists_tail.expected")); } #[test] fn test_change_delimiter() { let (at, mut ucmd) = testing(UTIL_NAME); let result = ucmd.args(&["-d", ":", "--complement", "--output-delimiter=#", "-f", "1", INPUT]) .run(); assert_eq!(result.stdout, at.read("lists_change_delimiter.expected")); }
mit
Azure/azure-rest-api-specs
specification/maps/resource-manager/readme.typescript.md
377
## TypeScript These settings apply only when `--typescript` is specified on the command line. Please also specify `--typescript-sdks-folder=<path to root folder of your azure-sdk-for-js clone>`. ``` yaml $(typescript) typescript: azure-arm: true package-name: "@azure/arm-maps" output-folder: "$(typescript-sdks-folder)/sdk/maps/arm-maps" generate-metadata: true ```
mit
Mrs-X/PIVX
src/primitives/block.cpp
1381
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2015-2019 The PIVX developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "primitives/block.h" #include "hash.h" #include "script/standard.h" #include "script/sign.h" #include "tinyformat.h" #include "utilstrencodings.h" #include "util.h" uint256 CBlockHeader::GetHash() const { if (nVersion < 4) return HashQuark(BEGIN(nVersion), END(nNonce)); if (nVersion < 7) return Hash(BEGIN(nVersion), END(nAccumulatorCheckpoint)); return Hash(BEGIN(nVersion), END(nNonce)); } std::string CBlock::ToString() const { std::stringstream s; s << strprintf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%u)\n", GetHash().ToString(), nVersion, hashPrevBlock.ToString(), hashMerkleRoot.ToString(), nTime, nBits, nNonce, vtx.size()); for (unsigned int i = 0; i < vtx.size(); i++) { s << " " << vtx[i].ToString() << "\n"; } return s.str(); } void CBlock::print() const { LogPrintf("%s", ToString()); } bool CBlock::IsZerocoinStake() const { return IsProofOfStake() && vtx[1].HasZerocoinSpendInputs(); }
mit
lpatmo/actionify_the_news
open_connect/accounts/templates/accounts/ban_form.html
479
{% extends "base.html" %} {% block title %}Ban {{ account }}{% endblock %} {% block page_title %} Ban {{ account }} {% endblock page_title %} {% block page_content %} <form method="POST" class="form-horizontal"> {% include "common/horizontal_form_snippet.html" %} <div class="form-actions"> <input type="submit" name="submit" value="Save" class="btn btn-primary"/> </div> </form> {% endblock %}
mit
neshmi/projectmosul
spec/models/artefact_spec.rb
828
require 'rails_helper' describe Artefact do it { should respond_to(:name) } it { should respond_to(:description) } it { should respond_to(:museum_identifier) } it { should have_many(:images).dependent(:destroy) } it { should have_many(:sketchfabs).dependent(:destroy) } describe '.new' do let(:artefact) { Artefact.new } it 'sets an UUID' do expect(artefact.uuid).to_not be_nil end end describe 'artefact has many models' do let(:artefact) { create(:artefact) } let(:sketchfab) { create(:sketchfab, :with_artefact) } it 'should find artefacts without models' do expect(Artefact.sketchfabless).to_not include(sketchfab.artefact) end it 'should find artefacts with models' do expect(Artefact.with_sketchfabs).to include(sketchfab.artefact) end end end
mit
fboxerappdev/Corporate-Web-App---Bootstrap-Wordpress
node_modules/npm-shrinkwrap/node_modules/npm/html/doc/cli/npm-help-search.html
3692
<!doctype html> <html> <title>npm-help-search</title> <meta http-equiv="content-type" value="text/html;utf-8"> <link rel="stylesheet" type="text/css" href="../../static/style.css"> <link rel="canonical" href="https://www.npmjs.org/doc/cli/npm-help-search.html"> <script async=true src="../../static/toc.js"></script> <body> <div id="wrapper"> <h1><a href="../cli/npm-help-search.html">npm-help-search</a></h1> <p>Search npm help documentation</p> <h2 id="synopsis">SYNOPSIS</h2> <pre><code>npm help-search some search terms </code></pre><h2 id="description">DESCRIPTION</h2> <p>This command will search the npm markdown documentation files for the terms provided, and then list the results, sorted by relevance.</p> <p>If only one result is found, then it will show that help topic.</p> <p>If the argument to <code>npm help</code> is not a known help topic, then it will call <code>help-search</code>. It is rarely if ever necessary to call this command directly.</p> <h2 id="configuration">CONFIGURATION</h2> <h3 id="long">long</h3> <ul> <li>Type: Boolean</li> <li>Default false</li> </ul> <p>If true, the &quot;long&quot; flag will cause help-search to output context around where the terms were found in the documentation.</p> <p>If false, then help-search will just list out the help topics found.</p> <h2 id="see-also">SEE ALSO</h2> <ul> <li><a href="../cli/npm.html">npm(1)</a></li> <li><a href="../misc/npm-faq.html">npm-faq(7)</a></li> <li><a href="../cli/npm-help.html">npm-help(1)</a></li> </ul> </div> <table border=0 cellspacing=0 cellpadding=0 id=npmlogo> <tr><td style="width:180px;height:10px;background:rgb(237,127,127)" colspan=18>&nbsp;</td></tr> <tr><td rowspan=4 style="width:10px;height:10px;background:rgb(237,127,127)">&nbsp;</td><td style="width:40px;height:10px;background:#fff" colspan=4>&nbsp;</td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=4>&nbsp;</td><td style="width:40px;height:10px;background:#fff" colspan=4>&nbsp;</td><td rowspan=4 style="width:10px;height:10px;background:rgb(237,127,127)">&nbsp;</td><td colspan=6 style="width:60px;height:10px;background:#fff">&nbsp;</td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=4>&nbsp;</td></tr> <tr><td colspan=2 style="width:20px;height:30px;background:#fff" rowspan=3>&nbsp;</td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=3>&nbsp;</td><td style="width:10px;height:10px;background:#fff" rowspan=3>&nbsp;</td><td style="width:20px;height:10px;background:#fff" rowspan=4 colspan=2>&nbsp;</td><td style="width:10px;height:20px;background:rgb(237,127,127)" rowspan=2>&nbsp;</td><td style="width:10px;height:10px;background:#fff" rowspan=3>&nbsp;</td><td style="width:20px;height:10px;background:#fff" rowspan=3 colspan=2>&nbsp;</td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=3>&nbsp;</td><td style="width:10px;height:10px;background:#fff" rowspan=3>&nbsp;</td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=3>&nbsp;</td></tr> <tr><td style="width:10px;height:10px;background:#fff" rowspan=2>&nbsp;</td></tr> <tr><td style="width:10px;height:10px;background:#fff">&nbsp;</td></tr> <tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6>&nbsp;</td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)">&nbsp;</td></tr> <tr><td colspan=5 style="width:50px;height:10px;background:#fff">&nbsp;</td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4>&nbsp;</td><td style="width:90px;height:10px;background:#fff" colspan=9>&nbsp;</td></tr> </table> <p id="footer">npm-help-search &mdash; [email protected]</p>
mit
IanField90/Coursework
Part 3/SE3AC11/eticket/eticket_uint.py
30
import sys from pycsp import *
mit
landcoin-project/landcoin
src/qt/optionsmodel.cpp
9070
#include "optionsmodel.h" #include "bitcoinunits.h" #include "init.h" #include "walletdb.h" #include "guiutil.h" #include <QSettings> OptionsModel::OptionsModel(QObject *parent) : QAbstractListModel(parent) { Init(); } bool static ApplyProxySettings() { QSettings settings; CService addrProxy(settings.value("addrProxy", "127.0.0.1:9042").toString().toStdString()); int nSocksVersion(settings.value("nSocksVersion", 5).toInt()); if (!settings.value("fUseProxy", false).toBool()) { addrProxy = CService(); nSocksVersion = 0; return false; } if (nSocksVersion && !addrProxy.IsValid()) return false; if (!IsLimited(NET_IPV4)) SetProxy(NET_IPV4, addrProxy, nSocksVersion); if (nSocksVersion > 4) { #ifdef USE_IPV6 if (!IsLimited(NET_IPV6)) SetProxy(NET_IPV6, addrProxy, nSocksVersion); #endif SetNameProxy(addrProxy, nSocksVersion); } return true; } void OptionsModel::Init() { QSettings settings; // These are Qt-only settings: nDisplayUnit = settings.value("nDisplayUnit", BitcoinUnits::LND).toInt(); bDisplayAddresses = settings.value("bDisplayAddresses", false).toBool(); fMinimizeToTray = settings.value("fMinimizeToTray", false).toBool(); fMinimizeOnClose = settings.value("fMinimizeOnClose", false).toBool(); nTransactionFee = settings.value("nTransactionFee").toLongLong(); language = settings.value("language", "").toString(); // These are shared with core Landcoin; we want // command-line options to override the GUI settings: if (settings.contains("fUseUPnP")) SoftSetBoolArg("-upnp", settings.value("fUseUPnP").toBool()); if (settings.contains("addrProxy") && settings.value("fUseProxy").toBool()) SoftSetArg("-proxy", settings.value("addrProxy").toString().toStdString()); if (settings.contains("nSocksVersion") && settings.value("fUseProxy").toBool()) SoftSetArg("-socks", settings.value("nSocksVersion").toString().toStdString()); if (!language.isEmpty()) SoftSetArg("-lang", language.toStdString()); } void OptionsModel::Reset() { QSettings settings; // Remove all entries in this QSettings object settings.clear(); // default setting for OptionsModel::StartAtStartup - disabled if (GUIUtil::GetStartOnSystemStartup()) GUIUtil::SetStartOnSystemStartup(false); // Re-Init to get default values Init(); // Ensure Upgrade() is not running again by setting the bImportFinished flag settings.setValue("bImportFinished", true); } bool OptionsModel::Upgrade() { QSettings settings; if (settings.contains("bImportFinished")) return false; // Already upgraded settings.setValue("bImportFinished", true); // Move settings from old wallet.dat (if any): CWalletDB walletdb("wallet.dat"); QList<QString> intOptions; intOptions << "nDisplayUnit" << "nTransactionFee"; foreach(QString key, intOptions) { int value = 0; if (walletdb.ReadSetting(key.toStdString(), value)) { settings.setValue(key, value); walletdb.EraseSetting(key.toStdString()); } } QList<QString> boolOptions; boolOptions << "bDisplayAddresses" << "fMinimizeToTray" << "fMinimizeOnClose" << "fUseProxy" << "fUseUPnP"; foreach(QString key, boolOptions) { bool value = false; if (walletdb.ReadSetting(key.toStdString(), value)) { settings.setValue(key, value); walletdb.EraseSetting(key.toStdString()); } } try { CAddress addrProxyAddress; if (walletdb.ReadSetting("addrProxy", addrProxyAddress)) { settings.setValue("addrProxy", addrProxyAddress.ToStringIPPort().c_str()); walletdb.EraseSetting("addrProxy"); } } catch (std::ios_base::failure &e) { // 0.6.0rc1 saved this as a CService, which causes failure when parsing as a CAddress CService addrProxy; if (walletdb.ReadSetting("addrProxy", addrProxy)) { settings.setValue("addrProxy", addrProxy.ToStringIPPort().c_str()); walletdb.EraseSetting("addrProxy"); } } ApplyProxySettings(); Init(); return true; } int OptionsModel::rowCount(const QModelIndex & parent) const { return OptionIDRowCount; } QVariant OptionsModel::data(const QModelIndex & index, int role) const { if(role == Qt::EditRole) { QSettings settings; switch(index.row()) { case StartAtStartup: return QVariant(GUIUtil::GetStartOnSystemStartup()); case MinimizeToTray: return QVariant(fMinimizeToTray); case MapPortUPnP: #ifdef USE_UPNP return settings.value("fUseUPnP", GetBoolArg("-upnp", true)); #else return QVariant(false); #endif case MinimizeOnClose: return QVariant(fMinimizeOnClose); case ProxyUse: { proxyType proxy; return QVariant(GetProxy(NET_IPV4, proxy)); } case ProxyIP: { proxyType proxy; if (GetProxy(NET_IPV4, proxy)) return QVariant(QString::fromStdString(proxy.first.ToStringIP())); else return QVariant(QString::fromStdString("127.0.0.1")); } case ProxyPort: { proxyType proxy; if (GetProxy(NET_IPV4, proxy)) return QVariant(proxy.first.GetPort()); else return QVariant(9042); } case ProxySocksVersion: { proxyType proxy; if (GetProxy(NET_IPV4, proxy)) return QVariant(proxy.second); else return QVariant(5); } case Fee: return QVariant(nTransactionFee); case DisplayUnit: return QVariant(nDisplayUnit); case DisplayAddresses: return QVariant(bDisplayAddresses); case Language: return settings.value("language", ""); default: return QVariant(); } } return QVariant(); } bool OptionsModel::setData(const QModelIndex & index, const QVariant & value, int role) { bool successful = true; /* set to false on parse error */ if(role == Qt::EditRole) { QSettings settings; switch(index.row()) { case StartAtStartup: successful = GUIUtil::SetStartOnSystemStartup(value.toBool()); break; case MinimizeToTray: fMinimizeToTray = value.toBool(); settings.setValue("fMinimizeToTray", fMinimizeToTray); break; case MapPortUPnP: settings.setValue("fUseUPnP", value.toBool()); MapPort(value.toBool()); break; case MinimizeOnClose: fMinimizeOnClose = value.toBool(); settings.setValue("fMinimizeOnClose", fMinimizeOnClose); break; case ProxyUse: settings.setValue("fUseProxy", value.toBool()); successful = ApplyProxySettings(); break; case ProxyIP: { proxyType proxy; proxy.first = CService("127.0.0.1", 9042); GetProxy(NET_IPV4, proxy); CNetAddr addr(value.toString().toStdString()); proxy.first.SetIP(addr); settings.setValue("addrProxy", proxy.first.ToStringIPPort().c_str()); successful = ApplyProxySettings(); } break; case ProxyPort: { proxyType proxy; proxy.first = CService("127.0.0.1", 9042); GetProxy(NET_IPV4, proxy); proxy.first.SetPort(value.toInt()); settings.setValue("addrProxy", proxy.first.ToStringIPPort().c_str()); successful = ApplyProxySettings(); } break; case ProxySocksVersion: { proxyType proxy; proxy.second = 5; GetProxy(NET_IPV4, proxy); proxy.second = value.toInt(); settings.setValue("nSocksVersion", proxy.second); successful = ApplyProxySettings(); } break; case Fee: nTransactionFee = value.toLongLong(); settings.setValue("nTransactionFee", nTransactionFee); break; case DisplayUnit: nDisplayUnit = value.toInt(); settings.setValue("nDisplayUnit", nDisplayUnit); emit displayUnitChanged(nDisplayUnit); break; case DisplayAddresses: bDisplayAddresses = value.toBool(); settings.setValue("bDisplayAddresses", bDisplayAddresses); break; case Language: settings.setValue("language", value); break; default: break; } } emit dataChanged(index, index); return successful; } qint64 OptionsModel::getTransactionFee() { return nTransactionFee; }
mit
uktrade/data-hub-fe-beta2
src/apps/contacts/controllers/__test__/details.test.js
3180
const { assign } = require('lodash') const proxyquire = require('proxyquire') const contact = require('../../../../../test/unit/data/contacts/contact.json') describe('Contact controller', () => { beforeEach(() => { this.getContactStub = sinon.stub().resolves(contact) this.getDitCompanyStub = sinon.stub().resolves(contact.company) this.transformerStub = sinon.stub() this.contactController = proxyquire('../details', { '../repos': { getContact: this.getContactStub, }, '../../companies/repos': { getDitCompany: this.getDitCompanyStub, }, '../transformers': { transformContactToView: this.transformerStub, }, }) this.req = { session: { token: 'abcd', }, params: { contactId: '12651151-2149-465e-871b-ac45bc568a62', }, } this.res = { locals: {}, breadcrumb: sinon.stub().returnsThis(), render: sinon.spy(), } this.next = sinon.spy() }) describe('#getCommon', () => { it('should get the contact ID', async () => { await this.contactController.getCommon(this.req, this.res, this.next) expect(this.res.locals.id).to.equal(this.req.params.contactId) expect(this.next).to.have.been.calledOnce }) it('should get the reason for archive options', async () => { await this.contactController.getCommon(this.req, this.res, this.next) const expected = [ 'Left the company', 'Does not want to be contacted', 'Changed role/responsibility', ] expect(this.res.locals.reasonForArchiveOptions).to.deep.equal(expected) expect(this.next).to.have.been.calledOnce }) it('should get the reason for archive options prefix', async () => { await this.contactController.getCommon(this.req, this.res, this.next) expect(this.res.locals.reasonForArchiveOptionsPrefix).to.equal( 'This contact has:' ) expect(this.next).to.have.been.calledOnce }) it('should handle an error', async () => { const error = Error('error') this.getContactStub.rejects(error) await this.contactController.getCommon(this.req, this.res, this.next) expect(this.next).to.be.calledWith( sinon.match({ message: error.message }) ) expect(this.next).to.have.been.calledOnce }) }) describe('#getDetails', () => { context('when called with a contact', () => { beforeEach(() => { this.res.locals = assign({}, this.res.locals, { contact }) this.res.locals.features = assign({}, this.res.locals.features) this.contactController.getDetails(this.req, this.res, this.next) }) it('should return the contact details', () => { const options = this.res.render.firstCall.args[1] expect(options).to.have.property('contactDetails') }) it('should call the details transformer', () => { expect(this.transformerStub).to.be.calledWith(contact) }) it('should render the contact details view', () => { expect(this.res.render).to.be.calledWith('contacts/views/details') }) }) }) })
mit
selvasingh/azure-sdk-for-java
sdk/apimanagement/mgmt-v2019_01_01/src/main/java/com/microsoft/azure/management/apimanagement/v2019_01_01/implementation/SubscriptionsImpl.java
3940
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * jkl */ package com.microsoft.azure.management.apimanagement.v2019_01_01.implementation; import com.microsoft.azure.arm.model.implementation.WrapperImpl; import com.microsoft.azure.management.apimanagement.v2019_01_01.Subscriptions; import rx.Completable; import rx.functions.Func1; import rx.Observable; import com.microsoft.azure.Page; import com.microsoft.azure.management.apimanagement.v2019_01_01.ProductSubscriptionContract; class SubscriptionsImpl extends WrapperImpl<SubscriptionsInner> implements Subscriptions { private final ApiManagementManager manager; SubscriptionsImpl(ApiManagementManager manager) { super(manager.inner().subscriptions()); this.manager = manager; } public ApiManagementManager manager() { return this.manager; } @Override public SubscriptionContractImpl define(String name) { return wrapModel(name); } private SubscriptionContractImpl wrapModel(SubscriptionContractInner inner) { return new SubscriptionContractImpl(inner, manager()); } private SubscriptionContractImpl wrapModel(String name) { return new SubscriptionContractImpl(name, this.manager()); } @Override public Observable<ProductSubscriptionContract> listAsync(final String resourceGroupName, final String serviceName) { SubscriptionsInner client = this.inner(); return client.listAsync(resourceGroupName, serviceName) .flatMapIterable(new Func1<Page<SubscriptionContractInner>, Iterable<SubscriptionContractInner>>() { @Override public Iterable<SubscriptionContractInner> call(Page<SubscriptionContractInner> page) { return page.items(); } }) .map(new Func1<SubscriptionContractInner, ProductSubscriptionContract>() { @Override public ProductSubscriptionContract call(SubscriptionContractInner inner) { return new ProductSubscriptionContractImpl(inner, manager()); } }); } @Override public Completable getEntityTagAsync(String resourceGroupName, String serviceName, String sid) { SubscriptionsInner client = this.inner(); return client.getEntityTagAsync(resourceGroupName, serviceName, sid).toCompletable(); } @Override public Observable<ProductSubscriptionContract> getAsync(String resourceGroupName, String serviceName, String sid) { SubscriptionsInner client = this.inner(); return client.getAsync(resourceGroupName, serviceName, sid) .map(new Func1<SubscriptionContractInner, ProductSubscriptionContract>() { @Override public ProductSubscriptionContract call(SubscriptionContractInner inner) { return new ProductSubscriptionContractImpl(inner, manager()); } }); } @Override public Completable deleteAsync(String resourceGroupName, String serviceName, String sid, String ifMatch) { SubscriptionsInner client = this.inner(); return client.deleteAsync(resourceGroupName, serviceName, sid, ifMatch).toCompletable(); } @Override public Completable regeneratePrimaryKeyAsync(String resourceGroupName, String serviceName, String sid) { SubscriptionsInner client = this.inner(); return client.regeneratePrimaryKeyAsync(resourceGroupName, serviceName, sid).toCompletable(); } @Override public Completable regenerateSecondaryKeyAsync(String resourceGroupName, String serviceName, String sid) { SubscriptionsInner client = this.inner(); return client.regenerateSecondaryKeyAsync(resourceGroupName, serviceName, sid).toCompletable(); } }
mit
kyl191/nginx-pagespeed
download_sources.py
1266
#!/usr/bin/python3 import os import re import requests def download_file(url): out_file = os.path.join("SOURCES", url.rsplit("/")[-1]) r = requests.get(url, stream=True) print("Downloading {} to {}".format(url, out_file)) with open(out_file, "wb") as out: for chunk in r.iter_content(chunk_size=None): if chunk: out.write(chunk) spec = "{}.spec".format(os.environ['CIRCLE_PROJECT_REPONAME']) with open(spec, 'r') as f: for line in f.readlines(): if line.startswith("Version:"): NGINX_VERSION = re.search("([0-9.])+", line).group() if line.startswith("%define nps_version"): NPS_VERSION = re.search("([0-9.])+", line).group() ngx_files = [ "https://nginx.org/download/nginx-{NGINX_VERSION}.tar.gz", "https://nginx.org/download/nginx-{NGINX_VERSION}.tar.gz.asc" ] for f in ngx_files: download_file(f.format(NGINX_VERSION=NGINX_VERSION)) nps_files = [ "https://github.com/pagespeed/ngx_pagespeed/archive/v{NPS_VERSION}-beta.zip", "https://dl.google.com/dl/page-speed/psol/{NPS_VERSION}-x64.tar.gz", "https://dl.google.com/dl/page-speed/psol/{NPS_VERSION}-ia32.tar.gz" ] for f in nps_files: download_file(f.format(NPS_VERSION=NPS_VERSION))
mit
farooqsheikhpk/Aspose.BarCode-for-Cloud
Examples/PHP/managing-recognition/cloud-storage/recognize-specified-count-of-barcodes.php
2244
<?php /** * Include the SDK by using the autoloader from Composer. */ require __DIR__ . '/../../vendor/autoload.php'; /** * Include the configuration values. * * Ensure that you have edited the configuration.php file * to include your application keys. */ $config = require __DIR__ . '/../../configuration.php'; $apiKey = $config ['apiKey']; $appSid = $config ['appSid']; $out_folder = $config ['outFolder']; $data_folder = '../../data/'; // resouece data folder /** * The namespaces provided by the SDK. */ use Aspose\Barcode\BarcodeApi; use Aspose\Storage\StorageApi; // ExStart:1 \Aspose\Storage\AsposeApp::$apiKey = $apiKey; \Aspose\Storage\AsposeApp::$appSID = $appSid; \Aspose\Barcode\AsposeApp::$apiKey = $apiKey; \Aspose\Barcode\AsposeApp::$appSID = $appSid; ; // Instantiate Aspose Storage Cloud API SDK $storageApi = new StorageApi (); // Instantiate Aspose BarCode Cloud API SDK $barcodeApi = new BarcodeApi (); // Set input file name $name = "sample-barcode.jpeg"; // The barcode type. // If this parameter is empty, autodetection of all supported types is used. $type = ""; // Set mode for checksum validation during recognition $checksumValidation = "On"; // Set if FNC symbol stripping should be performed. $stripFnc = "True"; // Set recognition of rotated barcode $rotationAngle = ""; // Set exact number of barcodes to recognize $barcodesCount = "1"; // Set recognition of barcode inside specified Rectangle region $rectX = 0; $rectY = 0; $rectWidth = 0; $rectHeight = 0; // Set 3rd party cloud storage server (if any) $storage = ""; // Set folder location at cloud storage $folder = ""; // Set local file (if any) $file = null; try { // upload file to aspose cloud storage $result = $storageApi->PutCreate ( $name, "", $storage, $data_folder . $name ); // invoke Aspose.BarCode Cloud SDK API to read barcode $response = $barcodeApi->GetBarcodeRecognize ( $name, $type, $checksumValidation, $stripFnc, $rotationAngle, $barcodesCount, $rectX, $rectY, $rectWidth, $rectHeight, $storage, $folder ); if ($response != null && $response->Status = "OK") { print_r ( $response->Barcode ); } } catch ( \Aspose\Barcode\ApiException $exp ) { echo "Exception:" . $exp->getMessage (); } //ExEnd:1
mit
giulidb/ticket_dapp
node_modules/ethereumjs-vm/lib/hooked.js
5536
const inherits = require('util').inherits const async = require('async') const ethUtil = require('ethereumjs-util') const Account = require('ethereumjs-account') const FakeMerklePatriciaTree = require('fake-merkle-patricia-tree') const VM = require('./index.js') const ZERO_BUFFER = new Buffer('0000000000000000000000000000000000000000000000000000000000000000', 'hex') module.exports = createHookedVm module.exports.fromWeb3Provider = fromWeb3Provider /* This is a helper for creating a vm with modified state lookups this should be made obsolete by a better public API for StateManager ```js var vm = createHookedVm({ enableHomestead: true, }, { fetchAccountBalance: function(addressHex, cb){ ... }, fetchAccountNonce: function(addressHex, cb){ ... }, fetchAccountCode: function(addressHex, cb){ ... }, fetchAccountStorage: function(addressHex, keyHex, cb){ ... }, }) vm.runTx(txParams, cb) ``` */ function createHookedVm (opts, hooks) { var codeStore = new FallbackAsyncStore(hooks.fetchAccountCode.bind(hooks)) var vm = new VM(opts) vm.stateManager._lookupStorageTrie = createAccountStorageTrie vm.stateManager.cache._lookupAccount = loadAccount vm.stateManager.getContractCode = codeStore.get.bind(codeStore) vm.stateManager.setContractCode = codeStore.set.bind(codeStore) return vm function createAccountStorageTrie (address, cb) { var addressHex = ethUtil.addHexPrefix(address.toString('hex')) var storageTrie = new FallbackStorageTrie({ fetchStorage: function (key, cb) { hooks.fetchAccountStorage(addressHex, ethUtil.addHexPrefix(key), cb) } }) cb(null, storageTrie) } function loadAccount (address, cb) { var addressHex = ethUtil.addHexPrefix(address.toString('hex')) async.parallel({ nonce: hooks.fetchAccountNonce.bind(hooks, addressHex), balance: hooks.fetchAccountBalance.bind(hooks, addressHex) }, function (err, results) { if (err) return cb(err) results._exists = results.nonce !== '0x0' || results.balance !== '0x0' || results._code !== '0x' // console.log('fetch account results:', results) var account = new Account(results) // not used but needs to be anything but the default (ethUtil.SHA3_NULL) // code lookups are handled by `codeStore` account.codeHash = ZERO_BUFFER.slice() cb(null, account) }) } } /* Additional helper for creating a vm with rpc state lookups blockNumber to query against is fixed */ function fromWeb3Provider (provider, blockNumber, opts) { return createHookedVm(opts, { fetchAccountBalance: createRpcFunction(provider, 'eth_getBalance', blockNumber), fetchAccountNonce: createRpcFunction(provider, 'eth_getTransactionCount', blockNumber), fetchAccountCode: createRpcFunction(provider, 'eth_getCode', blockNumber), fetchAccountStorage: createRpcFunction(provider, 'eth_getStorageAt', blockNumber) }) function createRpcFunction (provider, method, blockNumber) { return function sendRpcRequest () { // prepare arguments var args = [].slice.call(arguments) var cb = args.pop() args.push(blockNumber) // send rpc payload provider.sendAsync({ id: 1, jsonrpc: '2.0', method: method, params: args }, function (err, res) { if (err) return cb(err) cb(null, res.result) }) } } } // // FallbackStorageTrie // // is a FakeMerklePatriciaTree that will let lookups // fallback to the fetchStorage fn. writes shadow the underlying fetchStorage value. // doesn't bother with a stateRoot // inherits(FallbackStorageTrie, FakeMerklePatriciaTree) function FallbackStorageTrie (opts) { const self = this FakeMerklePatriciaTree.call(self) self._fetchStorage = opts.fetchStorage } FallbackStorageTrie.prototype.get = function (key, cb) { const self = this var _super = FakeMerklePatriciaTree.prototype.get.bind(self) _super(key, function (err, value) { if (err) return cb(err) if (value) return cb(null, value) // if value not in tree, try network var keyHex = key.toString('hex') self._fetchStorage(keyHex, function (err, rawValue) { if (err) return cb(err) var value = ethUtil.toBuffer(rawValue) value = ethUtil.unpad(value) var encodedValue = ethUtil.rlp.encode(value) cb(null, encodedValue) }) }) } // // FallbackAsyncStore // // is an async key-value store that will let lookups // fallback to the network. puts are not sent. // function FallbackAsyncStore (fetchFn) { // console.log('FallbackAsyncStore - new') const self = this self.fetch = fetchFn self.cache = {} } FallbackAsyncStore.prototype.get = function (address, cb) { // console.log('FallbackAsyncStore - get', arguments) const self = this var addressHex = '0x' + address.toString('hex') var code = self.cache[addressHex] if (code !== undefined) { cb(null, code) } else { // console.log('FallbackAsyncStore - fetch init') self.fetch(addressHex, function (err, value) { // console.log('FallbackAsyncStore - fetch return', arguments) if (err) return cb(err) value = ethUtil.toBuffer(value) self.cache[addressHex] = value cb(null, value) }) } } FallbackAsyncStore.prototype.set = function (address, code, cb) { // console.log('FallbackAsyncStore - set', arguments) const self = this var addressHex = '0x' + address.toString('hex') self.cache[addressHex] = code cb() }
mit
Anjeyster/Dimento
vendor/mockery/mockery/library/Mockery/Generator/StringManipulationGenerator.php
2895
<?php /** * Mockery * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://github.com/padraic/mockery/blob/master/LICENSE * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to [email protected] so we can send you a copy immediately. * * @category Mockery * @package Mockery * @copyright Copyright (c) 2010 Pádraic Brady (http://blog.astrumfutura.com) * @license http://github.com/padraic/mockery/blob/master/LICENSE New BSD License */ namespace Mockery\Generator; use Mockery\Generator\StringManipulation\Pass\Pass; use Mockery\Generator\StringManipulation\Pass\RemoveDestructorPass; use Mockery\Generator\StringManipulation\Pass\CallTypeHintPass; use Mockery\Generator\StringManipulation\Pass\MagicMethodTypeHintsPass; use Mockery\Generator\StringManipulation\Pass\ClassNamePass; use Mockery\Generator\StringManipulation\Pass\ClassPass; use Mockery\Generator\StringManipulation\Pass\TraitPass; use Mockery\Generator\StringManipulation\Pass\InstanceMockPass; use Mockery\Generator\StringManipulation\Pass\InterfacePass; use Mockery\Generator\StringManipulation\Pass\MethodDefinitionPass; use Mockery\Generator\StringManipulation\Pass\RemoveBuiltinMethodsThatAreFinalPass; use Mockery\Generator\StringManipulation\Pass\RemoveUnserializeForInternalSerializableClassesPass; class StringManipulationGenerator implements Generator { protected $passes = array(); /** * Creates a new StringManipulationGenerator with the default passes * * @return StringManipulationGenerator */ public static function withDefaultPasses() { return new static([ new CallTypeHintPass(), new MagicMethodTypeHintsPass(), new ClassPass(), new TraitPass(), new ClassNamePass(), new InstanceMockPass(), new InterfacePass(), new MethodDefinitionPass(), new RemoveUnserializeForInternalSerializableClassesPass(), new RemoveBuiltinMethodsThatAreFinalPass(), new RemoveDestructorPass(), ]); } public function __construct(array $passes) { $this->passes = $passes; } public function generate(MockConfiguration $config) { $code = file_get_contents(__DIR__ . '/../Mock.php'); $className = $config->getName() ?: $config->generateName(); $namedConfig = $config->rename($className); foreach ($this->passes as $pass) { $code = $pass->apply($code, $namedConfig); } return new MockDefinition($namedConfig, $code); } public function addPass(Pass $pass) { $this->passes[] = $pass; } }
mit
CS171/CS171.github.io
2016_Spring/lectures/lecture-d3/d3_selectors.html
639
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>D3 Selectors</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js" charset="utf-8"></script> </head> <body> <p>Here is a paragraph.</p> <p id="second">And one more.</p> <p class="other">Third one.</p> <p class="other">Fourth one.</p> <script> // selecting by tag var p = d3.select("p"); p.style("color", "steelblue"); // selecting by ID p = d3.select("#second"); p.style("color", "teal"); // selecting by class p = d3.select(".other"); p.style("color", "darkorchid"); </script> </body> </html>
mit
wczekalski/Distraction-Free-Xcode-plugin
Archived/v1/WCDistractionFreeXcodePlugin/Headers/PlugIns/IDESourceEditor/DVTSourceLanguageRelatedIdentifierScannerService-Protocol.h
337
// // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard. // #import "NSObject.h" @protocol DVTSourceLanguageRelatedIdentifierScannerService <NSObject> - (void)tokenizableRangesWithRange:(struct _NSRange)arg1 completionBlock:(void (^)(NSArray *))arg2; @end
mit
tmcgee/cmv-wab-widgets
wab/2.15/widgets/SmartEditor/XYCoordinates.html
1694
<div class="esriCTPopupContainer" data-dojo-attach-point="coordinatesPopup"> <div class="esriCTFieldDropdownContainer"> <div class="esriCTSelectTitle" title="${nls.coordinatesSelectTitle}">${nls.coordinatesSelectTitle}</div> <div class="esriCTFieldInput" style="width: 100%;"> <select aria-label="${nls.coordinatesSelectTitle}" class="esriCTControlWidth" data-dojo-attach-point="coordinatesDropDown" data-dojo-type="dijit/form/Select"> <option value="Map Spatial Reference">${nls.mapSpecialReferenceDropdownOption}</option> <option value="Latitude/Longitude">${nls.latLongDropdownOption}</option> </select> </div> </div> <div class="esriCTControlWidth"> <div class="esriCTSelectTitle" data-dojo-attach-point="xAttributeTextBoxLabel">${nls.xAttributeTextBoxLabel}</div> <div> <div aria-label="${nls.xAttributeTextBoxLabel}" class="esriCTControlWidth" data-dojo-attach-point="xAttributeTextBox" data-dojo-type="dijit/form/NumberTextBox" data-dojo-props="intermediateChanges:true" trim="true"> </div> </div> </div> <div style="padding-bottom: 5px;"> <div for="yAttributeTextBox" class="esriCTSelectTitle" data-dojo-attach-point="yAttributeTextBoxLabel">${nls.yAttributeTextBoxLabel}</div> <div class="esriCTControlWidth"> <div aria-label="${nls.yAttributeTextBoxLabel}" class="esriCTControlWidth" data-dojo-attach-point="yAttributeTextBox" data-dojo-type="dijit/form/NumberTextBox" data-dojo-props="intermediateChanges:true" trim="true"> </div> </div> </div> </div>
mit
sarawuthza/lollipop.css
index.html
9531
<!DOCTYPE HTML> <html lang="en"> <head> <meta charset="UTF-8"> <meta name=viewport content="width=device-width, initial-scale=1"> <meta name="description" content="Android lollipop animations in CSS" /> <title>lollipop.css - Android lollipop animations in CSS</title> <link href='http://fonts.googleapis.com/css?family=Open+Sans:400,800' rel='stylesheet' type='text/css'> <style> *, *:after, *:before { box-sizing: border-box; } html, body { height: 100%; } body { color: #555; font-family: 'open sans', sans-serif; margin: 0; background: #4794AB; } .float--right { float: right; } .float--left { float: left; } .text--center { text-align: center; } .caps { text-transform: uppercase; } a { color: inherit; text-decoration: none; } a:hover { /*text-decoration: underline;*/ color: #F47322; } .icon-btn { color: #AAA; } .sidebar { position: fixed; top: 0; bottom: 0; left: 0; width: 400px; background: white; text-align: center; overflow: hidden; box-shadow: 2px 0 40px 2px rgba(0,0,0,0.1); } .sidebar:after { content: ''; display: block; width: 100%; height: 500px; position: absolute; bottom: -130px; right: -110px; background: url('data:image/svg+xml;utf8,<svg fill="#f4f4f4" height="24" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg"><path d="M0 0h24v24H0z" fill="none"/><path d="M5 16c0 3.87 3.13 7 7 7s7-3.13 7-7v-4H5v4zM16.12 4.37l2.1-2.1-.82-.83-2.3 2.31C14.16 3.28 13.12 3 12 3s-2.16.28-3.09.75L6.6 1.44l-.82.83 2.1 2.1C6.14 5.64 5 7.68 5 10v1h14v-1c0-2.32-1.14-4.36-2.88-5.63zM9 9c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1zm6 0c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1z"/></svg>') no-repeat; background-size: 500px; background-position: right bottom; transform: rotate(10deg); z-index: -3; } .outer-wrap { padding: 32px; margin-left: 400px; position: relative; min-height: 100%; overflow: hidden; transition: 0.25s ease 0.1s; } .sidebar-btn { text-transform: uppercase; letter-spacing: 2px; color: #FFF; display: inline-block; background-color: rgba(0,0,0,0.1); padding: 10px 16px; } header { margin-bottom: 32px; text-align: center; padding: 32px 0; } .sidebar__footer { position: absolute; bottom: 0; width: 100%; padding: 32px; color: #AAA; font-size: 0.8em; letter-spacing: 4px; word-spacing: 4px; text-transform: uppercase; text-align: center; } .main-title { text-transform: uppercase; font-size: 20px; text-decoration: none; letter-spacing: 6px; color: inherit; font-weight: bold; } .drawer { position: fixed; top: 0; bottom: 0; right: 0; width: 400px; background: #444; transform: translateX(100%); transition: 0.2s ease-out; } .doc > a { color: #aaa; } .is-sidebar-open .drawer { transform: translateX(0); } .is-sidebar-open .outer-wrap { opacity: 0.6; transform: translateX(-200px); pointer-event: none; } .share-box { margin-bottom: 32px; } .tweet-btn { display: inline-block; background: #55ACEE; color: white; fill: white; border-radius: 5px; padding: 5px 10px; transition: 0.25s ease; box-shadow: 0 3px 12px rgba(0,0,0,0.1); } .tweet-btn:hover { padding: 5px 20px; background: white; } .tweet-btn:hover svg { color: #55ACEE; fill: #55ACEE; } .lollipop-icon { display: inline-block; position: relative; border-radius: 50%; background: #F06292 radial-gradient(farthest-corner at 40% 40% , rgba(255, 255, 255, 0.07) 0%, rgba(255, 255, 255, 0.07) 30%, transparent 30%); color: white; width: 6em; height: 6em; margin: 1em 0 2em; line-height: 6em; font-size: 3em; box-shadow: 0 13px 24px -7px rgba(0, 0, 0, 0.3); cursor: pointer; } .lollipop-icon:after { content: ''; display: block; width: 30px; height: 999px; position: absolute; top: 50%; left: calc(50% - 15px); background: linear-gradient(90deg, #FFF 0%, #DDD 100%); z-index: -2; box-shadow: 0 0 10px 2px rgba(0, 0, 0, 0.1); } .lollipop-icon:before { content: ''; display: block; width: 40px; height: 60px; position: absolute; top: 100%; left: calc(50% - 15px - 12px); margin-top: -3px; background: linear-gradient(to left bottom, #dadada 0px, #dadada 25px, transparent 25px); z-index: -1; } .item-list { transition: 0.3s ease; } .list-item { display: block; text-transform: uppercase; text-decoration: none; padding: 32px; border: 1px solid #4794AB; margin-bottom: 32px; color: white; letter-spacing: 2px; transition: 0.25s ease 80ms; } .list-item__title { font-size: 1.4em; font-weight: 100; } .list-item__date { color: inherit; opacity: 0.5; font-size: 0.7em; } .list-item:hover { background: rgba(0,0,0,0.1); border-color: transparent; color: white; letter-spacing: 4px; /*transform: scale(1.3) translate(100px, 0);*/ } .item-container { position: absolute; left: 0; top: 0; right: 0; bottom: 0; padding: 32px; padding-top: 48px; background: #40869A; text-align: center; transform: translateX(100%); transition: 0.35s ease 0.1s; } .item-container__close-btn { width: 100%; } .item-state .item-container { transform: translateX(0); visibility: visible; } [data-dummy-pen] { display: none; } .item-container iframe { opacity: 0; animation: fadeIn 0.3s ease forwards 1s; } @-webkit-keyframes fadeIn { from { opacity: 0; transform: scale(0.8); } to { opacity: 1; transform: scale(1); } } @media (max-width: 950px) { .sidebar { position: relative; width: auto; z-index: 1; overflow: hidden; } .lollipop-icon { margin: 1em 0; } .share-box { margin-bottom: 16px; } .sidebar__footer { position: static; padding: 16px; } .outer-wrap { margin-left: 0; min-height: auto; } /*.item-container { position: fixed; z-index: 2; }*/ } </style> </head> <body> <div class="sidebar"> <div class="lollipop-icon">lollipop.css</div> <h1 class="caps" style="padding:0 16px;">Android lollipop animations <br>in CSS</h1> <footer class="sidebar__footer"> <div class="share-box"> <a class="tweet-btn" target="_blank" href="https://twitter.com/share?url=https%3A%2F%2Fkushagragour.in/lab/lollipop.css%2F&text=lollipop.css%20-%20Android%20lollipop%20animations%20in%20CSS%20via%20@chinchang457"> <svg style="width:24px;height:24px" viewBox="0 0 24 24"> <path d="M22.46,6C21.69,6.35 20.86,6.58 20,6.69C20.88,6.16 21.56,5.32 21.88,4.31C21.05,4.81 20.13,5.16 19.16,5.36C18.37,4.5 17.26,4 16,4C13.65,4 11.73,5.92 11.73,8.29C11.73,8.63 11.77,8.96 11.84,9.27C8.28,9.09 5.11,7.38 3,4.79C2.63,5.42 2.42,6.16 2.42,6.94C2.42,8.43 3.17,9.75 4.33,10.5C3.62,10.5 2.96,10.3 2.38,10C2.38,10 2.38,10 2.38,10.03C2.38,12.11 3.86,13.85 5.82,14.24C5.46,14.34 5.08,14.39 4.69,14.39C4.42,14.39 4.15,14.36 3.89,14.31C4.43,16 6,17.26 7.89,17.29C6.43,18.45 4.58,19.13 2.56,19.13C2.22,19.13 1.88,19.11 1.54,19.07C3.44,20.29 5.7,21 8.12,21C16,21 20.33,14.46 20.33,8.79C20.33,8.6 20.33,8.42 20.32,8.23C21.16,7.63 21.88,6.87 22.46,6Z" /> </svg> </a> </div> Created by <a target="blank" href="https://twitter.com/intent/follow?original_referer=https%3A%2F%2Fdev.twitter.com%2Fweb%2Ffollow-button&screen_name=chinchang457&tw_p=followbutton">Kushagra Gour</a> </footer> </div> <div class="outer-wrap"> <div class="item-list"> <a class="list-item" onclick="ui.openItem(event)" href="chinchang/pen/yNyaEx/"> <div class="list-item__title">Main menu</div> <span class="list-item__date">25 July 2015</span> </a> <a class="list-item" onclick="ui.openItem(event)" href="chinchang/pen/yNyaEx/"> <div class="list-item__title">Dialpad</div> <span class="list-item__date">5 Dec 2015</span> </a> <div class="list-item"> More coming soon... </div> </div> <a href="" class="sidebar-btn">Submit an animation</a> <div class="item-container" id="js-item-container"> <a href="javascript:void(0)" class="sidebar-btn item-container__close-btn" onclick="ui.closeItem()">Close</a> <div></div> </div> <p id="js-embed-pen" data-dummy-pen data-height="700" data-theme-id="0" data-slug-hash="yNyaEx" data-default-tab="result" data-user="chinchang">See the Pen <a href='http://codepen.io/chinchang/pen/yNyaEx/'>yNyaEx</a> by Kushagra Gour (<a href='http://codepen.io/chinchang'>@chinchang</a>) on <a href='http://codepen.io'>CodePen</a>.</p> </div> <script src="script.js"></script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-19798102-1']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> </body> </html>
mit
eliancruz29/Xamarin_university
MobileCerti/[XAM150]/xam150-ex3-start/BookClient/BookClient/Data/BookManager.cs
2399
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Net.Http; using System.Text; using System.Threading.Tasks; namespace BookClient.Data { public class BookManager { const string Url = "http://xam150.azurewebsites.net/api/books/"; private string authorizationKey; private async Task<HttpClient> GetClient() { HttpClient client = new HttpClient(); if (string.IsNullOrEmpty(authorizationKey)) { authorizationKey = await client.GetStringAsync(Url + "login"); authorizationKey = JsonConvert.DeserializeObject<string>(authorizationKey); } client.DefaultRequestHeaders.Add("Authorization", authorizationKey); client.DefaultRequestHeaders.Add("Accept", "application/json"); return client; } public async Task<IEnumerable<Book>> GetAllAsync() { HttpClient client = await GetClient(); string result = await client.GetStringAsync(Url); return JsonConvert.DeserializeObject<IEnumerable<Book>>(result); } public async Task<Book> Add(string title, string author, string genre) { Book book = new Book() { Title = title, Authors = new List<string>(new[] { author }), ISBN = string.Empty, Genre = genre, PublishDate = DateTime.Now.Date, }; HttpClient client = await GetClient(); var response = await client.PostAsync(Url, new StringContent( JsonConvert.SerializeObject(book), Encoding.UTF8, "application/json")); return JsonConvert.DeserializeObject<Book>( await response.Content.ReadAsStringAsync()); } public async Task Update(Book book) { HttpClient client = await GetClient(); await client.PutAsync(Url + "/" + book.ISBN, new StringContent( JsonConvert.SerializeObject(book), Encoding.UTF8, "application/json")); } public async Task Delete(string isbn) { HttpClient client = await GetClient(); await client.DeleteAsync(Url + isbn); } } }
mit
govmeeting/govmeeting
Utilities/DevelopRetrieval/ParseSplitSample.cs
1250
using HtmlAgilityPack; using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; #pragma warning disable IDE0051 namespace GM.Utilities.DevelopRetrieval { class ParseSplitSample { private string[] ParseHtmlSplitTables(string urlLink) { string[] result = new string[] { }; HtmlDocument htmlDoc = new HtmlWeb().Load(urlLink); HtmlNodeCollection tableNodes = htmlDoc.DocumentNode.SelectNodes("//table"); if (tableNodes != null) { result = Array.ConvertAll<HtmlNode, string>(tableNodes.ToArray(), n => n.OuterHtml); } return result; } DataTable ToDataTable(List<List<KeyValuePair<string, string>>> list) { DataTable result = new DataTable(); if (list.Count == 0) return result; result.Columns.AddRange( list.First().Select(r => new DataColumn(r.Value)).ToArray() ); list = list.Skip(1).ToArray().ToList(); list.ForEach(r => result.Rows.Add(r.Select(c => c.Value).Cast<object>().ToArray())); return result; } } }
mit
mharkus/Sia
crypto/signatures_test.go
5005
package crypto import ( "bytes" "testing" "github.com/NebulousLabs/Sia/encoding" "github.com/NebulousLabs/fastrand" ) // TestUnitSignatureEncoding creates and encodes a public key, and verifies // that it decodes correctly, does the same with a signature. func TestUnitSignatureEncoding(t *testing.T) { // Create a dummy key pair. var sk SecretKey sk[0] = 4 sk[32] = 5 pk := sk.PublicKey() // Marshal and unmarshal the public key. marshalledPK := encoding.Marshal(pk) var unmarshalledPK PublicKey err := encoding.Unmarshal(marshalledPK, &unmarshalledPK) if err != nil { t.Fatal(err) } // Test the public keys for equality. if pk != unmarshalledPK { t.Error("pubkey not the same after marshalling and unmarshalling") } // Create a signature using the secret key. var signedData Hash fastrand.Read(signedData[:]) sig := SignHash(signedData, sk) // Marshal and unmarshal the signature. marshalledSig := encoding.Marshal(sig) var unmarshalledSig Signature err = encoding.Unmarshal(marshalledSig, &unmarshalledSig) if err != nil { t.Fatal(err) } // Test signatures for equality. if sig != unmarshalledSig { t.Error("signature not same after marshalling and unmarshalling") } } // TestUnitSigning creates a bunch of keypairs and signs random data with each of // them. func TestUnitSigning(t *testing.T) { if testing.Short() { t.SkipNow() } // Try a bunch of signatures because at one point there was a library that // worked around 98% of the time. Tests would usually pass, but 200 // iterations would normally cause a failure. iterations := 200 for i := 0; i < iterations; i++ { // Create dummy key pair. sk, pk := GenerateKeyPair() // Generate and sign the data. var randData Hash fastrand.Read(randData[:]) sig := SignHash(randData, sk) // Verify the signature. err := VerifyHash(randData, pk, sig) if err != nil { t.Fatal(err) } // Attempt to verify after the data has been altered. randData[0]++ err = VerifyHash(randData, pk, sig) if err != ErrInvalidSignature { t.Fatal(err) } // Restore the data and make sure the signature is valid again. randData[0]-- err = VerifyHash(randData, pk, sig) if err != nil { t.Fatal(err) } // Attempt to verify after the signature has been altered. sig[0]++ err = VerifyHash(randData, pk, sig) if err != ErrInvalidSignature { t.Fatal(err) } } } // TestIntegrationSigKeyGenerate is an integration test checking that // GenerateKeyPair and GenerateKeyPairDeterminisitc accurately create keys. func TestIntegrationSigKeyGeneration(t *testing.T) { if testing.Short() { t.SkipNow() } message := HashBytes([]byte{'m', 's', 'g'}) // Create a random key and use it. randSecKey, randPubKey := GenerateKeyPair() sig := SignHash(message, randSecKey) err := VerifyHash(message, randPubKey, sig) if err != nil { t.Error(err) } // Corrupt the signature sig[0]++ err = VerifyHash(message, randPubKey, sig) if err == nil { t.Error("corruption failed") } // Create a deterministic key and use it. var detEntropy [EntropySize]byte detEntropy[0] = 35 detSecKey, detPubKey := GenerateKeyPairDeterministic(detEntropy) sig = SignHash(message, detSecKey) err = VerifyHash(message, detPubKey, sig) if err != nil { t.Error(err) } // Corrupt the signature sig[0]++ err = VerifyHash(message, detPubKey, sig) if err == nil { t.Error("corruption failed") } } // TestReadWriteSignedObject tests the ReadSignObject and WriteSignedObject // functions, which are inverses of each other. func TestReadWriteSignedObject(t *testing.T) { sk, pk := GenerateKeyPair() // Write signed object into buffer. b := new(bytes.Buffer) err := WriteSignedObject(b, "foo", sk) if err != nil { t.Fatal(err) } // Keep a copy of b's bytes. buf := b.Bytes() // Read and verify object. var read string err = ReadSignedObject(b, &read, 11, pk) if err != nil { t.Fatal(err) } if read != "foo" { t.Fatal("encode/decode mismatch: expected 'foo', got", []byte(read)) } // Check that maxlen is being respected. b = bytes.NewBuffer(buf) // reset b err = ReadSignedObject(b, &read, 10, pk) if err == nil || err.Error() != "length 11 exceeds maxLen of 10" { t.Fatal("expected length error, got", err) } // Disrupt the decoding to get coverage on the failure branch. err = ReadSignedObject(b, &read, 11, pk) if err == nil || err.Error() != "could not decode type crypto.Signature: unexpected EOF" { t.Fatal(err) } // Try with an invalid signature. buf[0]++ // alter the first byte of the signature, invalidating it. b = bytes.NewBuffer(buf) // reset b err = ReadSignedObject(b, &read, 11, pk) if err != ErrInvalidSignature { t.Fatal(err) } } // TestUnitPublicKey tests the PublicKey method func TestUnitPublicKey(t *testing.T) { for i := 0; i < 1000; i++ { sk, pk := GenerateKeyPair() if sk.PublicKey() != pk { t.Error("PublicKey does not match actual public key:", pk, sk.PublicKey()) } } }
mit
AnteWall/DodskrokGame
bower_components/flexboxgrid/src/index.html
26857
<!DOCTYPE HTML> <html> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Flexbox Grid</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> <!-- build:include:dist ../css/index.min.css --> <!-- /build --> </style> </head> <body class="layout"> <div class="page js-page"> <header class="hero"> <div class="row center-xs"> <h1 class="hero-headline">Flexbox Grid</h1> </div> <div class="row center-xs"> <p class="hero-copy">A grid system based on the <a href="http://caniuse.com/#search=flexbox"><code class="inline-anchor">flex</code></a> display property.</p> </div> <div class="row center-xs"> <a class="button invisible-xs visible-md" href="https://github.com/kristoferjoseph/flexboxgrid/archive/v6.1.1.zip">Download</a> <a class="button" href="https://github.com/kristoferjoseph/flexboxgrid">Github</a> </div> </header> <div class="wrap container-fluid"> <a name="responsive"></a> <section class="page-section"> <h2>Responsive</h2> <p>Responsive modifiers enable specifying different column sizes, offsets, alignment and distribution at xs, sm, md &amp; lg viewport widths.</p> <div class="row"> <div class="col-xs-12 col-sm-3 col-md-2 col-lg-1"> <div class="box-row"></div> </div> <div class="col-xs-6 col-sm-6 col-md-8 col-lg-10"> <div class="box-row"></div> </div> <div class="col-xs-6 col-sm-3 col-md-2 col-lg-1"> <div class="box-row"></div> </div> </div> <div class="row"> <div class="col-xs-12 col-sm-3 col-md-2 col-lg-1"> <div class="box-row"></div> </div> <div class="col-xs-12 col-sm-9 col-md-10 col-lg-11"> <div class="box-row"></div> </div> </div> <div class="row"> <div class="col-xs-10 col-sm-6 col-md-8 col-lg-10"> <div class="box-row"></div> </div> <div class="col-xs-2 col-sm-6 col-md-4 col-lg-2"> <div class="box-row"></div> </div> </div> <pre><code>&lt;div class="row"> &lt;div class="col-xs-12 col-sm-8 col-md-6 col-lg-4"> &lt;div class="box">Responsive&lt;/div> &lt;/div> &lt;/div></code></pre> </section> <a name="fluid"></a> <section class="page-section"> <br> <h2>Fluid</h2> <p>Percent based widths allow fluid resizing of columns and rows.</p> <div class="row"> <div class="col-xs-12"> <div class="box-row"></div> </div> </div> <div class="row"> <div class="col-xs-1"> <div class="box-row"></div> </div> <div class="col-xs-11"> <div class="box-row"></div> </div> </div> <div class="row"> <div class="col-xs-2"> <div class="box-row"></div> </div> <div class="col-xs-10"> <div class="box-row"></div> </div> </div> <div class="row"> <div class="col-xs-3"> <div class="box-row"></div> </div> <div class="col-xs-9"> <div class="box-row"></div> </div> </div> <div class="row"> <div class="col-xs-4"> <div class="box-row"></div> </div> <div class="col-xs-8"> <div class="box-row"></div> </div> </div> <div class="row"> <div class="col-xs-5"> <div class="box-row"></div> </div> <div class="col-xs-7"> <div class="box-row"></div> </div> </div> <div class="row"> <div class="col-xs-6"> <div class="box-row"></div> </div> <div class="col-xs-6"> <div class="box-row"></div> </div> </div> <pre><code>.col-xs-6 { flex-basis: 50%; }</code></pre> </section> <a name="syntax"></a> <section class="page-section"> <h2>Simple Syntax</h2> <p>All you need to remember is row, column, content.</p> <pre><code>&lt;div class="row"> &lt;div class="col-xs-12"> &lt;div class="box">12&lt;/div> &lt;/div> &lt;/div></code></pre> </section> <a name="offsets"></a> <section class="page-section"> <h2>Offsets</h2> <p>Offset a column</p> <div class="row"> <div class="col-xs-offset-11 col-xs-1"> <div class="box-row"></div> </div> </div> <div class="row"> <div class="col-xs-offset-10 col-xs-2"> <div class="box-row"></div> </div> </div> <div class="row"> <div class="col-xs-offset-9 col-xs-3"> <div class="box-row"></div> </div> </div> <div class="row"> <div class="col-xs-offset-8 col-xs-4"> <div class="box-row"></div> </div> </div> <div class="row"> <div class="col-xs-offset-7 col-xs-5"> <div class="box-row"></div> </div> </div> <div class="row"> <div class="col-xs-offset-6 col-xs-6"> <div class="box-row"></div> </div> </div> <div class="row"> <div class="col-xs-offset-5 col-xs-7"> <div class="box-row"></div> </div> </div> <div class="row"> <div class="col-xs-offset-4 col-xs-8"> <div class="box-row"></div> </div> </div> <div class="row"> <div class="col-xs-offset-3 col-xs-9"> <div class="box-row"></div> </div> </div> <div class="row"> <div class="col-xs-offset-2 col-xs-10"> <div class="box-row"></div> </div> </div> <div class="row"> <div class="col-xs-offset-1 col-xs-11"> <div class="box-row"></div> </div> </div> <pre><code>&lt;div class="row"> &lt;div class="col-xs-offset-3 col-xs-9"> &lt;div class="box">offset&lt;/div> &lt;/div> &lt;/div></code></pre> </section> <a name="auto"></a> <section class="page-section"> <h2>Auto Width</h2> <p>Add any number of auto sizing columns to a row. Let the grid figure it out.</p> <div class="row"> <div class="col-xs"> <div class="box-row"></div> </div> <div class="col-xs"> <div class="box-row"></div> </div> </div> <div class="row"> <div class="col-xs"> <div class="box-row"></div> </div> <div class="col-xs"> <div class="box-row"></div> </div> <div class="col-xs"> <div class="box-row"></div> </div> </div> <pre><code>&lt;div class="row"> &lt;div class="col-xs"> &lt;div class="box">auto&lt;/div> &lt;/div> &lt;/div></code></pre> </section> <a name="nested"></a> <section class="page-section"> <h2>Nested Grids</h2> <p>Nest grids inside grids inside grids.</p> <div class="row"> <div class="col-xs-7"> <div class="box box-container"> <div class="row"> <div class="col-xs-9"> <div class="box-first box-container"> <div class="row"> <div class="col-xs-4"> <div class="box-nested"></div> </div> <div class="col-xs-8"> <div class="box-nested"></div> </div> </div> </div> </div> <div class="col-xs-3"> <div class="box-first box-container"> <div class="row"> <div class="col-xs"> <div class="box-nested"></div> </div> </div> </div> </div> </div> </div> </div> <div class="col-xs-5"> <div class="box box-container"> <div class="row"> <div class="col-xs-12"> <div class="box-first box-container"> <div class="row"> <div class="col-xs-6"> <div class="box-nested"></div> </div> <div class="col-xs-6"> <div class="box-nested"></div> </div> </div> </div> </div> </div> </div> </div> </div> <pre><code>&lt;div class="row"> &lt;div class="col-xs"> &lt;div class="box">auto&lt;/div> &lt;div class="row"> &lt;div class="col-xs"> &lt;div class="box">auto&lt;/div> &lt;/div> &lt;/div> &lt;/div> &lt;/div> &lt;/div></code></pre> </section> <a name="alignment"></a> <section class="page-section"> <h2>Alignment</h2> <p>Add classes to align elements to the start or end of a row as well as the top, bottom, or center of a column</p> <h3><code>.start-*</code></h3> <div class="row"> <div class="col-xs-12"> <div class="box box-container"> <div class="row start-xs"> <div class="col-xs-6"> <div class="box-nested"></div> </div> </div> </div> </div> </div>*default alignment <pre><code>&lt;div class="row start-xs"> &lt;div class="col-xs-6"> &lt;div class="box"> start &lt;/div> &lt;/div> &lt;/div> </code></pre> <h3><code>.center-*</code></h3> <div class="row"> <div class="col-xs-12"> <div class="box box-container"> <div class="row center-xs"> <div class="col-xs-6"> <div class="box-nested"></div> </div> </div> </div> </div> </div> <pre><code>&lt;div class="row center-xs"> &lt;div class="col-xs-6"> &lt;div class="box"> start &lt;/div> &lt;/div> &lt;/div> </code></pre> <h3><code>.end-*</code></h3> <div class="row"> <div class="col-xs-12"> <div class="box box-container"> <div class="row end-xs"> <div class="col-xs-6"> <div class="box-nested"></div> </div> </div> </div> </div> </div> <pre><code>&lt;div class="row end-xs"> &lt;div class="col-xs-6"> &lt;div class="box"> end &lt;/div> &lt;/div> &lt;/div> </code></pre> <p>Here is an example of using the modifiers in conjunction to acheive different alignment at different viewport sizes. </p> <div class="row"> <div class="col-xs-12"> <div class="box box-container"> <div class="row center-xs end-sm start-lg"> <div class="col-xs-6"> <div class="box-nested"></div> </div> </div> </div> </div> </div>*Resize the browser window to see the alignment change. <pre><code>&lt;div class="row center-xs end-sm start-lg"> &lt;div class="col-xs-6"> &lt;div class="box"> All together now &lt;/div> &lt;/div> &lt;/div> </code></pre> <h3><code>.top-*</code></h3> <div class="row top-xs"> <div class="col-xs-6"> <div class="box-large"></div> </div> <div class="col-xs-6"> <div class="box"></div> </div> </div>*default alignment <pre><code>&lt;div class="row top-xs"> &lt;div class="col-xs-6"> &lt;div class="box"> top &lt;/div> &lt;/div> &lt;/div> </code></pre> <h3><code>.middle-*</code></h3> <div class="row middle-xs"> <div class="col-xs-6"> <div class="box-large"></div> </div> <div class="col-xs-6"> <div class="box"></div> </div> </div> <pre><code>&lt;div class="row middle-xs"> &lt;div class="col-xs-6"> &lt;div class="box"> center &lt;/div> &lt;/div> &lt;/div> </code></pre> <h3><code>.bottom-*</code></h3> <div class="row bottom-xs"> <div class="col-xs-6"> <div class="box-large"></div> </div> <div class="col-xs-6"> <div class="box"></div> </div> </div> <pre><code>&lt;div class="row bottom-xs"> &lt;div class="col-xs-6"> &lt;div class="box"> bottom &lt;/div> &lt;/div> &lt;/div> </code></pre> </section> <a name="distribution"></a> <section class="page-section"> <h2>Distribution</h2> <p>Add classes to distribute the contents of a row or column.</p> <h3><code>.around-*</code></h3> <div class="row"> <div class="col-xs-12"> <div class="box box-container"> <div class="row around-xs"> <div class="col-xs-2"> <div class="box-nested"></div> </div> <div class="col-xs-2"> <div class="box-nested"></div> </div> <div class="col-xs-2"> <div class="box-nested"></div> </div> </div> </div> </div> </div> <pre><code>&lt;div class="row around-xs"> &lt;div class="col-xs-2"> &lt;div class="box"> around &lt;/div> &lt;/div> &lt;div class="col-xs-2"> &lt;div class="box"> around &lt;/div> &lt;/div> &lt;div class="col-xs-2"> &lt;div class="box"> around &lt;/div> &lt;/div> &lt;/div> </code></pre> <h3><code>.between-*</code></h3> <div class="row"> <div class="col-xs-12"> <div class="box box-container"> <div class="row between-xs"> <div class="col-xs-2"> <div class="box-nested"></div> </div> <div class="col-xs-2"> <div class="box-nested"></div> </div> <div class="col-xs-2"> <div class="box-nested"></div> </div> </div> </div> </div> </div> <pre><code>&lt;div class="row between-xs"> &lt;div class="col-xs-2"> &lt;div class="box"> between &lt;/div> &lt;/div> &lt;div class="col-xs-2"> &lt;div class="box"> between &lt;/div> &lt;/div> &lt;div class="col-xs-2"> &lt;div class="box"> between &lt;/div> &lt;/div> &lt;/div> </code></pre> </section> <a name="reordering"></a> <section class="page-section"> <h2>Reordering</h2> <p>Add classes to reorder columns.</p> <h3><code>.first-*</code></h3> <div class="row"> <div class="col-xs-12"> <div class="box box-container"> <div class="row"> <div class="col-xs-2"> <div class="box-first">1</div> </div> <div class="col-xs-2"> <div class="box-first">2</div> </div> <div class="col-xs-2"> <div class="box-first">3</div> </div> <div class="col-xs-2"> <div class="box-first">4</div> </div> <div class="col-xs-2"> <div class="box-first">5</div> </div> <div class="col-xs-2 first-xs"> <div class="box-nested">6</div> </div> </div> </div> </div> </div> <pre><code>&lt;div class="row"> &lt;div class="col-xs-2"> &lt;div class="box"> 1 &lt;/div> &lt;/div> &lt;div class="col-xs-2"> &lt;div class="box"> 2 &lt;/div> &lt;/div> &lt;div class="col-xs-2 first-xs"> &lt;div class="box"> 3 &lt;/div> &lt;/div> &lt;/div> </code></pre> <h3><code>.last-*</code></h3> <div class="row"> <div class="col-xs-12"> <div class="box box-container"> <div class="row"> <div class="col-xs-2 last-xs"> <div class="box-nested">1</div> </div> <div class="col-xs-2"> <div class="box-first">2</div> </div> <div class="col-xs-2"> <div class="box-first">3</div> </div> <div class="col-xs-2"> <div class="box-first">4</div> </div> <div class="col-xs-2"> <div class="box-first">5</div> </div> <div class="col-xs-2"> <div class="box-first">6</div> </div> </div> </div> </div> </div> <pre><code>&lt;div class="row"> &lt;div class="col-xs-2 last-xs"> &lt;div class="box"> 1 &lt;/div> &lt;/div> &lt;div class="col-xs-2"> &lt;div class="box"> 2 &lt;/div> &lt;/div> &lt;div class="col-xs-2"> &lt;div class="box"> 3 &lt;/div> &lt;/div> &lt;/div> </code></pre> </section> <a name="reversing"></a> <section class="page-section"> <h2>Reversing</h2> <h3><code>.reverse</code></h3> <div class="row"> <div class="col-xs-12"> <div class="box box-container"> <div class="row reverse"> <div class="col-xs-2"> <div class="box-nested">1</div> </div> <div class="col-xs-2"> <div class="box-nested">2</div> </div> <div class="col-xs-2"> <div class="box-nested">3</div> </div> <div class="col-xs-2"> <div class="box-nested">4</div> </div> <div class="col-xs-2"> <div class="box-nested">5</div> </div> <div class="col-xs-2"> <div class="box-nested">6</div> </div> </div> </div> </div> </div> <pre><code>&lt;div class="row reverse"> &lt;div class="col-xs-2"> &lt;div class="box"> 1 &lt;/div> &lt;/div> &lt;div class="col-xs-2"> &lt;div class="box"> 2 &lt;/div> &lt;/div> &lt;div class="col-xs-2"> &lt;div class="box"> 3 &lt;/div> &lt;/div> &lt;/div> </code></pre> </section> <footer class="page-footer"> <div class="row"> <div class="col-xs start"> <a class="tag" href="http://twitter.com/dam"> @dam ♡s you </a> </div> <div class="col-xs end"> <a class="link-top" href="#top">⇪ back to top</a> </div> </div> </footer> </div> </div> <script> (function() { document.addEventListener('DOMContentLoaded', function(e) { var code = document.createElement('script'); code.src = 'js/index.js'; var script = document.getElementsByTagName('script')[0]; script.parentNode.insertBefore(code, script); }); }()); </script> <script src="//localhost:35729/livereload.js"></script> </body> </html>
mit
FloRest/jobhunter
mobile/views/signViews/signup.html
648
<div class="col-sm-6 col-sm-offset-3"> <form class="form-horizontal" role="form" name="signupForm" ng-controller="SignUpController" novalidate> <md-text-float class="full-width" label="Name" ng-model="credentials.name" type="text"></md-text-float> <md-text-float class="full-width" label="E-mail" ng-model="credentials.email" type="email"></md-text-float> <md-text-float class="full-width" label="Password" ng-model="credentials.password" type="password"></md-text-float> <md-button aria-label="signup" class="md-button-colored md-primary nav-button" ng-click="signup(credentials)"> SignUp </md-button> </form> </div>
mit
dee-bee/decisionz
decisionz/lib/JointJS/www/demos/erd.js
1130
title('Entity-relationship diagram.'); description('Make your database structure visible.'); dimension(800, 250); var erd = Joint.dia.erd; Joint.paper("world", 800, 250); var e1 = erd.Entity.create({ rect: { x: 220, y: 70, width: 100, height: 60 }, label: "Entity" }); var e2 = erd.Entity.create({ rect: { x: 520, y: 70, width: 100, height: 60 }, label: "Weak Entity", weak: true }); var r1 = erd.Relationship.create({ rect: { x: 400, y: 72, width: 55, height: 55 }, label: "Relationship" }); var a1 = erd.Attribute.create({ ellipse: { x: 90, y: 30, rx: 50, ry: 20 }, label: "primary", primaryKey: true }); var a2 = erd.Attribute.create({ ellipse: { x: 90, y: 80, rx: 50, ry: 20 }, label: "multivalued", multivalued: true }); var a3 = erd.Attribute.create({ ellipse: { x: 90, y: 130, rx: 50, ry: 20 }, label: "derived", derived: true }); var a4 = erd.Attribute.create({ ellipse: { x: 90, y: 180, rx: 50, ry: 20 }, label: "normal" }); a1.joint(e1, erd.arrow); a2.joint(e1, erd.arrow); a3.joint(e1, erd.arrow); a4.joint(e1, erd.arrow); e1.joint(r1, erd.toMany); r1.joint(e2, erd.oneTo);
mit
EspritEnLigne/test
app/cache/dev/annotations/Esprit-RubriqueBundle-Entity-RubriqueStage.cache.php
345
<?php return unserialize('a:2:{i:0;O:26:"Doctrine\\ORM\\Mapping\\Table":5:{s:4:"name";s:17:"ESP_RubriqueStage";s:6:"schema";N;s:7:"indexes";N;s:17:"uniqueConstraints";N;s:7:"options";a:0:{}}i:1;O:27:"Doctrine\\ORM\\Mapping\\Entity":2:{s:15:"repositoryClass";s:52:"Esprit\\RubriqueBundle\\Entity\\RubriqueStageRepository";s:8:"readOnly";b:0;}}');
mit
mojmir-svoboda/BlackBoxTT
3rd_party/asio/src/tests/unit/generic/seq_packet_protocol.cpp
6415
// // generic/seq_packet_protocol.cpp // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2015 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // Disable autolinking for unit tests. #if !defined(BOOST_ALL_NO_LIB) #define BOOST_ALL_NO_LIB 1 #endif // !defined(BOOST_ALL_NO_LIB) // Test that header file is self-contained. #include "asio/generic/seq_packet_protocol.hpp" #include <cstring> #include "asio/io_context.hpp" #include "../unit_test.hpp" #if defined(__cplusplus_cli) || defined(__cplusplus_winrt) # define generic cpp_generic #endif //------------------------------------------------------------------------------ // generic_seq_packet_protocol_socket_compile test // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // The following test checks that all public member functions on the class // generic::seq_packet_socket::socket compile and link correctly. Runtime // failures are ignored. namespace generic_seq_packet_protocol_socket_compile { void connect_handler(const asio::error_code&) { } void send_handler(const asio::error_code&, std::size_t) { } void receive_handler(const asio::error_code&, std::size_t) { } void test() { using namespace asio; namespace generic = asio::generic; typedef generic::seq_packet_protocol spp; const int af_inet = ASIO_OS_DEF(AF_INET); const int sock_seqpacket = ASIO_OS_DEF(SOCK_SEQPACKET); try { io_context ioc; char mutable_char_buffer[128] = ""; const char const_char_buffer[128] = ""; const socket_base::message_flags in_flags = 0; socket_base::message_flags out_flags = 0; socket_base::send_buffer_size socket_option; socket_base::bytes_readable io_control_command; asio::error_code ec; // basic_seq_packet_socket constructors. spp::socket socket1(ioc); spp::socket socket2(ioc, spp(af_inet, 0)); spp::socket socket3(ioc, spp::endpoint()); #if !defined(ASIO_WINDOWS_RUNTIME) spp::socket::native_handle_type native_socket1 = ::socket(af_inet, sock_seqpacket, 0); spp::socket socket4(ioc, spp(af_inet, 0), native_socket1); #endif // !defined(ASIO_WINDOWS_RUNTIME) #if defined(ASIO_HAS_MOVE) spp::socket socket5(std::move(socket4)); #endif // defined(ASIO_HAS_MOVE) // basic_seq_packet_socket operators. #if defined(ASIO_HAS_MOVE) socket1 = spp::socket(ioc); socket1 = std::move(socket2); #endif // defined(ASIO_HAS_MOVE) // basic_io_object functions. spp::socket::executor_type ex = socket1.get_executor(); (void)ex; #if !defined(ASIO_NO_DEPRECATED) io_context& ioc_ref = socket1.get_io_context(); (void)ioc_ref; io_context& ioc_ref2 = socket1.get_io_service(); (void)ioc_ref2; #endif // !defined(ASIO_NO_DEPRECATED) // basic_socket functions. spp::socket::lowest_layer_type& lowest_layer = socket1.lowest_layer(); (void)lowest_layer; socket1.open(spp(af_inet, 0)); socket1.open(spp(af_inet, 0), ec); #if !defined(ASIO_WINDOWS_RUNTIME) spp::socket::native_handle_type native_socket2 = ::socket(af_inet, sock_seqpacket, 0); socket1.assign(spp(af_inet, 0), native_socket2); spp::socket::native_handle_type native_socket3 = ::socket(af_inet, sock_seqpacket, 0); socket1.assign(spp(af_inet, 0), native_socket3, ec); #endif // !defined(ASIO_WINDOWS_RUNTIME) bool is_open = socket1.is_open(); (void)is_open; socket1.close(); socket1.close(ec); spp::socket::native_handle_type native_socket4 = socket1.native_handle(); (void)native_socket4; socket1.cancel(); socket1.cancel(ec); bool at_mark1 = socket1.at_mark(); (void)at_mark1; bool at_mark2 = socket1.at_mark(ec); (void)at_mark2; std::size_t available1 = socket1.available(); (void)available1; std::size_t available2 = socket1.available(ec); (void)available2; socket1.bind(spp::endpoint()); socket1.bind(spp::endpoint(), ec); socket1.connect(spp::endpoint()); socket1.connect(spp::endpoint(), ec); socket1.async_connect(spp::endpoint(), connect_handler); socket1.set_option(socket_option); socket1.set_option(socket_option, ec); socket1.get_option(socket_option); socket1.get_option(socket_option, ec); socket1.io_control(io_control_command); socket1.io_control(io_control_command, ec); spp::endpoint endpoint1 = socket1.local_endpoint(); spp::endpoint endpoint2 = socket1.local_endpoint(ec); spp::endpoint endpoint3 = socket1.remote_endpoint(); spp::endpoint endpoint4 = socket1.remote_endpoint(ec); socket1.shutdown(socket_base::shutdown_both); socket1.shutdown(socket_base::shutdown_both, ec); // basic_seq_packet_socket functions. socket1.send(buffer(mutable_char_buffer), in_flags); socket1.send(buffer(const_char_buffer), in_flags); socket1.send(null_buffers(), in_flags); socket1.send(buffer(mutable_char_buffer), in_flags, ec); socket1.send(buffer(const_char_buffer), in_flags, ec); socket1.send(null_buffers(), in_flags, ec); socket1.async_send(buffer(mutable_char_buffer), in_flags, send_handler); socket1.async_send(buffer(const_char_buffer), in_flags, send_handler); socket1.async_send(null_buffers(), in_flags, send_handler); socket1.receive(buffer(mutable_char_buffer), out_flags); socket1.receive(null_buffers(), out_flags); socket1.receive(buffer(mutable_char_buffer), in_flags, out_flags); socket1.receive(null_buffers(), in_flags, out_flags); socket1.receive(buffer(mutable_char_buffer), in_flags, out_flags, ec); socket1.receive(null_buffers(), in_flags, out_flags, ec); socket1.async_receive(buffer(mutable_char_buffer), out_flags, receive_handler); socket1.async_receive(null_buffers(), out_flags, receive_handler); socket1.async_receive(buffer(mutable_char_buffer), in_flags, out_flags, receive_handler); socket1.async_receive(null_buffers(), in_flags, out_flags, receive_handler); } catch (std::exception&) { } } } // namespace generic_seq_packet_protocol_socket_compile //------------------------------------------------------------------------------ ASIO_TEST_SUITE ( "generic/seq_packet_protocol", ASIO_TEST_CASE(generic_seq_packet_protocol_socket_compile::test) )
mit
facebook/fresco
docs/javadoc/reference/com/facebook/imagepipeline/request/RepeatedPostprocessorRunner.html
23013
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="description" content="Javadoc API documentation for Fresco." /> <link rel="shortcut icon" type="image/x-icon" href="../../../../favicon.ico" /> <title> RepeatedPostprocessorRunner - Fresco API | Fresco </title> <link href="../../../../../assets/doclava-developer-docs.css" rel="stylesheet" type="text/css" /> <link href="../../../../../assets/customizations.css" rel="stylesheet" type="text/css" /> <script src="../../../../../assets/search_autocomplete.js" type="text/javascript"></script> <script src="../../../../../assets/jquery-resizable.min.js" type="text/javascript"></script> <script src="../../../../../assets/doclava-developer-docs.js" type="text/javascript"></script> <script src="../../../../../assets/prettify.js" type="text/javascript"></script> <script type="text/javascript"> setToRoot("../../../../", "../../../../../assets/"); </script> <script src="../../../../../assets/doclava-developer-reference.js" type="text/javascript"></script> <script src="../../../../../assets/navtree_data.js" type="text/javascript"></script> <script src="../../../../../assets/customizations.js" type="text/javascript"></script> <noscript> <style type="text/css"> html,body{overflow:auto;} #body-content{position:relative; top:0;} #doc-content{overflow:visible;border-left:3px solid #666;} #side-nav{padding:0;} #side-nav .toggle-list ul {display:block;} #resize-packages-nav{border-bottom:3px solid #666;} </style> </noscript> </head> <body class=""> <div id="header"> <div id="headerLeft"> <span id="masthead-title"><a href="../../../../packages.html">Fresco</a></span> </div> <div id="headerRight"> <div id="search" > <div id="searchForm"> <form accept-charset="utf-8" class="gsc-search-box" onsubmit="return submit_search()"> <table class="gsc-search-box" cellpadding="0" cellspacing="0"><tbody> <tr> <td class="gsc-input"> <input id="search_autocomplete" class="gsc-input" type="text" size="33" autocomplete="off" title="search developer docs" name="q" value="search developer docs" onFocus="search_focus_changed(this, true)" onBlur="search_focus_changed(this, false)" onkeydown="return search_changed(event, true, '../../../../')" onkeyup="return search_changed(event, false, '../../../../')" /> <div id="search_filtered_div" class="no-display"> <table id="search_filtered" cellspacing=0> </table> </div> </td> <!-- <td class="gsc-search-button"> <input type="submit" value="Search" title="search" id="search-button" class="gsc-search-button" /> </td> <td class="gsc-clear-button"> <div title="clear results" class="gsc-clear-button">&nbsp;</div> </td> --> </tr></tbody> </table> </form> </div><!-- searchForm --> </div><!-- search --> </div> </div><!-- header --> <div class="g-section g-tpl-240" id="body-content"> <div class="g-unit g-first side-nav-resizable" id="side-nav"> <div id="swapper"> <div id="nav-panels"> <div id="resize-packages-nav"> <div id="packages-nav"> <div id="index-links"> <a href="../../../../packages.html" >Packages</a> | <a href="../../../../classes.html" >Classes</a> </div> <ul> <li class="api apilevel-"> <a href="../../../../com/facebook/animated/gif/package-summary.html">com.facebook.animated.gif</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/animated/giflite/package-summary.html">com.facebook.animated.giflite</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/animated/giflite/decoder/package-summary.html">com.facebook.animated.giflite.decoder</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/animated/giflite/draw/package-summary.html">com.facebook.animated.giflite.draw</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/animated/giflite/drawable/package-summary.html">com.facebook.animated.giflite.drawable</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/animated/webp/package-summary.html">com.facebook.animated.webp</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/animated/webpdrawable/package-summary.html">com.facebook.animated.webpdrawable</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/binaryresource/package-summary.html">com.facebook.binaryresource</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/cache/common/package-summary.html">com.facebook.cache.common</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/cache/disk/package-summary.html">com.facebook.cache.disk</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/callercontext/package-summary.html">com.facebook.callercontext</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/activitylistener/package-summary.html">com.facebook.common.activitylistener</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/disk/package-summary.html">com.facebook.common.disk</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/executors/package-summary.html">com.facebook.common.executors</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/file/package-summary.html">com.facebook.common.file</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/internal/package-summary.html">com.facebook.common.internal</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/lifecycle/package-summary.html">com.facebook.common.lifecycle</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/logging/package-summary.html">com.facebook.common.logging</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/media/package-summary.html">com.facebook.common.media</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/memory/package-summary.html">com.facebook.common.memory</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/references/package-summary.html">com.facebook.common.references</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/statfs/package-summary.html">com.facebook.common.statfs</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/streams/package-summary.html">com.facebook.common.streams</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/time/package-summary.html">com.facebook.common.time</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/util/package-summary.html">com.facebook.common.util</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/common/webp/package-summary.html">com.facebook.common.webp</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/datasource/package-summary.html">com.facebook.datasource</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/drawable/base/package-summary.html">com.facebook.drawable.base</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/drawee/backends/pipeline/package-summary.html">com.facebook.drawee.backends.pipeline</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/drawee/backends/pipeline/debug/package-summary.html">com.facebook.drawee.backends.pipeline.debug</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/drawee/backends/pipeline/info/package-summary.html">com.facebook.drawee.backends.pipeline.info</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/drawee/backends/pipeline/info/internal/package-summary.html">com.facebook.drawee.backends.pipeline.info.internal</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/drawee/components/package-summary.html">com.facebook.drawee.components</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/drawee/controller/package-summary.html">com.facebook.drawee.controller</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/drawee/debug/package-summary.html">com.facebook.drawee.debug</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/drawee/debug/listener/package-summary.html">com.facebook.drawee.debug.listener</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/drawee/drawable/package-summary.html">com.facebook.drawee.drawable</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/drawee/generic/package-summary.html">com.facebook.drawee.generic</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/drawee/gestures/package-summary.html">com.facebook.drawee.gestures</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/drawee/interfaces/package-summary.html">com.facebook.drawee.interfaces</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/drawee/span/package-summary.html">com.facebook.drawee.span</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/drawee/view/package-summary.html">com.facebook.drawee.view</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/fresco/animation/backend/package-summary.html">com.facebook.fresco.animation.backend</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/fresco/animation/bitmap/package-summary.html">com.facebook.fresco.animation.bitmap</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/fresco/animation/bitmap/cache/package-summary.html">com.facebook.fresco.animation.bitmap.cache</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/fresco/animation/bitmap/preparation/package-summary.html">com.facebook.fresco.animation.bitmap.preparation</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/fresco/animation/bitmap/wrapper/package-summary.html">com.facebook.fresco.animation.bitmap.wrapper</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/fresco/animation/drawable/package-summary.html">com.facebook.fresco.animation.drawable</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/fresco/animation/drawable/animator/package-summary.html">com.facebook.fresco.animation.drawable.animator</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/fresco/animation/factory/package-summary.html">com.facebook.fresco.animation.factory</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/fresco/animation/frame/package-summary.html">com.facebook.fresco.animation.frame</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/fresco/middleware/package-summary.html">com.facebook.fresco.middleware</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/fresco/ui/common/package-summary.html">com.facebook.fresco.ui.common</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imageformat/package-summary.html">com.facebook.imageformat</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/animated/base/package-summary.html">com.facebook.imagepipeline.animated.base</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/animated/factory/package-summary.html">com.facebook.imagepipeline.animated.factory</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/animated/impl/package-summary.html">com.facebook.imagepipeline.animated.impl</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/animated/util/package-summary.html">com.facebook.imagepipeline.animated.util</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/backends/okhttp3/package-summary.html">com.facebook.imagepipeline.backends.okhttp3</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/backends/volley/package-summary.html">com.facebook.imagepipeline.backends.volley</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/bitmaps/package-summary.html">com.facebook.imagepipeline.bitmaps</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/cache/package-summary.html">com.facebook.imagepipeline.cache</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/common/package-summary.html">com.facebook.imagepipeline.common</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/core/package-summary.html">com.facebook.imagepipeline.core</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/datasource/package-summary.html">com.facebook.imagepipeline.datasource</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/debug/package-summary.html">com.facebook.imagepipeline.debug</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/decoder/package-summary.html">com.facebook.imagepipeline.decoder</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/drawable/package-summary.html">com.facebook.imagepipeline.drawable</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/filter/package-summary.html">com.facebook.imagepipeline.filter</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/image/package-summary.html">com.facebook.imagepipeline.image</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/instrumentation/package-summary.html">com.facebook.imagepipeline.instrumentation</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/listener/package-summary.html">com.facebook.imagepipeline.listener</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/memory/package-summary.html">com.facebook.imagepipeline.memory</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/multiuri/package-summary.html">com.facebook.imagepipeline.multiuri</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/nativecode/package-summary.html">com.facebook.imagepipeline.nativecode</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/platform/package-summary.html">com.facebook.imagepipeline.platform</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/postprocessors/package-summary.html">com.facebook.imagepipeline.postprocessors</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/producers/package-summary.html">com.facebook.imagepipeline.producers</a></li> <li class="selected api apilevel-"> <a href="../../../../com/facebook/imagepipeline/request/package-summary.html">com.facebook.imagepipeline.request</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/systrace/package-summary.html">com.facebook.imagepipeline.systrace</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/transcoder/package-summary.html">com.facebook.imagepipeline.transcoder</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imagepipeline/transformation/package-summary.html">com.facebook.imagepipeline.transformation</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/imageutils/package-summary.html">com.facebook.imageutils</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/webpsupport/package-summary.html">com.facebook.webpsupport</a></li> <li class="api apilevel-"> <a href="../../../../com/facebook/widget/text/span/package-summary.html">com.facebook.widget.text.span</a></li> </ul><br/> </div> <!-- end packages --> </div> <!-- end resize-packages --> <div id="classes-nav"> <ul> <li><h2>Interfaces</h2> <ul> <li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/request/HasImageRequest.html">HasImageRequest</a></li> <li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/request/Postprocessor.html">Postprocessor</a></li> <li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/request/RepeatedPostprocessor.html">RepeatedPostprocessor</a></li> <li class="selected api apilevel-"><a href="../../../../com/facebook/imagepipeline/request/RepeatedPostprocessorRunner.html">RepeatedPostprocessorRunner</a></li> </ul> </li> <li><h2>Classes</h2> <ul> <li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/request/BasePostprocessor.html">BasePostprocessor</a></li> <li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/request/BaseRepeatedPostProcessor.html">BaseRepeatedPostProcessor</a></li> <li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/request/ImageRequest.html">ImageRequest</a></li> <li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/request/ImageRequestBuilder.html">ImageRequestBuilder</a></li> </ul> </li> <li><h2>Enums</h2> <ul> <li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/request/ImageRequest.CacheChoice.html">ImageRequest.CacheChoice</a></li> <li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/request/ImageRequest.RequestLevel.html">ImageRequest.RequestLevel</a></li> </ul> </li> <li><h2>Exceptions</h2> <ul> <li class="api apilevel-"><a href="../../../../com/facebook/imagepipeline/request/ImageRequestBuilder.BuilderException.html">ImageRequestBuilder.BuilderException</a></li> </ul> </li> </ul><br/> </div><!-- end classes --> </div><!-- end nav-panels --> <div id="nav-tree" style="display:none"> <div id="index-links"> <a href="../../../../packages.html" >Packages</a> | <a href="../../../../classes.html" >Classes</a> </div> </div><!-- end nav-tree --> </div><!-- end swapper --> </div> <!-- end side-nav --> <script> if (!isMobile) { //$("<a href='#' id='nav-swap' onclick='swapNav();return false;' style='font-size:10px;line-height:9px;margin-left:1em;text-decoration:none;'><span id='tree-link'>Use Tree Navigation</span><span id='panel-link' style='display:none'>Use Panel Navigation</span></a>").appendTo("#side-nav"); chooseDefaultNav(); if ($("#nav-tree").is(':visible')) { init_default_navtree("../../../../"); } else { addLoadEvent(function() { scrollIntoView("packages-nav"); scrollIntoView("classes-nav"); }); } //$("#swapper").css({borderBottom:"2px solid #aaa"}); } else { swapNav(); // tree view should be used on mobile } </script> <div class="g-unit" id="doc-content"> <div id="api-info-block"> <div class="sum-details-links"> </div><!-- end sum-details-links --> <div class="api-level"> </div> </div><!-- end api-info-block --> <!-- ======== START OF CLASS DATA ======== --> <div id="jd-header"> public interface <h1>RepeatedPostprocessorRunner</h1> </div><!-- end header --> <div id="naMessage"></div> <div id="jd-content" class="api apilevel-"> <table class="jd-inheritance-table"> <tr> <td colspan="1" class="jd-inheritance-class-cell">com.facebook.imagepipeline.request.RepeatedPostprocessorRunner</td> </tr> </table> <div class="jd-descr"> <h2>Class Overview</h2> <p>An instance of this class is used to run a postprocessor whenever the client requires. </p> </div><!-- jd-descr --> <div class="jd-descr"> <h2>Summary</h2> <!-- ========== METHOD SUMMARY =========== --> <table id="pubmethods" class="jd-sumtable"><tr><th colspan="12">Public Methods</th></tr> <tr class="alt-color api apilevel-" > <td class="jd-typecol"> abstract void </td> <td class="jd-linkcol" width="100%"> <span class="sympad"><a href="../../../../com/facebook/imagepipeline/request/RepeatedPostprocessorRunner.html#update()">update</a></span>() </td></tr> </table> </div><!-- jd-descr (summary) --> <!-- Details --> <!-- XML Attributes --> <!-- Enum Values --> <!-- Constants --> <!-- Fields --> <!-- Public ctors --> <!-- ========= CONSTRUCTOR DETAIL ======== --> <!-- Protected ctors --> <!-- ========= METHOD DETAIL ======== --> <!-- Public methdos --> <h2>Public Methods</h2> <a id="update()"></a> <div class="jd-details api apilevel-"> <h4 class="jd-details-title"> <span class="normal"> public abstract void </span> <span class="sympad">update</span> <span class="normal">()</span> </h4> <div class="api-level"> <div> </div> </div> <div class="jd-details-descr"> <div class="jd-tagdata jd-tagdescr"><p></p></div> </div> </div> <!-- ========= METHOD DETAIL ======== --> <!-- ========= END OF CLASS DATA ========= --> <a id="navbar_top"></a> <div id="footer"> +Generated by <a href="http://code.google.com/p/doclava/">Doclava</a>. +</div> <!-- end footer - @generated --> </div> <!-- jd-content --> </div><!-- end doc-content --> </div> <!-- end body-content --> <script type="text/javascript"> init(); /* initialize doclava-developer-docs.js */ </script> </body> </html>
mit
tonivade/claudb
lib/src/test/java/com/github/tonivade/claudb/data/SortedSetTest.java
2686
/* * Copyright (c) 2015-2022, Antonio Gabriel Muñoz Conejo <antoniogmc at gmail dot com> * Distributed under the terms of the MIT License */ package com.github.tonivade.claudb.data; import static com.github.tonivade.claudb.data.DatabaseValue.score; import static com.github.tonivade.resp.protocol.SafeString.safeString; import static java.util.Collections.unmodifiableSet; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.MatcherAssert.assertThat; import org.junit.Test; public class SortedSetTest { @Test public void testSet() { SortedSet set = new SortedSet(); assertThat(set.add(score(1, safeString("a"))), is(true)); assertThat(set.add(score(2, safeString("a"))), is(false)); assertThat(set.add(score(2, safeString("b"))), is(true)); assertThat(set.contains(score(0, safeString("a"))), is(true)); assertThat(set.contains(score(0, safeString("b"))), is(true)); assertThat(set.contains(score(0, safeString("c"))), is(false)); assertThat(set.score(safeString("a")), is(1.0)); assertThat(set.score(safeString("b")), is(2.0)); assertThat(set.ranking(safeString("a")), is(0)); assertThat(set.ranking(safeString("b")), is(1)); assertThat(set.remove(score(0, safeString("a"))), is(true)); assertThat(set.contains(score(0, safeString("a"))), is(false)); } @Test public void testEquals() { SortedSet setA = new SortedSet(); setA.add(score(1, safeString("a"))); setA.add(score(2, safeString("b"))); SortedSet setB = new SortedSet(); setB.add(score(1, safeString("a"))); setB.add(score(2, safeString("b"))); assertThat(setA, is(setB)); assertThat(unmodifiableSet(setA), is(unmodifiableSet(setB))); } @Test public void testNotEquals() { SortedSet setA = new SortedSet(); setA.add(score(1, safeString("a"))); SortedSet setB = new SortedSet(); setB.add(score(1, safeString("a"))); setB.add(score(2, safeString("b"))); assertThat(setA, not(is(setB))); } @Test public void testScore() { SortedSet set = new SortedSet(); set.add(score(1, safeString("a"))); set.add(score(2, safeString("b"))); set.add(score(3, safeString("c"))); set.add(score(4, safeString("d"))); set.add(score(5, safeString("e"))); set.add(score(6, safeString("f"))); set.add(score(7, safeString("g"))); set.add(score(8, safeString("h"))); set.add(score(9, safeString("i"))); assertThat(set.tailSet(score(3, safeString(""))).first(), is(score(3.0, safeString("c")))); assertThat(set.headSet(score(4, safeString(""))).last(), is(score(3.0, safeString("c")))); } }
mit
KKoPV/PVLng
core/Channel/Sonnenertrag/JSON.php
4502
<?php /** * Delivers the daily production in Wh/kWh * * URL format: * .../<GUID>.json?m= for Wh data * .../<GUID>.json?u=kWh&m= for kWh data * * kWh format is hightly suggested! * * http://wiki.sonnenertrag.eu/datenimport:json * * @author Knut Kohl <[email protected]> * @copyright 2012-2013 Knut Kohl * @license GNU General Public License http://www.gnu.org/licenses/gpl.txt * @version 1.0.0 */ namespace Channel\Sonnenertrag; /** * */ class JSON extends \Channel { /** * Accept only childs of the same entity type */ public function addChild( $guid ) { $childs = $this->getChilds(); if (empty($childs)) { // Add 1st child return parent::addChild($guid); } // Check if the new child have the same type as the 1st (and any other) child $first = self::byID($childs[0]['entity']); $new = self::byGUID($guid); if ($first->type == $new->type) { // ok, add new child return parent::addChild($guid); } throw new Exception('"'.$this->name.'" accepts only childs of type "'.$first->type.'"', 400); } /** * */ public function read( $request, $attributes=FALSE ) { $this->year = date('Y'); $this->month = (array_key_exists('m', $request) AND $request['m']) ? $request['m'] : date('n'); $this->factor = (array_key_exists('u', $request) AND $request['u'] == 'kWh') ? 1000 : 1; if ($this->month > date('n')) $this->year--; $request['start'] = $this->year . '-' . $this->month . '-01'; $request['end'] = $this->year . '-' . $this->month . '-01+1month'; $request['period'] = '1day'; $request['full'] = TRUE; $request['format'] = 'json'; $this->before_read($request); $childs = $this->getChilds(); // no childs, return empty file if (count($childs) == 0) { return $this->finish(); } $buffer = $childs[0]->read($request); // only one child, use as is if (count($childs) == 1) { $result = $buffer; } // combine all data for same timestamp for ($i=1; $i<count($childs); $i++) { $next = $childs[$i]->read($request); $row1 = $buffer->rewind()->current(); $row2 = $next->rewind()->current(); $result = new \Buffer; while (!empty($row1) OR !empty($row2)) { if ($buffer->key() == $next->key()) { // same timestamp, combine $row1['consumption'] += $row2['consumption']; $result->write($row1, $buffer->key()); // read both next rows $row1 = $buffer->next()->current(); $row2 = $next->next()->current(); } elseif ($buffer->key() AND $buffer->key() < $next->key() OR $next->key() == '') { // missing row 2, save row 1 as is $result->write($row1, $buffer->key()); // read only row 1 $row1 = $buffer->next()->current(); } else /* $buffer->key() > $next->key() */ { // missing row 1, save row 2 as is $result->write($row2, $next->key()); // read only row 2 $row2 = $next->next()->current(); } } $buffer = $result; } $data = array(); foreach ($result as $row) { $data[] = round($row['consumption'] / $this->factor, 3); } return $this->finish($data); } /** * r2 */ public function GET ( &$request ) { $request['format'] = 'json'; return $this->read($request); } // ----------------------------------------------------------------------- // PROTECTED // ----------------------------------------------------------------------- protected function finish( $data=array() ) { // Provide full information... return array( 'un' => $this->factor == 1 ? 'Wh' : 'kWh', 'tm' => sprintf('%04d-%02d-01T00:00:00', $this->year, $this->month), 'dt' => 86400, 'val' => $data ); } }
mit
relimited/HearthSim
src/main/java/com/hearthsim/card/classic/spell/rare/BlessedChampion.java
1657
package com.hearthsim.card.classic.spell.rare; import com.hearthsim.card.minion.Minion; import com.hearthsim.card.spellcard.SpellTargetableCard; import com.hearthsim.event.effect.EffectCharacter; import com.hearthsim.event.filter.FilterCharacter; import com.hearthsim.event.filter.FilterCharacterTargetedSpell; public class BlessedChampion extends SpellTargetableCard { public static final EffectCharacter effect = (originSide, origin, targetSide, targetCharacterIndex, boardState) -> { Minion targetCharacter = boardState.data_.getCharacter(targetSide, targetCharacterIndex); targetCharacter.setAttack((byte) (2 * targetCharacter.getTotalAttack())); return boardState; }; /** * Constructor * * @param hasBeenUsed Whether the card has already been used or not */ @Deprecated public BlessedChampion(boolean hasBeenUsed) { this(); this.hasBeenUsed = hasBeenUsed; } /** * Constructor * * Defaults to hasBeenUsed = false */ public BlessedChampion() { super(); } @Override public FilterCharacter getTargetableFilter() { return FilterCharacterTargetedSpell.ALL_MINIONS; } /** * * Use the card on the given target * * Double a minion's Attack * * * * @param side * @param boardState The BoardState before this card has performed its action. It will be manipulated and returned. * * @return The boardState is manipulated and returned */ @Override public EffectCharacter getTargetableEffect() { return BlessedChampion.effect; } }
mit
scbizu/letschat
vendor/github.com/nareix/joy4/format/format.go
557
package format import ( "github.com/nareix/joy4/av/avutil" "github.com/nareix/joy4/format/aac" "github.com/nareix/joy4/format/flv" "github.com/nareix/joy4/format/mp4" "github.com/nareix/joy4/format/rtmp" "github.com/nareix/joy4/format/rtsp" "github.com/nareix/joy4/format/ts" ) func RegisterAll() { avutil.DefaultHandlers.Add(mp4.Handler) avutil.DefaultHandlers.Add(ts.Handler) avutil.DefaultHandlers.Add(rtmp.Handler) avutil.DefaultHandlers.Add(rtsp.Handler) avutil.DefaultHandlers.Add(flv.Handler) avutil.DefaultHandlers.Add(aac.Handler) }
mit
nemoNoboru/ET3
controllers/subirApunte.php
4059
<?php // Controlador subir apunte hecho por FVieira //Includes iniciales require_once '../views/templateEngine.php'; require_once '../model/driver.php'; require_once '../model/Apunte.php'; require_once '../model/Usuario.php'; require_once '../model/Materia.php'; require_once '../model/Materia_Usuario.php'; require_once '../model/Notificacion.php'; require_once 'navbar.php'; require_once 'comboboxes.php'; require_once 'modal.php'; session_start(); // se inicia el manejo de sesiones //Cancerbero require_once '../cancerbero/cancerbero.php'; $cerb = new Cancerbero('AP_SubirApunte'); $cerb->handleAuto(); $db = Driver::getInstance(); //Instancias TemplateEngine, renderizan elementos $renderMain = new TemplateEngine(); $renderSubirApunte = new TemplateEngine(); $usuarios = new Usuario($db); $usuario = $usuarios->findBy('user_name',$_SESSION['name']); $renderSubirApunte->materias = $usuario[0]->materias(); //se renderiza el combobox materia $renderSubirApunte->modal = null; //FUNCIONES DEL CONTROLADOR $renderMain->title = "SubirApunte"; //Titulo y cabecera de la pagina if(isset($_FILES['apunteUploaded'])){ //inicio colecta de datos para ser introducidos en la bd $apunte = new Apunte($db); $id = $usuario[0]->getUser_id(); $apunte->setUser_id($id); $apunte->setApunte_name($_POST['name']); $apunte->setMat_id($_POST['materia']); $apunte->setAnho_academico($_POST['anho']); //fin colecta de datos //inicio operacion subir archivo $titulo = "Archivo subido correctamente"; $contenido = "gracias por su colaboración con la comunidad"; $target = "../apuntes/"; $hashedName = md5_file($_FILES['apunteUploaded']['tmp_name']); //en el servidor su guarda como filename el hash md5 //resultante de hashear el archivo. Asi si dos archivos son diferentes tendran diferente filename $target = $target . basename( $hashedName ) ; $ok=1; if($_FILES["apunteUploaded"]["type"] == "application/pdf"){ if(is_uploaded_file($_FILES['apunteUploaded']['tmp_name'])){ if(move_uploaded_file($_FILES['apunteUploaded']['tmp_name'], $target)) { $titulo = "El apunte ". basename( $_FILES['apunteUploaded']['name']). " ha sido subido correctamente"; $matuser= new Materia_usuario($db); $notificacion= new Notificacion($db); $materia= new Materia($db); $date = getdate(); $buffer = $date['year']."-".$date['mon']."-".$date['mday']; $mat= $materia->findBy('mat_id',$apunte->getMat_id())[0]->getMat_name(); $array=$matuser->findBy('mat_id',$apunte->getMat_id()); foreach($array as $arrays){ $notificacion->setFecha($buffer); $notificacion->setContenido("Nuevos apuntes en " .$mat); $notificacion->setUser_id($arrays->getUser_id()); $notificacion->create(); } } else { $titulo = "Error subiendo el apunte."; $contenido = "Ha ocurrido un error inesperado. Compruebe los datos de entrada, pruebe otra vez y si el error sigue ocurriendo contacte con un administrador"; } } }else{ $titulo = "fichero invalido"; $contenido = "compruebe que su fichero es .pdf"; } //fin operacion subir archivo $apunte->setRuta($hashedName); $apunte->create(); //se crea en la BD el nuevo apunte $renderSubirApunte->modal = renderModal($titulo,$contenido); } //RENDERIZADO FINAL $renderSubirApunte->comboboxAnho = anhoRenderComboBox(); // se renderiza el combobox de año $renderMain->navbar = renderNavBar(); //Inserción de navBar en la pagina. Omitible si no la necesita $renderMain->content = $renderSubirApunte->render('subirApunte_v.php'); //Inserción del contenido de la página echo $renderMain->renderMain(); // Dibujado de la página al completo ?>
mit
twilio/twilio-python
twilio/rest/video/v1/room/room_participant/__init__.py
20355
# coding=utf-8 r""" This code was generated by \ / _ _ _| _ _ | (_)\/(_)(_|\/| |(/_ v1.0.0 / / """ from twilio.base import deserialize from twilio.base import serialize from twilio.base import values from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource from twilio.base.page import Page from twilio.rest.video.v1.room.room_participant.room_participant_published_track import PublishedTrackList from twilio.rest.video.v1.room.room_participant.room_participant_subscribe_rule import SubscribeRulesList from twilio.rest.video.v1.room.room_participant.room_participant_subscribed_track import SubscribedTrackList class ParticipantList(ListResource): def __init__(self, version, room_sid): """ Initialize the ParticipantList :param Version version: Version that contains the resource :param room_sid: The SID of the participant's room :returns: twilio.rest.video.v1.room.room_participant.ParticipantList :rtype: twilio.rest.video.v1.room.room_participant.ParticipantList """ super(ParticipantList, self).__init__(version) # Path Solution self._solution = {'room_sid': room_sid, } self._uri = '/Rooms/{room_sid}/Participants'.format(**self._solution) def stream(self, status=values.unset, identity=values.unset, date_created_after=values.unset, date_created_before=values.unset, limit=None, page_size=None): """ Streams ParticipantInstance records from the API as a generator stream. This operation lazily loads records as efficiently as possible until the limit is reached. The results are returned as a generator, so this operation is memory efficient. :param ParticipantInstance.Status status: Read only the participants with this status :param unicode identity: Read only the Participants with this user identity value :param datetime date_created_after: Read only Participants that started after this date in UTC ISO 8601 format :param datetime date_created_before: Read only Participants that started before this date in ISO 8601 format :param int limit: Upper limit for the number of records to return. stream() guarantees to never return more than limit. Default is no limit :param int page_size: Number of records to fetch per request, when not set will use the default value of 50 records. If no page_size is defined but a limit is defined, stream() will attempt to read the limit with the most efficient page size, i.e. min(limit, 1000) :returns: Generator that will yield up to limit results :rtype: list[twilio.rest.video.v1.room.room_participant.ParticipantInstance] """ limits = self._version.read_limits(limit, page_size) page = self.page( status=status, identity=identity, date_created_after=date_created_after, date_created_before=date_created_before, page_size=limits['page_size'], ) return self._version.stream(page, limits['limit']) def list(self, status=values.unset, identity=values.unset, date_created_after=values.unset, date_created_before=values.unset, limit=None, page_size=None): """ Lists ParticipantInstance records from the API as a list. Unlike stream(), this operation is eager and will load `limit` records into memory before returning. :param ParticipantInstance.Status status: Read only the participants with this status :param unicode identity: Read only the Participants with this user identity value :param datetime date_created_after: Read only Participants that started after this date in UTC ISO 8601 format :param datetime date_created_before: Read only Participants that started before this date in ISO 8601 format :param int limit: Upper limit for the number of records to return. list() guarantees never to return more than limit. Default is no limit :param int page_size: Number of records to fetch per request, when not set will use the default value of 50 records. If no page_size is defined but a limit is defined, list() will attempt to read the limit with the most efficient page size, i.e. min(limit, 1000) :returns: Generator that will yield up to limit results :rtype: list[twilio.rest.video.v1.room.room_participant.ParticipantInstance] """ return list(self.stream( status=status, identity=identity, date_created_after=date_created_after, date_created_before=date_created_before, limit=limit, page_size=page_size, )) def page(self, status=values.unset, identity=values.unset, date_created_after=values.unset, date_created_before=values.unset, page_token=values.unset, page_number=values.unset, page_size=values.unset): """ Retrieve a single page of ParticipantInstance records from the API. Request is executed immediately :param ParticipantInstance.Status status: Read only the participants with this status :param unicode identity: Read only the Participants with this user identity value :param datetime date_created_after: Read only Participants that started after this date in UTC ISO 8601 format :param datetime date_created_before: Read only Participants that started before this date in ISO 8601 format :param str page_token: PageToken provided by the API :param int page_number: Page Number, this value is simply for client state :param int page_size: Number of records to return, defaults to 50 :returns: Page of ParticipantInstance :rtype: twilio.rest.video.v1.room.room_participant.ParticipantPage """ data = values.of({ 'Status': status, 'Identity': identity, 'DateCreatedAfter': serialize.iso8601_datetime(date_created_after), 'DateCreatedBefore': serialize.iso8601_datetime(date_created_before), 'PageToken': page_token, 'Page': page_number, 'PageSize': page_size, }) response = self._version.page(method='GET', uri=self._uri, params=data, ) return ParticipantPage(self._version, response, self._solution) def get_page(self, target_url): """ Retrieve a specific page of ParticipantInstance records from the API. Request is executed immediately :param str target_url: API-generated URL for the requested results page :returns: Page of ParticipantInstance :rtype: twilio.rest.video.v1.room.room_participant.ParticipantPage """ response = self._version.domain.twilio.request( 'GET', target_url, ) return ParticipantPage(self._version, response, self._solution) def get(self, sid): """ Constructs a ParticipantContext :param sid: The SID that identifies the resource to fetch :returns: twilio.rest.video.v1.room.room_participant.ParticipantContext :rtype: twilio.rest.video.v1.room.room_participant.ParticipantContext """ return ParticipantContext(self._version, room_sid=self._solution['room_sid'], sid=sid, ) def __call__(self, sid): """ Constructs a ParticipantContext :param sid: The SID that identifies the resource to fetch :returns: twilio.rest.video.v1.room.room_participant.ParticipantContext :rtype: twilio.rest.video.v1.room.room_participant.ParticipantContext """ return ParticipantContext(self._version, room_sid=self._solution['room_sid'], sid=sid, ) def __repr__(self): """ Provide a friendly representation :returns: Machine friendly representation :rtype: str """ return '<Twilio.Video.V1.ParticipantList>' class ParticipantPage(Page): def __init__(self, version, response, solution): """ Initialize the ParticipantPage :param Version version: Version that contains the resource :param Response response: Response from the API :param room_sid: The SID of the participant's room :returns: twilio.rest.video.v1.room.room_participant.ParticipantPage :rtype: twilio.rest.video.v1.room.room_participant.ParticipantPage """ super(ParticipantPage, self).__init__(version, response) # Path Solution self._solution = solution def get_instance(self, payload): """ Build an instance of ParticipantInstance :param dict payload: Payload response from the API :returns: twilio.rest.video.v1.room.room_participant.ParticipantInstance :rtype: twilio.rest.video.v1.room.room_participant.ParticipantInstance """ return ParticipantInstance(self._version, payload, room_sid=self._solution['room_sid'], ) def __repr__(self): """ Provide a friendly representation :returns: Machine friendly representation :rtype: str """ return '<Twilio.Video.V1.ParticipantPage>' class ParticipantContext(InstanceContext): def __init__(self, version, room_sid, sid): """ Initialize the ParticipantContext :param Version version: Version that contains the resource :param room_sid: The SID of the room with the Participant resource to fetch :param sid: The SID that identifies the resource to fetch :returns: twilio.rest.video.v1.room.room_participant.ParticipantContext :rtype: twilio.rest.video.v1.room.room_participant.ParticipantContext """ super(ParticipantContext, self).__init__(version) # Path Solution self._solution = {'room_sid': room_sid, 'sid': sid, } self._uri = '/Rooms/{room_sid}/Participants/{sid}'.format(**self._solution) # Dependents self._published_tracks = None self._subscribed_tracks = None self._subscribe_rules = None def fetch(self): """ Fetch the ParticipantInstance :returns: The fetched ParticipantInstance :rtype: twilio.rest.video.v1.room.room_participant.ParticipantInstance """ payload = self._version.fetch(method='GET', uri=self._uri, ) return ParticipantInstance( self._version, payload, room_sid=self._solution['room_sid'], sid=self._solution['sid'], ) def update(self, status=values.unset): """ Update the ParticipantInstance :param ParticipantInstance.Status status: The new status of the resource :returns: The updated ParticipantInstance :rtype: twilio.rest.video.v1.room.room_participant.ParticipantInstance """ data = values.of({'Status': status, }) payload = self._version.update(method='POST', uri=self._uri, data=data, ) return ParticipantInstance( self._version, payload, room_sid=self._solution['room_sid'], sid=self._solution['sid'], ) @property def published_tracks(self): """ Access the published_tracks :returns: twilio.rest.video.v1.room.room_participant.room_participant_published_track.PublishedTrackList :rtype: twilio.rest.video.v1.room.room_participant.room_participant_published_track.PublishedTrackList """ if self._published_tracks is None: self._published_tracks = PublishedTrackList( self._version, room_sid=self._solution['room_sid'], participant_sid=self._solution['sid'], ) return self._published_tracks @property def subscribed_tracks(self): """ Access the subscribed_tracks :returns: twilio.rest.video.v1.room.room_participant.room_participant_subscribed_track.SubscribedTrackList :rtype: twilio.rest.video.v1.room.room_participant.room_participant_subscribed_track.SubscribedTrackList """ if self._subscribed_tracks is None: self._subscribed_tracks = SubscribedTrackList( self._version, room_sid=self._solution['room_sid'], participant_sid=self._solution['sid'], ) return self._subscribed_tracks @property def subscribe_rules(self): """ Access the subscribe_rules :returns: twilio.rest.video.v1.room.room_participant.room_participant_subscribe_rule.SubscribeRulesList :rtype: twilio.rest.video.v1.room.room_participant.room_participant_subscribe_rule.SubscribeRulesList """ if self._subscribe_rules is None: self._subscribe_rules = SubscribeRulesList( self._version, room_sid=self._solution['room_sid'], participant_sid=self._solution['sid'], ) return self._subscribe_rules def __repr__(self): """ Provide a friendly representation :returns: Machine friendly representation :rtype: str """ context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) return '<Twilio.Video.V1.ParticipantContext {}>'.format(context) class ParticipantInstance(InstanceResource): class Status(object): CONNECTED = "connected" DISCONNECTED = "disconnected" def __init__(self, version, payload, room_sid, sid=None): """ Initialize the ParticipantInstance :returns: twilio.rest.video.v1.room.room_participant.ParticipantInstance :rtype: twilio.rest.video.v1.room.room_participant.ParticipantInstance """ super(ParticipantInstance, self).__init__(version) # Marshaled Properties self._properties = { 'sid': payload.get('sid'), 'room_sid': payload.get('room_sid'), 'account_sid': payload.get('account_sid'), 'status': payload.get('status'), 'identity': payload.get('identity'), 'date_created': deserialize.iso8601_datetime(payload.get('date_created')), 'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')), 'start_time': deserialize.iso8601_datetime(payload.get('start_time')), 'end_time': deserialize.iso8601_datetime(payload.get('end_time')), 'duration': deserialize.integer(payload.get('duration')), 'url': payload.get('url'), 'links': payload.get('links'), } # Context self._context = None self._solution = {'room_sid': room_sid, 'sid': sid or self._properties['sid'], } @property def _proxy(self): """ Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: ParticipantContext for this ParticipantInstance :rtype: twilio.rest.video.v1.room.room_participant.ParticipantContext """ if self._context is None: self._context = ParticipantContext( self._version, room_sid=self._solution['room_sid'], sid=self._solution['sid'], ) return self._context @property def sid(self): """ :returns: The unique string that identifies the resource :rtype: unicode """ return self._properties['sid'] @property def room_sid(self): """ :returns: The SID of the participant's room :rtype: unicode """ return self._properties['room_sid'] @property def account_sid(self): """ :returns: The SID of the Account that created the resource :rtype: unicode """ return self._properties['account_sid'] @property def status(self): """ :returns: The status of the Participant :rtype: ParticipantInstance.Status """ return self._properties['status'] @property def identity(self): """ :returns: The string that identifies the resource's User :rtype: unicode """ return self._properties['identity'] @property def date_created(self): """ :returns: The ISO 8601 date and time in GMT when the resource was created :rtype: datetime """ return self._properties['date_created'] @property def date_updated(self): """ :returns: The ISO 8601 date and time in GMT when the resource was last updated :rtype: datetime """ return self._properties['date_updated'] @property def start_time(self): """ :returns: The time of participant connected to the room in ISO 8601 format :rtype: datetime """ return self._properties['start_time'] @property def end_time(self): """ :returns: The time when the participant disconnected from the room in ISO 8601 format :rtype: datetime """ return self._properties['end_time'] @property def duration(self): """ :returns: Duration of time in seconds the participant was connected :rtype: unicode """ return self._properties['duration'] @property def url(self): """ :returns: The absolute URL of the resource :rtype: unicode """ return self._properties['url'] @property def links(self): """ :returns: The URLs of related resources :rtype: unicode """ return self._properties['links'] def fetch(self): """ Fetch the ParticipantInstance :returns: The fetched ParticipantInstance :rtype: twilio.rest.video.v1.room.room_participant.ParticipantInstance """ return self._proxy.fetch() def update(self, status=values.unset): """ Update the ParticipantInstance :param ParticipantInstance.Status status: The new status of the resource :returns: The updated ParticipantInstance :rtype: twilio.rest.video.v1.room.room_participant.ParticipantInstance """ return self._proxy.update(status=status, ) @property def published_tracks(self): """ Access the published_tracks :returns: twilio.rest.video.v1.room.room_participant.room_participant_published_track.PublishedTrackList :rtype: twilio.rest.video.v1.room.room_participant.room_participant_published_track.PublishedTrackList """ return self._proxy.published_tracks @property def subscribed_tracks(self): """ Access the subscribed_tracks :returns: twilio.rest.video.v1.room.room_participant.room_participant_subscribed_track.SubscribedTrackList :rtype: twilio.rest.video.v1.room.room_participant.room_participant_subscribed_track.SubscribedTrackList """ return self._proxy.subscribed_tracks @property def subscribe_rules(self): """ Access the subscribe_rules :returns: twilio.rest.video.v1.room.room_participant.room_participant_subscribe_rule.SubscribeRulesList :rtype: twilio.rest.video.v1.room.room_participant.room_participant_subscribe_rule.SubscribeRulesList """ return self._proxy.subscribe_rules def __repr__(self): """ Provide a friendly representation :returns: Machine friendly representation :rtype: str """ context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) return '<Twilio.Video.V1.ParticipantInstance {}>'.format(context)
mit
imasaru/sabbath-school-lessons
src/zh/2020-04-hant/06/06.md
1752
--- title: 一個頓悟的學生 date: 05/11/2020 --- 耶穌和跟隨祂的人往耶路撒冷走去。從前希律王在意的是施洗約翰,但現在包括希律王在內的當權者在意的是耶穌。跟隨祂的人包括窮人和其他渴望改變的弱勢群體。 耶穌最想做的就是給這個世界帶來希望。但祂現在非常確定,那些位高權重的人會竭力抵制這一使命。他們不希望祂成功。 至於耶穌門徒的核心圈子,就是那十二個門徒,似乎急於站在耶穌這邊。但與此同時,他們似乎也很困惑,或者說很盲目。例如在可8:31-33,大教師要祂的學生們努力去看他們很難看清的事。也就是說,在許多方面,他們仍然對真正重要的事情存著屬靈的盲目(見可8:37)。 而這一切正是耶穌與一個真正看得清之人相遇時的背景。 `請閱讀耶穌使一個叫巴底買的盲眼乞丐得醫治的故事(見可10:46-52)。注意耶穌對那人顯出的偉大恩慈。現在,想一想那位瞎子想重見光明的願望如何一路引導他,讓他決定跟隨耶穌去耶路撒冷。你認為馬可是刻意將巴底買和其他門徒做一番比較嗎?這個故事如何讓你明白,對大教師的回應意味著什麼?` 巴底買原想看見嬰兒頭上的卷髮和收割時小麥的顏色。但所謂「看見」,不僅試紙實質上的東西。換句話說,這個故事說的是屬靈上的看見,是明白大教師真正關心的是什麼。看得見的確很重要,耶穌明白這一點。但祂也深知,每個人最懇切的願望是追求一個更新、更美好的人生。 `請閱讀來5:12-14。關於真教育,這節經文教導了我們什麼?`
mit
VirusTotal/content
Packs/URLHaus/ReleaseNotes/1_0_8.md
133
#### Integrations ##### URLhaus - Fixed an issue where non-latin characters in *url* parameter in **url** command raised exception.
mit
ministryofjustice/specialist-publisher
spec/dependency_container_spec.rb
4540
require "spec_helper" require "dependency_container" describe DependencyContainer do class ExampleClass; end it "builds object instances from a factory defined by a passed-in block" do container = DependencyContainer.new container.define_factory(:example) { ExampleClass.new } expect(container.get(:example)).to be_a ExampleClass expect(container.get(:example)).to_not equal container.get(:example) end it "fetches registered object instances" do my_instance = ExampleClass.new container = DependencyContainer.new container.define_instance(:example, my_instance) expect(container.get(:example)).to equal my_instance end it "fetches registered object instances defined by block" do my_instance = ExampleClass.new container = DependencyContainer.new container.define_instance(:example) { my_instance } expect(container.get(:example)).to equal my_instance end it "builds a single instance of singleton factories" do container = DependencyContainer.new container.define_singleton(:example) { ExampleClass.new } expect(container.get(:example)).to be_a ExampleClass expect(container.get(:example)).to equal container.get(:example) end it "allows initial wiring to be defined in block passed to constructor" do container = DependencyContainer.new do define_singleton(:example) { ExampleClass.new } end expect(container.get(:example)).to be_a ExampleClass end describe "#inject_into" do let(:container) { DependencyContainer.new.tap { |c| c.define_singleton(:example) { ExampleClass.new } } } let(:target_class) { Class.new } context "without a visibity option" do it "injects private helper methods for all defined dependencies" do container.inject_into(target_class) expect(target_class.private_instance_methods).to include(:example) expect(target_class.new.send(:example)).to be_a ExampleClass end end context "with visibility option set to public" do it "injects private helper methods for all defined dependencies" do container.inject_into(target_class, visibility: :public) expect(target_class.public_instance_methods).to include(:example) expect(target_class.new.send(:example)).to be_a ExampleClass end end context "with visibility option set to protected" do it "injects protected helper methods for all defined dependencies" do container.inject_into(target_class, visibility: :protected) expect(target_class.protected_instance_methods).to include(:example) expect(target_class.new.send(:example)).to be_a ExampleClass end end end context "a class with a constructor dependency" do before(:all) do class PublishingService attr_reader :logger def initialize(logger) @logger = logger end end MyLogger = Class.new end before(:each) do @container = DependencyContainer.new @container.define_factory(:publishing_service) do PublishingService.new(get(:logger)) end @container.define_factory(:logger) do MyLogger.new end end it "gives the factory access to the container to allow dependencies to be fetched" do publishing_service_instance = @container.get(:publishing_service) expect(publishing_service_instance).to be_a PublishingService expect(publishing_service_instance.logger).to be_a MyLogger end it "can build an object with dependencies based on the initializer's arguments" do @container.define_factory(:another_publishing_service) do build_with_dependencies(PublishingService) end publishing_service_instance = @container.get(:another_publishing_service) expect(publishing_service_instance).to be_a PublishingService expect(publishing_service_instance.logger).to be_a MyLogger end it "can build a Struct with dependencies based on the struct members" do struct = Struct.new(:logger) @container.define_factory(:my_struct) do build_with_dependencies(struct) end instance = @container.get(:my_struct) expect(instance).to be_a struct expect(instance.logger).to be_a MyLogger end it "will set optional dependencies if defined" do my_class = Class.new do def initialize(logger = nil, not_defined = nil) end end @container.define_factory(:test) end end end
mit
oliviertassinari/material-ui
packages/mui-icons-material/lib/AccountCircleOutlined.js
934
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zM7.07 18.28c.43-.9 3.05-1.78 4.93-1.78s4.51.88 4.93 1.78C15.57 19.36 13.86 20 12 20s-3.57-.64-4.93-1.72zm11.29-1.45c-1.43-1.74-4.9-2.33-6.36-2.33s-4.93.59-6.36 2.33C4.62 15.49 4 13.82 4 12c0-4.41 3.59-8 8-8s8 3.59 8 8c0 1.82-.62 3.49-1.64 4.83zM12 6c-1.94 0-3.5 1.56-3.5 3.5S10.06 13 12 13s3.5-1.56 3.5-3.5S13.94 6 12 6zm0 5c-.83 0-1.5-.67-1.5-1.5S11.17 8 12 8s1.5.67 1.5 1.5S12.83 11 12 11z" }), 'AccountCircleOutlined'); exports.default = _default;
mit
cardigann/cardigann
vendor/github.com/bcampbell/fuzzytime/datetime.go
1739
package fuzzytime // DateTime represents a set of fields for date and time, any of which may // be unset. The default initialisation is a valid empty datetime with no // fields set. type DateTime struct { Date Time } // Equals returns true if dates and times match func (dt *DateTime) Equals(other *DateTime) bool { return dt.Date.Equals(&other.Date) && dt.Time.Equals(&other.Time) } // String returns "YYYY-MM-DD hh:mm:ss tz" with question marks in place of // any missing values (except for timezone, which will be blank if missing) func (dt *DateTime) String() string { return dt.Date.String() + " " + dt.Time.String() } // Empty tests if datetime is blank (ie all fields unset) func (dt *DateTime) Empty() bool { return dt.Time.Empty() && dt.Date.Empty() } // ISOFormat returns the most precise-possible datetime given the available // data. // Aims for "YYYY-MM-DDTHH:MM:SS+TZ" but will drop off // higher-precision components as required eg "YYYY-MM" func (dt *DateTime) ISOFormat() string { if dt.Time.Empty() { // just the date. return dt.Date.ISOFormat() } return dt.Date.ISOFormat() + "T" + dt.Time.ISOFormat() } // HasFullDate returns true if Year, Month and Day are all set func (dt *DateTime) HasFullDate() bool { return dt.HasYear() && dt.HasMonth() && dt.HasDay() } // Conflicts returns true if the two datetimes conflict. // Note that this is not the same as the two being equal - one // datetime can be more precise than the other. They are only in // conflict if they have different values set for the same field. // eg "2012-01-01T03:34:10" doesn't conflict with "03:34" func (dt *DateTime) Conflicts(other *DateTime) bool { return dt.Time.Conflicts(&other.Time) || dt.Date.Conflicts(&other.Date) }
mit
CaitSith2/ktanemod-twitchplays
Assets/Scripts/Helpers/LogUploader.cs
3929
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using UnityEngine; public class LogUploader : MonoBehaviour { public string log { get; private set; } public IRCConnection ircConnection = null; [HideInInspector] public string analysisUrl = null; [HideInInspector] public bool postOnComplete = false; [HideInInspector] public string LOGPREFIX; private string output; private OrderedDictionary domainNames = new OrderedDictionary { // In order of preference (favourite first) // The integer value is the data size limit in bytes { "hastebin.com", 400000 }, { "ktane.w00ty.com", 2000000 } }; public void OnEnable() { LOGPREFIX = "[" + GetType().Name + "] "; Application.logMessageReceived += HandleLog; } public void OnDisable() { Application.logMessageReceived -= HandleLog; } public void Clear() { log = ""; } public string Flush() { string result = log; log = ""; return result; } public void Post(bool postToChat = true) { analysisUrl = null; postOnComplete = false; StartCoroutine( DoPost(log, postToChat) ); } private IEnumerator DoPost(string data, bool postToChat) { // This first line is necessary as the Log Analyser uses it as an identifier data = "Initialize engine version: Twitch Plays\n" + data; byte[] encodedData = System.Text.Encoding.UTF8.GetBytes(data); int dataLength = encodedData.Length; bool tooLong = false; foreach (DictionaryEntry domain in domainNames) { string domainName = (string)domain.Key; int maxLength = (int)domain.Value; tooLong = false; if (dataLength >= maxLength) { Debug.LogFormat(LOGPREFIX + "Data ({0}B) is too long for {1} ({2}B)", dataLength, domainName, maxLength); tooLong = true; continue; } Debug.Log(LOGPREFIX + "Posting new log to " + domainName); string url = "https://" + domainName + "/documents"; WWW www = new WWW(url, encodedData); yield return www; if (www.error == null) { // example result // {"key":"oxekofidik"} string key = www.text; key = key.Substring(0, key.Length - 2); key = key.Substring(key.LastIndexOf("\"") + 1); string rawUrl = "https://" + domainName + "/raw/" + key; Debug.Log(LOGPREFIX + "Paste now available at " + rawUrl); analysisUrl = TwitchPlaysService.urlHelper.LogAnalyserFor(rawUrl); if (postOnComplete) { PostToChat(); } break; } else { Debug.Log(LOGPREFIX + "Error: " + www.error); } } if (tooLong) { ircConnection.SendMessage("BibleThump The bomb log is too big to upload to any of the supported services, sorry!"); } yield break; } public bool PostToChat(string format = "Analysis for this bomb: {0}", string emote = "copyThis") { if (string.IsNullOrEmpty(analysisUrl)) { Debug.Log(LOGPREFIX + "No analysis URL available, can't post to chat"); return false; } Debug.Log(LOGPREFIX + "Posting analysis URL to chat"); emote = " " + emote + " "; ircConnection.SendMessage(string.Format(emote + format, analysisUrl)); return true; } private void HandleLog(string message, string stackTrace, LogType type) { log += message + "\n"; } }
mit
Seeed-Studio/DSOQuad_SourceCode
SYS_V1.50/include/USB_pwr.h
2202
/******************** (C) COPYRIGHT 2008 STMicroelectronics ******************** * File Name : usb_pwr.h * Author : MCD Application Team * Version : V2.2.1 * Date : 09/22/2008 * Description : Connection/disconnection & power management header ******************************************************************************** * THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME. * AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT, * INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE * CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING * INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS. *******************************************************************************/ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __USB_PWR_H #define __USB_PWR_H /* Includes ------------------------------------------------------------------*/ #include "usb_core.h" /* Exported types ------------------------------------------------------------*/ typedef enum _RESUME_STATE { RESUME_EXTERNAL, RESUME_INTERNAL, RESUME_LATER, RESUME_WAIT, RESUME_START, RESUME_ON, RESUME_OFF, RESUME_ESOF } RESUME_STATE; typedef enum _DEVICE_STATE { UNCONNECTED, ATTACHED, POWERED, SUSPENDED, ADDRESSED, CONFIGURED } DEVICE_STATE; /* Exported constants --------------------------------------------------------*/ /* Exported macro ------------------------------------------------------------*/ /* Exported functions ------------------------------------------------------- */ void Suspend(void); void Resume_Init(void); void Resume(RESUME_STATE eResumeSetVal); RESULT PowerOn(void); RESULT PowerOff(void); /* External variables --------------------------------------------------------*/ extern vu32 bDeviceState; /* USB device status */ extern volatile bool fSuspendEnabled; /* true when suspend is possible */ #endif /*__USB_PWR_H*/ /******************* (C) COPYRIGHT 2008 STMicroelectronics *****END OF FILE****/
mit
pietermartin/sqlg
sqlg-test/src/main/java/org/umlg/sqlg/test/graph/TestGraphStepWithIds.java
2943
package org.umlg.sqlg.test.graph; import org.apache.tinkerpop.gremlin.structure.Edge; import org.apache.tinkerpop.gremlin.structure.T; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.junit.Assert; import org.junit.Test; import org.umlg.sqlg.test.BaseTest; import java.util.List; /** * Date: 2015/11/18 * Time: 8:47 AM */ public class TestGraphStepWithIds extends BaseTest { @Test public void testGraphWithIds() { Vertex a1 = this.sqlgGraph.addVertex(T.label, "A"); Vertex a2 = this.sqlgGraph.addVertex(T.label, "A"); Vertex a3 = this.sqlgGraph.addVertex(T.label, "A"); this.sqlgGraph.tx().commit(); List<Vertex> vertices = this.sqlgGraph.traversal().V(a1.id()).toList(); Assert.assertEquals(1, vertices.size()); Assert.assertEquals(a1, vertices.get(0)); vertices = this.sqlgGraph.traversal().V(a1).toList(); Assert.assertEquals(1, vertices.size()); Assert.assertEquals(a1, vertices.get(0)); } @Test public void testGraphWithIdsGroupingOfIdsAccordingToLabel() { Vertex a1 = this.sqlgGraph.addVertex(T.label, "A", "name", "a1"); Vertex a2 = this.sqlgGraph.addVertex(T.label, "A", "name", "a2"); Vertex b1 = this.sqlgGraph.addVertex(T.label, "B", "name", "b1"); Vertex b2 = this.sqlgGraph.addVertex(T.label, "B", "name", "b2"); Vertex b3 = this.sqlgGraph.addVertex(T.label, "B", "name", "b3"); Vertex c1 = this.sqlgGraph.addVertex(T.label, "C", "name", "c1"); Edge e1 = b3.addEdge("bc", c1); this.sqlgGraph.tx().commit(); List<Vertex> vertices = this.sqlgGraph.traversal().V(new Object[]{a1, a2, b1, b2, b3}).toList(); Assert.assertEquals(5, vertices.size()); vertices = this.sqlgGraph.traversal().V(new Object[]{a1, a2, b1, b2, b3}).outE().outV().toList(); Assert.assertEquals(1, vertices.size()); List<Object> values =this.sqlgGraph.traversal().E(e1.id()).inV().values("name").toList(); Assert.assertEquals(1, values.size()); } @Test(expected = IllegalArgumentException.class) public void shouldThrowExceptionIfIdsAreMixed() { Vertex a1 = this.sqlgGraph.addVertex(T.label, "A", "name", "a1"); Vertex b1 = this.sqlgGraph.addVertex(T.label, "B", "name", "b1"); Vertex c1 = this.sqlgGraph.addVertex(T.label, "C", "name", "c1"); Edge e1 = b1.addEdge("bc", c1); this.sqlgGraph.tx().commit(); List<Vertex> vertices = this.sqlgGraph.traversal().V(new Object[]{a1, b1.id()}).toList(); } @Test public void testIdAndHasLabel() { Vertex a1 = this.sqlgGraph.addVertex(T.label, "A", "name", "a1"); this.sqlgGraph.tx().commit(); List<Vertex> vertices = this.sqlgGraph.traversal().V(a1).hasLabel("A").toList(); Assert.assertEquals(1, vertices.size()); Assert.assertTrue(vertices.contains(a1)); } }
mit
Raina4uberz/Showdown-light
data/abilities.js
120010
/* Ratings and how they work: -2: Extremely detrimental The sort of ability that relegates Pokemon with Uber-level BSTs into NU. ex. Slow Start, Truant -1: Detrimental An ability that does more harm than good. ex. Defeatist, Normalize 0: Useless An ability with no net effect on a Pokemon during a battle. ex. Pickup, Illuminate 1: Ineffective An ability that has a minimal effect. Should never be chosen over any other ability. ex. Damp, Shell Armor 2: Situationally useful An ability that can be useful in certain situations. ex. Blaze, Insomnia 3: Useful An ability that is generally useful. ex. Volt Absorb, Iron Fist 4: Very useful One of the most popular abilities. The difference between 3 and 4 can be ambiguous. ex. Technician, Protean 5: Essential The sort of ability that defines metagames. ex. Drizzle, Shadow Tag */ exports.BattleAbilities = { "adaptability": { desc: "This Pokemon's attacks that receive STAB (Same Type Attack Bonus) are increased from 50% to 100%.", shortDesc: "This Pokemon's same-type attack bonus (STAB) is increased from 1.5x to 2x.", onModifyMove: function (move) { move.stab = 2; }, id: "adaptability", name: "Adaptability", rating: 3.5, num: 91 }, "aftermath": { desc: "If a contact move knocks out this Pokemon, the opponent receives damage equal to one-fourth of its max HP.", shortDesc: "If this Pokemon is KOed with a contact move, that move's user loses 1/4 its max HP.", id: "aftermath", name: "Aftermath", onAfterDamageOrder: 1, onAfterDamage: function (damage, target, source, move) { if (source && source !== target && move && move.isContact && !target.hp) { this.damage(source.maxhp / 4, source, target, null, true); } }, rating: 3, num: 106 }, "aerilate": { desc: "Turns all of this Pokemon's Normal-typed attacks into Flying-type and deal 1.3x damage. Does not affect Hidden Power.", shortDesc: "This Pokemon's Normal moves become Flying-type and do 1.3x damage.", onModifyMove: function (move, pokemon) { if (move.type === 'Normal' && move.id !== 'hiddenpower') { move.type = 'Flying'; if (move.category !== 'Status') pokemon.addVolatile('aerilate'); } }, effect: { duration: 1, onBasePowerPriority: 8, onBasePower: function (basePower, pokemon, target, move) { return this.chainModify([0x14CD, 0x1000]); } }, id: "aerilate", name: "Aerilate", rating: 3, num: 185 }, "airlock": { desc: "While this Pokemon is active, all weather conditions and their effects are disabled.", shortDesc: "While this Pokemon is active, all weather conditions and their effects are disabled.", onStart: function (pokemon) { this.add('-ability', pokemon, 'Air Lock'); }, onAnyModifyPokemon: function (pokemon) { pokemon.ignore['WeatherTarget'] = true; }, onAnyTryWeather: false, id: "airlock", name: "Air Lock", rating: 3, num: 76 }, "analytic": { desc: "This Pokemon's attacks do 1.3x damage if it is the last to move in a turn.", shortDesc: "If the user moves last, the power of that move is increased by 30%.", onBasePowerPriority: 8, onBasePower: function (basePower, attacker, defender, move) { if (!this.willMove(defender)) { this.debug('Analytic boost'); return this.chainModify([0x14CD, 0x1000]); // The Analytic modifier is slightly higher than the normal 1.3 (0x14CC) } }, id: "analytic", name: "Analytic", rating: 1, num: 148 }, "angerpoint": { desc: "If this Pokemon, and not its Substitute, is struck by a Critical Hit, its Attack is boosted to six stages.", shortDesc: "If this Pokemon is hit by a critical hit, its Attack is boosted by 12.", onCriticalHit: function (target) { if (!target.volatiles['substitute']) { target.setBoost({atk: 6}); this.add('-setboost', target, 'atk', 12, '[from] ability: Anger Point'); } }, id: "angerpoint", name: "Anger Point", rating: 2, num: 83 }, "anticipation": { desc: "A warning is displayed if an opposing Pokemon has the moves Fissure, Guillotine, Horn Drill, Sheer Cold, or any attacking move from a type that is considered super effective against this Pokemon (including Counter, Mirror Coat, and Metal Burst). Hidden Power, Judgment, Natural Gift and Weather Ball are considered Normal-type moves. Flying Press is considered a Fighting-type move.", shortDesc: "On switch-in, this Pokemon shudders if any foe has a super effective or OHKO move.", onStart: function (pokemon) { var targets = pokemon.side.foe.active; for (var i = 0; i < targets.length; i++) { if (!targets[i] || targets[i].fainted) continue; for (var j = 0; j < targets[i].moveset.length; j++) { var move = this.getMove(targets[i].moveset[j].move); if (move.category !== 'Status' && (this.getImmunity(move.type, pokemon) && this.getEffectiveness(move.type, pokemon) > 0 || move.ohko)) { this.add('-activate', pokemon, 'ability: Anticipation'); return; } } } }, id: "anticipation", name: "Anticipation", rating: 1, num: 107 }, "arenatrap": { desc: "When this Pokemon enters the field, its opponents cannot switch or flee the battle unless they are part Flying-type, have the Levitate ability, are holding Shed Shell, or they use the moves Baton Pass or U-Turn. Flying-type and Levitate Pokemon cannot escape if they are holding Iron Ball or Gravity is in effect. Levitate Pokemon also cannot escape if their ability is disabled through other means, such as Skill Swap or Gastro Acid.", shortDesc: "Prevents foes from switching out normally unless they have immunity to Ground.", onFoeModifyPokemon: function (pokemon) { if (!this.isAdjacent(pokemon, this.effectData.target)) return; if (!pokemon.runImmunity('Ground', false)) return; if (!pokemon.hasType('Flying') || pokemon.hasType('ironball') || this.getPseudoWeather('gravity') || pokemon.volatiles['ingrain']) { pokemon.tryTrap(true); } }, onFoeMaybeTrapPokemon: function (pokemon, source) { if (!source) source = this.effectData.target; if (!this.isAdjacent(pokemon, source)) return; if (!pokemon.runImmunity('Ground', false)) return; if (!pokemon.hasType('Flying') || pokemon.hasType('ironball') || this.getPseudoWeather('gravity') || pokemon.volatiles['ingrain']) { pokemon.maybeTrapped = true; } }, id: "arenatrap", name: "Arena Trap", rating: 5, num: 71 }, "aromaveil": { desc: "Protects this Pokemon and its allies from Attract, Disable, Encore, Heal Block, Taunt, and Torment.", shortDesc: "Protects from Attract, Disable, Encore, Heal Block, Taunt, and Torment.", onAllyTryHit: function (target, source, move) { if (move && move.id in {attract:1, disable:1, encore:1, healblock:1, taunt:1, torment:1}) { return false; } }, id: "aromaveil", name: "Aroma Veil", rating: 3, num: 165 }, "aurabreak": { desc: "Reverses the effect of Dark Aura and Fairy Aura.", shortDesc: "Reverses the effect of Aura abilities.", onStart: function (pokemon) { this.add('-ability', pokemon, 'Aura Break'); }, onAnyTryPrimaryHit: function (target, source, move) { if (target === source || move.category === 'Status') return; source.addVolatile('aurabreak'); }, effect: { duration: 1 }, id: "aurabreak", name: "Aura Break", rating: 2, num: 188 }, "baddreams": { desc: "If asleep, each of this Pokemon's opponents receives damage equal to one-eighth of its max HP.", shortDesc: "Causes sleeping adjacent foes to lose 1/8 of their max HP at the end of each turn.", onResidualOrder: 26, onResidualSubOrder: 1, onResidual: function (pokemon) { if (!pokemon.hp) return; for (var i = 0; i < pokemon.side.foe.active.length; i++) { var target = pokemon.side.foe.active[i]; if (!target || !target.hp) continue; if (target.status === 'slp') { this.damage(target.maxhp / 8, target); } } }, id: "baddreams", name: "Bad Dreams", rating: 2, num: 123 }, "battlearmor": { desc: "This Pokemon cannot be struck by a critical hit.", shortDesc: "Critical Hits cannot strike this Pokemon.", onCriticalHit: false, id: "battlearmor", name: "Battle Armor", rating: 1, num: 4 }, "bigpecks": { desc: "Prevents other Pokemon from lowering this Pokemon's Defense.", shortDesc: "Prevents the Pokemon's Defense stat from being reduced.", onBoost: function (boost, target, source, effect) { if (source && target === source) return; if (boost['def'] && boost['def'] < 0) { boost['def'] = 0; if (!effect.secondaries) this.add("-fail", target, "unboost", "Defense", "[from] ability: Big Pecks", "[of] " + target); } }, id: "bigpecks", name: "Big Pecks", rating: 1, num: 145 }, "blaze": { desc: "When its health reaches one-third or less of its max HP, this Pokemon's Fire-type attacks receive a 50% boost in power.", shortDesc: "When this Pokemon has 1/3 or less of its max HP, its Fire attacks do 1.5x damage.", onModifyAtkPriority: 5, onModifyAtk: function (atk, attacker, defender, move) { if (move.type === 'Fire' && attacker.hp <= attacker.maxhp / 3) { this.debug('Blaze boost'); return this.chainModify(1.5); } }, onModifySpAPriority: 5, onModifySpA: function (atk, attacker, defender, move) { if (move.type === 'Fire' && attacker.hp <= attacker.maxhp / 3) { this.debug('Blaze boost'); return this.chainModify(1.5); } }, id: "blaze", name: "Blaze", rating: 2, num: 66 }, "bulletproof": { desc: "This Pokemon is protected from some Ball and Bomb moves.", shortDesc: "This Pokemon is protected from ball and bomb moves.", onTryHit: function (pokemon, target, move) { if (move.flags && move.flags['bullet']) { this.add('-immune', pokemon, '[msg]', '[from] Bulletproof'); return null; } }, id: "bulletproof", name: "Bulletproof", rating: 3, num: 171 }, "cheekpouch": { desc: "Restores HP when this Pokemon consumes a berry.", shortDesc: "Restores HP when this Pokemon consumes a berry.", onEatItem: function (item, pokemon) { this.heal(pokemon.maxhp / 3); }, id: "cheekpouch", name: "Cheek Pouch", rating: 2, num: 167 }, "chlorophyll": { desc: "If this Pokemon is active while Sunny Day is in effect, its speed is temporarily doubled.", shortDesc: "If Sunny Day is active, this Pokemon's Speed is doubled.", onModifySpe: function (speMod) { if (this.isWeather(['sunnyday', 'desolateland'])) { return this.chain(speMod, 2); } }, id: "chlorophyll", name: "Chlorophyll", rating: 2, num: 34 }, "clearbody": { desc: "Opponents cannot reduce this Pokemon's stats; they can, however, modify stat changes with Power Swap, Guard Swap and Heart Swap and inflict stat boosts with Swagger and Flatter. This ability does not prevent self-inflicted stat reductions.", shortDesc: "Prevents other Pokemon from lowering this Pokemon's stat stages.", onBoost: function (boost, target, source, effect) { if (source && target === source) return; var showMsg = false; for (var i in boost) { if (boost[i] < 0) { delete boost[i]; showMsg = true; } } if (showMsg && !effect.secondaries) this.add("-fail", target, "unboost", "[from] ability: Clear Body", "[of] " + target); }, id: "clearbody", name: "Clear Body", rating: 2, num: 29 }, "cloudnine": { desc: "While this Pokemon is active, all weather conditions and their effects are disabled.", shortDesc: "While this Pokemon is active, all weather conditions and their effects are disabled.", onStart: function (pokemon) { this.add('-ability', pokemon, 'Cloud Nine'); }, onAnyModifyPokemon: function (pokemon) { pokemon.ignore['WeatherTarget'] = true; }, onAnyTryWeather: false, id: "cloudnine", name: "Cloud Nine", rating: 3, num: 13 }, "colorchange": { desc: "This Pokemon's type changes according to the type of the last move that hit this Pokemon.", shortDesc: "This Pokemon's type changes to match the type of the last move that hit it.", onAfterMoveSecondary: function (target, source, move) { if (target.isActive && move && move.effectType === 'Move' && move.category !== 'Status') { if (!target.hasType(move.type)) { if (!target.setType(move.type)) return false; this.add('-start', target, 'typechange', move.type, '[from] Color Change'); target.update(); } } }, id: "colorchange", name: "Color Change", rating: 2, num: 16 }, "competitive": { desc: "Raises the user's Special Attack stat by two stages when a stat is lowered, including the Special Attack stat. This does not include self-induced stat drops like those from Close Combat.", shortDesc: "This Pokemon's SpAtk is boosted by 2 for each of its stats that is lowered by a foe.", onAfterEachBoost: function (boost, target, source) { if (!source || target.side === source.side) { return; } var statsLowered = false; for (var i in boost) { if (boost[i] < 0) { statsLowered = true; } } if (statsLowered) { this.boost({spa: 2}); } }, id: "competitive", name: "Competitive", rating: 2, num: 172 }, "compoundeyes": { desc: "The accuracy of this Pokemon's moves receives a 30% increase; for example, a 75% accurate move becomes 97.5% accurate.", shortDesc: "This Pokemon's moves have their accuracy boosted to 1.3x.", onSourceAccuracy: function (accuracy) { if (typeof accuracy !== 'number') return; this.debug('compoundeyes - enhancing accuracy'); return accuracy * 1.3; }, id: "compoundeyes", name: "Compound Eyes", rating: 3.5, num: 14 }, "contrary": { desc: "If this Pokemon has a stat boosted it is lowered instead, and vice versa.", shortDesc: "Stat changes are inverted.", onBoost: function (boost) { for (var i in boost) { boost[i] *= -1; } }, id: "contrary", name: "Contrary", rating: 4, num: 126 }, "cursedbody": { desc: "30% chance of disabling one of the opponent's moves when attacked. This works even if the attacker is behind a Substitute, but will not activate if the Pokemon with Cursed Body is behind a Substitute.", shortDesc: "If this Pokemon is hit by an attack, there is a 30% chance that move gets Disabled.", onAfterDamage: function (damage, target, source, move) { if (!source || source.volatiles['disable']) return; if (source !== target && move && move.effectType === 'Move') { if (this.random(10) < 3) { source.addVolatile('disable'); } } }, id: "cursedbody", name: "Cursed Body", rating: 2, num: 130 }, "cutecharm": { desc: "If an opponent of the opposite gender directly attacks this Pokemon, there is a 30% chance that the opponent will become Attracted to this Pokemon.", shortDesc: "30% chance of infatuating Pokemon of the opposite gender if they make contact.", onAfterDamage: function (damage, target, source, move) { if (move && move.isContact) { if (this.random(10) < 3) { source.addVolatile('attract', target); } } }, id: "cutecharm", name: "Cute Charm", rating: 1, num: 56 }, "damp": { desc: "While this Pokemon is active, no Pokemon on the field can use Selfdestruct or Explosion.", shortDesc: "While this Pokemon is active, Selfdestruct, Explosion, and Aftermath do not work.", id: "damp", onAnyTryMove: function (target, source, effect) { if (effect.id === 'selfdestruct' || effect.id === 'explosion') { this.attrLastMove('[still]'); this.add('-activate', this.effectData.target, 'ability: Damp'); return false; } }, onAnyDamage: function (damage, target, source, effect) { if (effect && effect.id === 'aftermath') { return false; } }, name: "Damp", rating: 0.5, num: 6 }, "darkaura": { desc: "Increases the power of all Dark-type moves in battle to 1.33x.", shortDesc: "Increases the power of all Dark-type moves in battle to 1.33x.", onStart: function (pokemon) { this.add('-ability', pokemon, 'Dark Aura'); }, onAnyTryPrimaryHit: function (target, source, move) { if (target === source || move.category === 'Status') return; if (move.type === 'Dark') { source.addVolatile('aura'); } }, id: "darkaura", name: "Dark Aura", rating: 3, num: 186 }, "defeatist": { desc: "When this Pokemon has 1/2 or less of its max HP, its Attack and Sp. Atk are halved.", shortDesc: "Attack and Special Attack are halved when HP is less than half.", onModifyAtkPriority: 5, onModifyAtk: function (atk, pokemon) { if (pokemon.hp < pokemon.maxhp / 2) { return this.chainModify(0.5); } }, onModifySpAPriority: 5, onModifySpA: function (atk, pokemon) { if (pokemon.hp < pokemon.maxhp / 2) { return this.chainModify(0.5); } }, onResidual: function (pokemon) { pokemon.update(); }, id: "defeatist", name: "Defeatist", rating: -1, num: 129 }, "defiant": { desc: "Raises the user's Attack stat by two stages when a stat is lowered, including the Attack stat. This does not include self-induced stat drops like those from Close Combat.", shortDesc: "This Pokemon's Attack is boosted by 2 for each of its stats that is lowered by a foe.", onAfterEachBoost: function (boost, target, source) { if (!source || target.side === source.side) { return; } var statsLowered = false; for (var i in boost) { if (boost[i] < 0) { statsLowered = true; } } if (statsLowered) { this.boost({atk: 2}); } }, id: "defiant", name: "Defiant", rating: 2, num: 128 }, "deltastream": { desc: "When this Pokemon enters the battlefield, the weather becomes strong winds for as long as this Pokemon remains on the battlefield with Delta Stream.", shortDesc: "The weather becomes strong winds until this Pokemon leaves battle.", onStart: function (source) { this.setWeather('deltastream'); }, onEnd: function (pokemon) { if (this.weatherData.source !== pokemon) return; for (var i = 0; i < this.sides.length; i++) { for (var j = 0; j < this.sides[i].active.length; j++) { var target = this.sides[i].active[j]; if (target === pokemon) continue; if (target && target.hp && target.ability === 'deltastream' && target.ignore['Ability'] !== true) { this.weatherData.source = target; return; } } } this.clearWeather(); }, id: "deltastream", name: "Delta Stream", rating: 5, num: 191 }, "desolateland": { desc: "When this Pokemon enters the battlefield, the weather becomes harsh sun for as long as this Pokemon remains on the battlefield with Desolate Land.", shortDesc: "The weather becomes harsh sun until this Pokemon leaves battle.", onStart: function (source) { this.setWeather('desolateland'); }, onEnd: function (pokemon) { if (this.weatherData.source !== pokemon) return; for (var i = 0; i < this.sides.length; i++) { for (var j = 0; j < this.sides[i].active.length; j++) { var target = this.sides[i].active[j]; if (target === pokemon) continue; if (target && target.hp && target.ability === 'desolateland' && target.ignore['Ability'] !== true) { this.weatherData.source = target; return; } } } this.clearWeather(); }, id: "desolateland", name: "Desolate Land", rating: 5, num: 190 }, "download": { desc: "If this Pokemon switches into an opponent with equal Defenses or higher Defense than Special Defense, this Pokemon's Special Attack receives a 50% boost. If this Pokemon switches into an opponent with higher Special Defense than Defense, this Pokemon's Attack receive a 50% boost.", shortDesc: "On switch-in, Attack or Sp. Atk is boosted by 1 based on the foes' weaker Defense.", onStart: function (pokemon) { var foeactive = pokemon.side.foe.active; var totaldef = 0; var totalspd = 0; for (var i = 0; i < foeactive.length; i++) { if (!foeactive[i] || foeactive[i].fainted) continue; totaldef += foeactive[i].getStat('def', false, true); totalspd += foeactive[i].getStat('spd', false, true); } if (totaldef && totaldef >= totalspd) { this.boost({spa:1}); } else if (totalspd) { this.boost({atk:1}); } }, id: "download", name: "Download", rating: 4, num: 88 }, "drizzle": { desc: "When this Pokemon enters the battlefield, the weather becomes Rain Dance (for 5 turns normally, or 8 turns while holding Damp Rock).", shortDesc: "On switch-in, the weather becomes Rain Dance.", onStart: function (source) { if (this.isWeather(['desolateland', 'primordialsea', 'deltastream'])) { this.add('-ability', source, 'Drizzle', '[from] ' + this.effectiveWeather(), '[fail]'); return null; } this.setWeather('raindance'); }, id: "drizzle", name: "Drizzle", rating: 5, num: 2 }, "drought": { desc: "When this Pokemon enters the battlefield, the weather becomes Sunny Day (for 5 turns normally, or 8 turns while holding Heat Rock).", shortDesc: "On switch-in, the weather becomes Sunny Day.", onStart: function (source) { if (this.isWeather(['desolateland', 'primordialsea', 'deltastream'])) { this.add('-ability', source, 'Drought', '[from] ' + this.effectiveWeather(), '[fail]'); return null; } this.setWeather('sunnyday'); }, id: "drought", name: "Drought", rating: 5, num: 70 }, "dryskin": { desc: "This Pokemon absorbs Water attacks and gains a weakness to Fire attacks. If Sunny Day is in effect, this Pokemon takes damage. If Rain Dance is in effect, this Pokemon recovers health.", shortDesc: "This Pokemon is healed 1/4 by Water, 1/8 by Rain; is hurt 1.25x by Fire, 1/8 by Sun.", onTryHit: function (target, source, move) { if (target !== source && move.type === 'Water') { if (!this.heal(target.maxhp / 4)) { this.add('-immune', target, '[msg]'); } return null; } }, onBasePowerPriority: 7, onFoeBasePower: function (basePower, attacker, defender, move) { if (this.effectData.target !== defender) return; if (move.type === 'Fire') { return this.chainModify(1.25); } }, onWeather: function (target, source, effect) { if (effect.id === 'raindance' || effect.id === 'primordialsea') { this.heal(target.maxhp / 8); } else if (effect.id === 'sunnyday' || effect.id === 'desolateland') { this.damage(target.maxhp / 8); } }, id: "dryskin", name: "Dry Skin", rating: 3.5, num: 87 }, "earlybird": { desc: "This Pokemon will remain asleep for half as long as it normally would; this includes both opponent-induced sleep and user-induced sleep via Rest.", shortDesc: "This Pokemon's sleep status lasts half as long as usual, self-induced or not.", id: "earlybird", name: "Early Bird", isHalfSleep: true, rating: 2.5, num: 48 }, "effectspore": { desc: "If an opponent directly attacks this Pokemon, there is a 30% chance that the opponent will become either poisoned, paralyzed or put to sleep. There is an equal chance to inflict each status.", shortDesc: "30% chance of poisoning, paralyzing, or causing sleep on Pokemon making contact.", onAfterDamage: function (damage, target, source, move) { if (move && move.isContact && !source.status && source.runImmunity('powder')) { var r = this.random(100); if (r < 11) { source.setStatus('slp', target); } else if (r < 21) { source.setStatus('par', target); } else if (r < 30) { source.setStatus('psn', target); } } }, id: "effectspore", name: "Effect Spore", rating: 2, num: 27 }, "fairyaura": { desc: "Increases the power of all Fairy-type moves in battle to 1.33x.", shortDesc: "Increases the power of all Fairy-type moves in battle to 1.33x.", onStart: function (pokemon) { this.add('-ability', pokemon, 'Fairy Aura'); }, onAnyTryPrimaryHit: function (target, source, move) { if (target === source || move.category === 'Status') return; if (move.type === 'Fairy') { source.addVolatile('aura'); } }, id: "fairyaura", name: "Fairy Aura", rating: 3, num: 187 }, "filter": { desc: "This Pokemon receives one-fourth reduced damage from Super Effective attacks.", shortDesc: "This Pokemon receives 3/4 damage from super effective attacks.", onSourceModifyDamage: function (damage, source, target, move) { if (target.runEffectiveness(move) > 0) { this.debug('Filter neutralize'); return this.chainModify(0.75); } }, id: "filter", name: "Filter", rating: 3, num: 111 }, "flamebody": { desc: "If an opponent directly attacks this Pokemon, there is a 30% chance that the opponent will become burned.", shortDesc: "30% chance of burning a Pokemon making contact with this Pokemon.", onAfterDamage: function (damage, target, source, move) { if (move && move.isContact) { if (this.random(10) < 3) { source.trySetStatus('brn', target, move); } } }, id: "flamebody", name: "Flame Body", rating: 2, num: 49 }, "flareboost": { desc: "When the user with this ability is burned, its Special Attack is raised by 50%.", shortDesc: "When this Pokemon is burned, its special attacks do 1.5x damage.", onBasePowerPriority: 8, onBasePower: function (basePower, attacker, defender, move) { if (attacker.status === 'brn' && move.category === 'Special') { return this.chainModify(1.5); } }, id: "flareboost", name: "Flare Boost", rating: 3, num: 138 }, "flashfire": { desc: "This Pokemon is immune to all Fire-type attacks; additionally, its own Fire-type attacks receive a 50% boost if a Fire-type move hits this Pokemon. Multiple boosts do not occur if this Pokemon is hit with multiple Fire-type attacks.", shortDesc: "This Pokemon's Fire attacks do 1.5x damage if hit by one Fire move; Fire immunity.", onTryHit: function (target, source, move) { if (target !== source && move.type === 'Fire') { move.accuracy = true; if (!target.addVolatile('flashfire')) { this.add('-immune', target, '[msg]'); } return null; } }, effect: { noCopy: true, // doesn't get copied by Baton Pass onStart: function (target) { this.add('-start', target, 'ability: Flash Fire'); }, onModifyAtkPriority: 5, onModifyAtk: function (atk, attacker, defender, move) { if (move.type === 'Fire') { this.debug('Flash Fire boost'); return this.chainModify(1.5); } }, onModifySpAPriority: 5, onModifySpA: function (atk, attacker, defender, move) { if (move.type === 'Fire') { this.debug('Flash Fire boost'); return this.chainModify(1.5); } } }, id: "flashfire", name: "Flash Fire", rating: 3, num: 18 }, "flowergift": { desc: "If this Pokemon is active while Sunny Day is in effect, its Attack and Special Defense stats (as well as its partner's stats in double battles) receive a 50% boost.", shortDesc: "If user is Cherrim and Sunny Day is active, it and allies' Attack and Sp. Def are 1.5x.", onStart: function (pokemon) { delete this.effectData.forme; }, onUpdate: function (pokemon) { if (!pokemon.isActive || pokemon.speciesid !== 'cherrim') return; if (this.isWeather(['sunnyday', 'desolateland'])) { if (this.effectData.forme !== 'Sunshine') { this.effectData.forme = 'Sunshine'; this.add('-formechange', pokemon, 'Cherrim-Sunshine', '[msg]'); } } else { if (this.effectData.forme) { delete this.effectData.forme; this.add('-formechange', pokemon, 'Cherrim', '[msg]'); } } }, onModifyAtkPriority: 3, onAllyModifyAtk: function (atk) { if (this.effectData.target.template.speciesid !== 'cherrim') return; if (this.isWeather(['sunnyday', 'desolateland'])) { return this.chainModify(1.5); } }, onModifySpDPriority: 4, onAllyModifySpD: function (spd) { if (this.effectData.target.template.speciesid !== 'cherrim') return; if (this.isWeather(['sunnyday', 'desolateland'])) { return this.chainModify(1.5); } }, id: "flowergift", name: "Flower Gift", rating: 3, num: 122 }, "flowerveil": { desc: "Prevents ally Grass-type Pokemon from being statused or having their stats lowered.", shortDesc: "Prevents lowering of ally Grass-type Pokemon's stats.", onAllyBoost: function (boost, target, source, effect) { if ((source && target === source) || !target.hasType('Grass')) return; var showMsg = false; for (var i in boost) { if (boost[i] < 0) { delete boost[i]; showMsg = true; } } if (showMsg && !effect.secondaries) this.add("-fail", target, "unboost", "[from] ability: Flower Veil", "[of] " + target); }, onAllySetStatus: function (status, target) { if (target.hasType('Grass')) return false; }, id: "flowerveil", name: "Flower Veil", rating: 0, num: 166 }, "forecast": { desc: "This Pokemon's type changes according to the current weather conditions: it becomes Fire-type during Sunny Day, Water-type during Rain Dance, Ice-type during Hail and remains its regular type otherwise.", shortDesc: "Castform's type changes to the current weather condition's type, except Sandstorm.", onUpdate: function (pokemon) { if (pokemon.baseTemplate.species !== 'Castform' || pokemon.transformed) return; var forme = null; switch (this.effectiveWeather()) { case 'sunnyday': case 'desolateland': if (pokemon.template.speciesid !== 'castformsunny') forme = 'Castform-Sunny'; break; case 'raindance': case 'primordialsea': if (pokemon.template.speciesid !== 'castformrainy') forme = 'Castform-Rainy'; break; case 'hail': if (pokemon.template.speciesid !== 'castformsnowy') forme = 'Castform-Snowy'; break; default: if (pokemon.template.speciesid !== 'castform') forme = 'Castform'; break; } if (pokemon.isActive && forme) { pokemon.formeChange(forme); this.add('-formechange', pokemon, forme, '[msg]'); } }, id: "forecast", name: "Forecast", rating: 4, num: 59 }, "forewarn": { desc: "On switch-in, this Pokemon is alerted to the foes' move with the highest Base Power.", shortDesc: "The move with the highest Base Power in the opponent's moveset is revealed.", onStart: function (pokemon) { var targets = pokemon.side.foe.active; var warnMoves = []; var warnBp = 1; for (var i = 0; i < targets.length; i++) { if (targets[i].fainted) continue; for (var j = 0; j < targets[i].moveset.length; j++) { var move = this.getMove(targets[i].moveset[j].move); var bp = move.basePower; if (move.ohko) bp = 160; if (move.id === 'counter' || move.id === 'metalburst' || move.id === 'mirrorcoat') bp = 120; if (!bp && move.category !== 'Status') bp = 80; if (bp > warnBp) { warnMoves = [[move, targets[i]]]; warnBp = bp; } else if (bp === warnBp) { warnMoves.push([move, targets[i]]); } } } if (!warnMoves.length) return; var warnMove = warnMoves[this.random(warnMoves.length)]; this.add('-activate', pokemon, 'ability: Forewarn', warnMove[0], warnMove[1]); }, id: "forewarn", name: "Forewarn", rating: 1, num: 108 }, "friendguard": { desc: "Reduces the damage received from an ally in a double or triple battle.", shortDesc: "This Pokemon's allies receive 3/4 damage from other Pokemon's attacks.", id: "friendguard", name: "Friend Guard", onAnyModifyDamage: function (damage, source, target, move) { if (target !== this.effectData.target && target.side === this.effectData.target.side) { this.debug('Friend Guard weaken'); return this.chainModify(0.75); } }, rating: 0, num: 132 }, "frisk": { desc: "When this Pokemon enters the field, it identifies all the opponent's held items.", shortDesc: "On switch-in, this Pokemon identifies the foe's held items.", onStart: function (pokemon) { var foeactive = pokemon.side.foe.active; for (var i = 0; i < foeactive.length; i++) { if (!foeactive[i] || foeactive[i].fainted) continue; if (foeactive[i].item) { this.add('-item', foeactive[i], foeactive[i].getItem().name, '[from] ability: Frisk', '[of] ' + pokemon, '[identify]'); } } }, id: "frisk", name: "Frisk", rating: 1.5, num: 119 }, "furcoat": { desc: "This Pokemon's Defense is doubled.", shortDesc: "This Pokemon's Defense is doubled.", onModifyDefPriority: 6, onModifyDef: function (def) { return this.chainModify(2); }, id: "furcoat", name: "Fur Coat", rating: 3.5, num: 169 }, "galewings": { desc: "This Pokemon's Flying-type moves have their priority increased by 1.", shortDesc: "Gives priority to Flying-type moves.", onModifyPriority: function (priority, pokemon, target, move) { if (move && move.type === 'Flying') return priority + 1; }, id: "galewings", name: "Gale Wings", rating: 4.5, num: 177 }, "gluttony": { desc: "This Pokemon consumes its held berry when its health reaches 50% max HP or lower.", shortDesc: "When this Pokemon has 1/2 or less of its max HP, it uses certain Berries early.", id: "gluttony", name: "Gluttony", rating: 1.5, num: 82 }, "gooey": { desc: "Contact with this Pokemon lowers the attacker's Speed stat by 1.", shortDesc: "Contact with this Pokemon lowers the attacker's Speed.", onAfterDamage: function (damage, target, source, effect) { if (effect && effect.isContact) this.boost({spe: -1}, source, target); }, id: "gooey", name: "Gooey", rating: 3, num: 183 }, "grasspelt": { desc: "This Pokemon's Defense is boosted in Grassy Terrain.", shortDesc: "This Pokemon's Defense is boosted in Grassy Terrain.", onModifyDefPriority: 6, onModifyDef: function (pokemon) { if (this.isTerrain('grassyterrain')) return this.chainModify(1.5); }, id: "grasspelt", name: "Grass Pelt", rating: 2, num: 179 }, "guts": { desc: "When this Pokemon is poisoned (including Toxic), burned, paralyzed or asleep (including self-induced Rest), its Attack stat receives a 50% boost; the burn status' Attack drop is also ignored.", shortDesc: "If this Pokemon is statused, its Attack is 1.5x; burn's Attack drop is ignored.", onModifyAtkPriority: 5, onModifyAtk: function (atk, pokemon) { if (pokemon.status) { return this.chainModify(1.5); } }, id: "guts", name: "Guts", rating: 3, num: 62 }, "harvest": { desc: "When the user uses a held Berry, it has a 50% chance of having it restored at the end of the turn. This chance becomes 100% during Sunny Day.", shortDesc: "50% chance this Pokemon's Berry is restored at the end of each turn. 100% in Sun.", id: "harvest", name: "Harvest", onResidualOrder: 26, onResidualSubOrder: 1, onResidual: function (pokemon) { if (this.isWeather(['sunnyday', 'desolateland']) || this.random(2) === 0) { if (pokemon.hp && !pokemon.item && this.getItem(pokemon.lastItem).isBerry) { pokemon.setItem(pokemon.lastItem); this.add('-item', pokemon, pokemon.getItem(), '[from] ability: Harvest'); } } }, rating: 2, num: 139 }, "healer": { desc: "Has a 30% chance of curing an adjacent ally's status ailment at the end of each turn in Double and Triple Battles.", shortDesc: "30% chance of curing an adjacent ally's status at the end of each turn.", id: "healer", name: "Healer", onResidualOrder: 5, onResidualSubOrder: 1, onResidual: function (pokemon) { var allyActive = pokemon.side.active; if (allyActive.length === 1) { return; } for (var i = 0; i < allyActive.length; i++) { if (allyActive[i] && this.isAdjacent(pokemon, allyActive[i]) && allyActive[i].status && this.random(10) < 3) { allyActive[i].cureStatus(); } } }, rating: 0, num: 131 }, "heatproof": { desc: "This Pokemon receives half damage from both Fire-type attacks and residual burn damage.", shortDesc: "This Pokemon receives half damage from Fire-type attacks and burn damage.", onBasePowerPriority: 7, onSourceBasePower: function (basePower, attacker, defender, move) { if (move.type === 'Fire') { return this.chainModify(0.5); } }, onDamage: function (damage, target, source, effect) { if (effect && effect.id === 'brn') { return damage / 2; } }, id: "heatproof", name: "Heatproof", rating: 2.5, num: 85 }, "heavymetal": { desc: "The user's weight is doubled. This increases user's base power of Heavy Slam and Heat Crash, as well as damage taken from the opponent's Low Kick and Grass Knot, due to these moves being calculated by the target's weight.", shortDesc: "This Pokemon's weight is doubled.", onModifyPokemon: function (pokemon) { pokemon.weightkg *= 2; }, id: "heavymetal", name: "Heavy Metal", rating: -1, num: 134 }, "honeygather": { desc: "If it is not already holding an item, this Pokemon may find and be holding Honey after a battle.", shortDesc: "No competitive use.", id: "honeygather", name: "Honey Gather", rating: 0, num: 118 }, "hugepower": { desc: "This Pokemon's Attack stat is doubled. Therefore, if this Pokemon's Attack stat on the status screen is 200, it effectively has an Attack stat of 400; which is then subject to the full range of stat boosts and reductions.", shortDesc: "This Pokemon's Attack is doubled.", onModifyAtkPriority: 5, onModifyAtk: function (atk) { return this.chainModify(2); }, id: "hugepower", name: "Huge Power", rating: 5, num: 37 }, "hustle": { desc: "This Pokemon's Attack receives a 50% boost but its Physical attacks receive a 20% drop in Accuracy. For example, a 100% accurate move would become an 80% accurate move. The accuracy of moves that never miss, such as Aerial Ace, remains unaffected.", shortDesc: "This Pokemon's Attack is 1.5x and accuracy of its physical attacks is 0.8x.", // This should be applied directly to the stat as opposed to chaining witht he others onModifyAtkPriority: 5, onModifyAtk: function (atk) { return this.modify(atk, 1.5); }, onModifyMove: function (move) { if (move.category === 'Physical' && typeof move.accuracy === 'number') { move.accuracy *= 0.8; } }, id: "hustle", name: "Hustle", rating: 3, num: 55 }, "hydration": { desc: "If this Pokemon is active while Rain Dance is in effect, it recovers from poison, paralysis, burn, sleep and freeze at the end of the turn.", shortDesc: "This Pokemon has its status cured at the end of each turn if Rain Dance is active.", onResidualOrder: 5, onResidualSubOrder: 1, onResidual: function (pokemon) { if (pokemon.status && this.isWeather(['raindance', 'primordialsea'])) { this.debug('hydration'); pokemon.cureStatus(); } }, id: "hydration", name: "Hydration", rating: 2, num: 93 }, "hypercutter": { desc: "Opponents cannot reduce this Pokemon's Attack stat; they can, however, modify stat changes with Power Swap or Heart Swap and inflict a stat boost with Swagger. This ability does not prevent self-inflicted stat reductions.", shortDesc: "Prevents other Pokemon from lowering this Pokemon's Attack.", onBoost: function (boost, target, source, effect) { if (source && target === source) return; if (boost['atk'] && boost['atk'] < 0) { boost['atk'] = 0; if (!effect.secondaries) this.add("-fail", target, "unboost", "Attack", "[from] ability: Hyper Cutter", "[of] " + target); } }, id: "hypercutter", name: "Hyper Cutter", rating: 1.5, num: 52 }, "icebody": { desc: "If active while Hail is in effect, this Pokemon recovers one-sixteenth of its max HP after each turn. If a non-Ice-type Pokemon receives this ability through Skill Swap, Role Play or the Trace ability, it will not take damage from Hail.", shortDesc: "If Hail is active, this Pokemon heals 1/16 of its max HP each turn; immunity to Hail.", onWeather: function (target, source, effect) { if (effect.id === 'hail') { this.heal(target.maxhp / 16); } }, onImmunity: function (type, pokemon) { if (type === 'hail') return false; }, id: "icebody", name: "Ice Body", rating: 3, num: 115 }, "illuminate": { desc: "When this Pokemon is in the first slot of the player's party, it doubles the rate of wild encounters.", shortDesc: "No competitive use.", id: "illuminate", name: "Illuminate", rating: 0, num: 35 }, "illusion": { desc: "Illusion will change the appearance of the Pokemon to a different species. This is dependent on the last Pokemon in the player's party. Along with the species itself, Illusion is broken when the user is damaged, but is not broken by Substitute, weather conditions, status ailments, or entry hazards. Illusion will replicate the type of Poke Ball, the species name, and the gender of the Pokemon it is masquerading as.", shortDesc: "This Pokemon appears as the last Pokemon in the party until it takes direct damage.", onBeforeSwitchIn: function (pokemon) { pokemon.illusion = null; var i; for (i = pokemon.side.pokemon.length - 1; i > pokemon.position; i--) { if (!pokemon.side.pokemon[i]) continue; if (!pokemon.side.pokemon[i].fainted) break; } if (!pokemon.side.pokemon[i]) return; if (pokemon === pokemon.side.pokemon[i]) return; pokemon.illusion = pokemon.side.pokemon[i]; }, // illusion clearing is hardcoded in the damage function id: "illusion", name: "Illusion", rating: 4.5, num: 149 }, "immunity": { desc: "This Pokemon cannot be poisoned. Gaining this Ability while poisoned cures it.", shortDesc: "This Pokemon cannot become poisoned nor Toxic poisoned.", onUpdate: function (pokemon) { if (pokemon.status === 'psn' || pokemon.status === 'tox') { pokemon.cureStatus(); } }, onImmunity: function (type) { if (type === 'psn') return false; }, id: "immunity", name: "Immunity", rating: 1, num: 17 }, "imposter": { desc: "As soon as the user comes into battle, it Transforms into its opponent, copying the opponent's stats exactly, with the exception of HP. Imposter copies all stat changes on the target originating from moves and abilities such as Swords Dance and Intimidate, but not from items such as Choice Specs. Imposter will not Transform the user if the opponent is an Illusion or if the opponent is behind a Substitute.", shortDesc: "On switch-in, this Pokemon copies the foe it's facing; stats, moves, types, Ability.", onStart: function (pokemon) { var target = pokemon.side.foe.active[pokemon.side.foe.active.length - 1 - pokemon.position]; if (target) { pokemon.transformInto(target, pokemon); } }, id: "imposter", name: "Imposter", rating: 5, num: 150 }, "infiltrator": { desc: "This Pokemon's moves ignore the target's Light Screen, Mist, Reflect, Safeguard, and Substitute.", shortDesc: "Ignores Light Screen, Mist, Reflect, Safeguard, and Substitute.", onModifyMove: function (move) { move.notSubBlocked = true; move.ignoreScreens = true; }, id: "infiltrator", name: "Infiltrator", rating: 2.5, num: 151 }, "innerfocus": { desc: "This Pokemon cannot be made to flinch.", shortDesc: "This Pokemon cannot be made to flinch.", onFlinch: false, id: "innerfocus", name: "Inner Focus", rating: 1, num: 39 }, "insomnia": { desc: "This Pokemon cannot be put to sleep; this includes both opponent-induced sleep as well as user-induced sleep via Rest.", shortDesc: "This Pokemon cannot fall asleep. Gaining this Ability while asleep cures it.", onUpdate: function (pokemon) { if (pokemon.status === 'slp') { pokemon.cureStatus(); } }, onImmunity: function (type, pokemon) { if (type === 'slp') return false; }, id: "insomnia", name: "Insomnia", rating: 2, num: 15 }, "intimidate": { desc: "When this Pokemon enters the field, the Attack stat of each of its opponents lowers by one stage.", shortDesc: "On switch-in, this Pokemon lowers adjacent foes' Attack by 1.", onStart: function (pokemon) { var foeactive = pokemon.side.foe.active; for (var i = 0; i < foeactive.length; i++) { if (!foeactive[i] || !this.isAdjacent(foeactive[i], pokemon)) continue; if (foeactive[i].volatiles['substitute']) { // does it give a message? this.add('-activate', foeactive[i], 'Substitute', 'ability: Intimidate', '[of] ' + pokemon); } else { this.add('-ability', pokemon, 'Intimidate', '[of] ' + foeactive[i]); this.boost({atk: -1}, foeactive[i], pokemon); } } }, id: "intimidate", name: "Intimidate", rating: 3.5, num: 22 }, "ironbarbs": { desc: "All moves that make contact with the Pokemon with Iron Barbs will damage the user by 1/8 of their maximum HP after damage is dealt.", shortDesc: "This Pokemon causes other Pokemon making contact to lose 1/8 of their max HP.", onAfterDamageOrder: 1, onAfterDamage: function (damage, target, source, move) { if (source && source !== target && move && move.isContact) { this.damage(source.maxhp / 8, source, target, null, true); } }, id: "ironbarbs", name: "Iron Barbs", rating: 3, num: 160 }, "ironfist": { desc: "This Pokemon receives a 20% power boost for the following attacks: Bullet Punch, Comet Punch, Dizzy Punch, Drain Punch, Dynamicpunch, Fire Punch, Focus Punch, Hammer Arm, Ice Punch, Mach Punch, Mega Punch, Meteor Mash, Shadow Punch, Sky Uppercut, and Thunderpunch. Sucker Punch, which is known Ambush in Japan, is not boosted.", shortDesc: "This Pokemon's punch-based attacks do 1.2x damage. Sucker Punch is not boosted.", onBasePowerPriority: 8, onBasePower: function (basePower, attacker, defender, move) { if (move.isPunchAttack) { this.debug('Iron Fist boost'); return this.chainModify(1.2); } }, id: "ironfist", name: "Iron Fist", rating: 3, num: 89 }, "justified": { desc: "Will raise the user's Attack stat one level when hit by any Dark-type moves. Unlike other abilities with immunity to certain typed moves, the user will still receive damage from the attack. Justified will raise Attack one level for each hit of a multi-hit move like Beat Up.", shortDesc: "This Pokemon's Attack is boosted by 1 after it is damaged by a Dark-type attack.", onAfterDamage: function (damage, target, source, effect) { if (effect && effect.type === 'Dark') { this.boost({atk:1}); } }, id: "justified", name: "Justified", rating: 2, num: 154 }, "keeneye": { desc: "Prevents other Pokemon from lowering this Pokemon's accuracy.", shortDesc: "This Pokemon's Accuracy cannot be lowered.", onBoost: function (boost, target, source, effect) { if (source && target === source) return; if (boost['accuracy'] && boost['accuracy'] < 0) { boost['accuracy'] = 0; if (!effect.secondaries) this.add("-fail", target, "unboost", "accuracy", "[from] ability: Keen Eye", "[of] " + target); } }, onModifyMove: function (move) { move.ignoreEvasion = true; }, id: "keeneye", name: "Keen Eye", rating: 1, num: 51 }, "klutz": { desc: "This Pokemon ignores both the positive and negative effects of its held item, other than the speed-halving and EV-enhancing effects of Macho Brace, Power Anklet, Power Band, Power Belt, Power Bracer, Power Lens, and Power Weight. Fling cannot be used.", shortDesc: "This Pokemon's held item has no effect, except Macho Brace. Fling cannot be used.", onModifyPokemonPriority: 1, onModifyPokemon: function (pokemon) { if (pokemon.getItem().megaEvolves) return; pokemon.ignore['Item'] = true; }, id: "klutz", name: "Klutz", rating: 0, num: 103 }, "leafguard": { desc: "If this Pokemon is active while Sunny Day is in effect, it cannot become poisoned, burned, paralyzed or put to sleep (other than user-induced Rest). Leaf Guard does not heal status effects that existed before Sunny Day came into effect.", shortDesc: "If Sunny Day is active, this Pokemon cannot be statused and Rest will fail for it.", onSetStatus: function (pokemon) { if (this.isWeather(['sunnyday', 'desolateland'])) { return false; } }, onTryHit: function (target, source, move) { if (move && move.id === 'yawn' && this.isWeather(['sunnyday', 'desolateland'])) { return false; } }, id: "leafguard", name: "Leaf Guard", rating: 1, num: 102 }, "levitate": { desc: "This Pokemon is immune to Ground-type attacks, Spikes, Toxic Spikes and the Arena Trap ability; it loses these immunities while holding Iron Ball, after using Ingrain or if Gravity is in effect.", shortDesc: "This Pokemon is immune to Ground; Gravity, Ingrain, Smack Down, Iron Ball nullify it.", onImmunity: function (type) { if (type === 'Ground') return false; }, id: "levitate", name: "Levitate", rating: 3.5, num: 26 }, "lightmetal": { desc: "The user's weight is halved. This decreases the damage taken from Low Kick and Grass Knot, and also lowers user's base power of Heavy Slam and Heat Crash, due these moves being calculated by the target and user's weight.", shortDesc: "This Pokemon's weight is halved.", onModifyPokemon: function (pokemon) { pokemon.weightkg /= 2; }, id: "lightmetal", name: "Light Metal", rating: 1, num: 135 }, "lightningrod": { desc: "During double battles, this Pokemon draws any single-target Electric-type attack to itself. If an opponent uses an Electric-type attack that affects multiple Pokemon, those targets will be hit. This ability does not affect Electric Hidden Power or Judgment. The user is immune to Electric and its Special Attack is increased one stage when hit by one.", shortDesc: "This Pokemon draws Electric moves to itself to boost Sp. Atk by 1; Electric immunity.", onTryHit: function (target, source, move) { if (target !== source && move.type === 'Electric') { if (!this.boost({spa:1})) { this.add('-immune', target, '[msg]'); } return null; } }, onAnyRedirectTargetPriority: 1, onAnyRedirectTarget: function (target, source, source2, move) { if (move.type !== 'Electric') return; if (this.validTarget(this.effectData.target, source, move.target)) { return this.effectData.target; } }, id: "lightningrod", name: "Lightning Rod", rating: 3.5, num: 32 }, "limber": { desc: "This Pokemon cannot be paralyzed. Gaining this Ability while paralyzed cures it.", shortDesc: "This Pokemon cannot become paralyzed.", onUpdate: function (pokemon) { if (pokemon.status === 'par') { pokemon.cureStatus(); } }, onImmunity: function (type, pokemon) { if (type === 'par') return false; }, id: "limber", name: "Limber", rating: 2, num: 7 }, "liquidooze": { desc: "When another Pokemon uses Absorb, Drain Punch, Dream Eater, Giga Drain, Leech Life, Leech Seed or Mega Drain against this Pokemon, the attacking Pokemon loses the amount of health that it would have gained.", shortDesc: "This Pokemon damages those draining HP from it for as much as they would heal.", id: "liquidooze", onSourceTryHeal: function (damage, target, source, effect) { this.debug("Heal is occurring: " + target + " <- " + source + " :: " + effect.id); var canOoze = {drain: 1, leechseed: 1}; if (canOoze[effect.id]) { this.damage(damage, null, null, null, true); return 0; } }, name: "Liquid Ooze", rating: 1, num: 64 }, "magicbounce": { desc: "This Pokemon blocks certain status moves and uses the move itself.", shortDesc: "Non-damaging moves are reflected back at the user.", id: "magicbounce", name: "Magic Bounce", onTryHitPriority: 1, onTryHit: function (target, source, move) { if (target === source) return; if (move.hasBounced) return; if (typeof move.isBounceable === 'undefined') { move.isBounceable = !!(move.category === 'Status' && (move.status || move.boosts || move.volatileStatus === 'confusion' || move.forceSwitch)); } if (move.isBounceable) { var newMove = this.getMoveCopy(move.id); newMove.hasBounced = true; this.useMove(newMove, target, source); return null; } }, onAllyTryHitSide: function (target, source, move) { if (target.side === source.side) return; if (move.hasBounced) return; if (typeof move.isBounceable === 'undefined') { move.isBounceable = !!(move.category === 'Status' && (move.status || move.boosts || move.volatileStatus === 'confusion' || move.forceSwitch)); } if (move.isBounceable) { var newMove = this.getMoveCopy(move.id); newMove.hasBounced = true; this.useMove(newMove, target, source); return null; } }, effect: { duration: 1 }, rating: 5, num: 156 }, "magicguard": { desc: "This Pokemon can only be damaged by direct attacks.", shortDesc: "Prevents all damage except from direct attacks.", onDamage: function (damage, target, source, effect) { if (effect.effectType !== 'Move') { return false; } }, id: "magicguard", name: "Magic Guard", rating: 4.5, num: 98 }, "magician": { desc: "If this Pokemon is not holding an item, it steals the held item of a target it hits with a move.", shortDesc: "This Pokemon steals the held item of a target it hits with a move.", onSourceHit: function (target, source, move) { if (!move || !target) return; if (target !== source && move.category !== 'Status') { if (source.item) return; var yourItem = target.takeItem(source); if (!yourItem) return; if (!source.setItem(yourItem)) { target.item = yourItem.id; // bypass setItem so we don't break choicelock or anything return; } this.add('-item', source, yourItem, '[from] ability: Magician', '[of] ' + target); } }, id: "magician", name: "Magician", rating: 2, num: 170 }, "magmaarmor": { desc: "This Pokemon cannot be frozen. Gaining this Ability while frozen cures it.", shortDesc: "This Pokemon cannot become frozen.", onUpdate: function (pokemon) { if (pokemon.status === 'frz') { pokemon.cureStatus(); } }, onImmunity: function (type, pokemon) { if (type === 'frz') return false; }, id: "magmaarmor", name: "Magma Armor", rating: 0.5, num: 40 }, "magnetpull": { desc: "When this Pokemon enters the field, Steel-type opponents cannot switch out nor flee the battle unless they are holding Shed Shell or use attacks like U-Turn or Baton Pass.", shortDesc: "Prevents Steel-type foes from switching out normally.", onFoeModifyPokemon: function (pokemon) { if (pokemon.hasType('Steel') && this.isAdjacent(pokemon, this.effectData.target)) { pokemon.tryTrap(true); } }, onFoeMaybeTrapPokemon: function (pokemon, source) { if (!source) source = this.effectData.target; if (pokemon.hasType('Steel') && this.isAdjacent(pokemon, source)) { pokemon.maybeTrapped = true; } }, id: "magnetpull", name: "Magnet Pull", rating: 4.5, num: 42 }, "marvelscale": { desc: "When this Pokemon becomes burned, poisoned (including Toxic), paralyzed, frozen or put to sleep (including self-induced sleep via Rest), its Defense receives a 50% boost.", shortDesc: "If this Pokemon is statused, its Defense is 1.5x.", onModifyDefPriority: 6, onModifyDef: function (def, pokemon) { if (pokemon.status) { return this.chainModify(1.5); } }, id: "marvelscale", name: "Marvel Scale", rating: 3, num: 63 }, "megalauncher": { desc: "Boosts the power of Aura and Pulse moves, such as Aura Sphere and Dark Pulse, by 50%.", shortDesc: "Boosts the power of Aura/Pulse moves by 50%.", onBasePowerPriority: 8, onBasePower: function (basePower, attacker, defender, move) { if (move.flags && move.flags['pulse']) { return this.chainModify(1.5); } }, id: "megalauncher", name: "Mega Launcher", rating: 3, num: 178 }, "minus": { desc: "This Pokemon's Special Attack receives a 50% boost in double battles if a partner has the Plus or Minus ability.", shortDesc: "If an ally has the Ability Plus or Minus, this Pokemon's Sp. Atk is 1.5x.", onModifySpAPriority: 5, onModifySpA: function (spa, pokemon) { var allyActive = pokemon.side.active; if (allyActive.length === 1) { return; } for (var i = 0; i < allyActive.length; i++) { if (allyActive[i] && allyActive[i].position !== pokemon.position && !allyActive[i].fainted && allyActive[i].hasAbility(['minus', 'plus'])) { return this.chainModify(1.5); } } }, id: "minus", name: "Minus", rating: 0, num: 58 }, "moldbreaker": { desc: "When this Pokemon uses any move, it nullifies the Ability of any active Pokemon that hinder or empower this Pokemon's attacks. These abilities include Battle Armor, Clear Body, Damp, Dry Skin, Filter, Flash Fire, Flower Gift, Heatproof, Herbivore, Hyper Cutter, Immunity, Inner Focus, Insomnia, Keen Eye, Leaf Guard, Levitate, Lightningrod, Limber, Magma Armor, Marvel Scale, Motor Drive, Oblivious, Own Tempo, Sand Veil, Shell Armor, Shield Dust, Simple, Snow Cloak, Solid Rock, Soundproof, Sticky Hold, Storm Drain, Sturdy, Suction Cups, Tangled Feet, Thick Fat, Unaware, Vital Spirit, Volt Absorb, Water Absorb, Water Veil, White Smoke and Wonder Guard.", shortDesc: "This Pokemon's moves ignore any Ability that could modify the effectiveness.", onStart: function (pokemon) { this.add('-ability', pokemon, 'Mold Breaker'); }, onAllyModifyPokemonPriority: 100, onAllyModifyPokemon: function (pokemon) { if (this.activePokemon === this.effectData.target && pokemon !== this.activePokemon) { pokemon.ignore['Ability'] = 'A'; } }, onFoeModifyPokemonPriority: 100, onFoeModifyPokemon: function (pokemon) { if (this.activePokemon === this.effectData.target) { pokemon.ignore['Ability'] = 'A'; } }, id: "moldbreaker", name: "Mold Breaker", rating: 3, num: 104 }, "moody": { desc: "At the end of each turn, the Pokemon raises a random stat that isn't already +6 by two stages, and lowers a random stat that isn't already -6 by one stage. These stats include accuracy and evasion.", shortDesc: "Boosts a random stat by 2 and lowers another stat by 1 at the end of each turn.", onResidualOrder: 26, onResidualSubOrder: 1, onResidual: function (pokemon) { var stats = [], i = ''; var boost = {}; for (var i in pokemon.boosts) { if (pokemon.boosts[i] < 6) { stats.push(i); } } if (stats.length) { i = stats[this.random(stats.length)]; boost[i] = 2; } stats = []; for (var j in pokemon.boosts) { if (pokemon.boosts[j] > -6 && j !== i) { stats.push(j); } } if (stats.length) { i = stats[this.random(stats.length)]; boost[i] = -1; } this.boost(boost); }, id: "moody", name: "Moody", rating: 5, num: 141 }, "motordrive": { desc: "This Pokemon is immune to all Electric-type moves (including Status moves). If hit by an Electric-type attack, its Speed increases by one stage.", shortDesc: "This Pokemon's Speed is boosted by 1 if hit by an Electric move; Electric immunity.", onTryHit: function (target, source, move) { if (target !== source && move.type === 'Electric') { if (!this.boost({spe:1})) { this.add('-immune', target, '[msg]'); } return null; } }, id: "motordrive", name: "Motor Drive", rating: 3, num: 78 }, "moxie": { desc: "If this Pokemon knocks out another Pokemon with a damaging attack, its Attack is raised by one stage.", shortDesc: "This Pokemon's Attack is boosted by 1 if it attacks and faints another Pokemon.", onSourceFaint: function (target, source, effect) { if (effect && effect.effectType === 'Move') { this.boost({atk:1}, source); } }, id: "moxie", name: "Moxie", rating: 4, num: 153 }, "multiscale": { desc: "If this Pokemon is at full HP, it takes half damage from attacks.", shortDesc: "If this Pokemon is at full HP, it takes half damage from attacks.", onSourceModifyDamage: function (damage, source, target, move) { if (target.hp >= target.maxhp) { this.debug('Multiscale weaken'); return this.chainModify(0.5); } }, id: "multiscale", name: "Multiscale", rating: 4, num: 136 }, "multitype": { desc: "If this Pokemon is Arceus, its type and sprite change to match its held Plate. Either way, this Pokemon is holding a Plate, the Plate cannot be taken (such as by Trick or Thief). This ability cannot be Skill Swapped, Role Played or Traced.", shortDesc: "If this Pokemon is Arceus, its type changes to match its held Plate.", // Multitype's type-changing itself is implemented in statuses.js id: "multitype", name: "Multitype", rating: 4, num: 121 }, "mummy": { desc: "When the user is attacked by a contact move, the opposing Pokemon's ability is turned into Mummy as well. Multitype, Wonder Guard and Mummy itself are the only abilities not affected by Mummy. The effect of Mummy is not removed by Mold Breaker, Turboblaze, or Teravolt.", shortDesc: "Pokemon making contact with this Pokemon have their Ability changed to Mummy.", id: "mummy", name: "Mummy", onAfterDamage: function (damage, target, source, move) { if (source && source !== target && move && move.isContact) { var oldAbility = source.setAbility('mummy', source, 'mummy', true); if (oldAbility) { this.add('-endability', source, oldAbility, '[from] Mummy'); this.add('-ability', source, 'Mummy', '[from] Mummy'); this.runEvent('EndAbility', source, oldAbility, 'mummy'); } } }, rating: 1, num: 152 }, "naturalcure": { desc: "When this Pokemon switches out of battle, it is cured of poison (including Toxic), paralysis, burn, freeze and sleep (including self-induced Rest).", shortDesc: "This Pokemon has its status cured when it switches out.", onSwitchOut: function (pokemon) { pokemon.setStatus(''); }, id: "naturalcure", name: "Natural Cure", rating: 4, num: 30 }, "noguard": { desc: "Every attack used by or against this Pokemon will always hit, even during evasive two-turn moves such as Fly and Dig.", shortDesc: "Every move used by or against this Pokemon will always hit.", onAnyAccuracy: function (accuracy, target, source, move) { if (move && (source === this.effectData.target || target === this.effectData.target)) { return true; } return accuracy; }, id: "noguard", name: "No Guard", rating: 4, num: 99 }, "normalize": { desc: "Makes all of this Pokemon's attacks Normal-typed.", shortDesc: "This Pokemon's moves all become Normal-typed.", onModifyMove: function (move) { if (move.id !== 'struggle') { move.type = 'Normal'; } }, id: "normalize", name: "Normalize", rating: -1, num: 96 }, "oblivious": { desc: "This Pokemon cannot be infatuated (by Attract or Cute Charm) or taunted. Gaining this Ability while afflicted by either condition cures it.", shortDesc: "This Pokemon cannot be infatuated or taunted. Gaining this Ability cures it.", onUpdate: function (pokemon) { if (pokemon.volatiles['attract']) { pokemon.removeVolatile('attract'); this.add('-end', pokemon, 'move: Attract'); } if (pokemon.volatiles['taunt']) { pokemon.removeVolatile('taunt'); // Taunt's volatile already sends the -end message when removed } }, onImmunity: function (type, pokemon) { if (type === 'attract') { this.add('-immune', pokemon, '[from] Oblivious'); return false; } }, onTryHit: function (pokemon, target, move) { if (move.id === 'captivate' || move.id === 'taunt') { this.add('-immune', pokemon, '[msg]', '[from] Oblivious'); return null; } }, id: "oblivious", name: "Oblivious", rating: 0.5, num: 12 }, "overcoat": { desc: "In battle, the Pokemon does not take damage from weather conditions like Sandstorm or Hail. It is also immune to powder moves.", shortDesc: "This Pokemon is immune to residual weather damage, and powder moves.", onImmunity: function (type, pokemon) { if (type === 'sandstorm' || type === 'hail' || type === 'powder') return false; }, id: "overcoat", name: "Overcoat", rating: 2, num: 142 }, "overgrow": { desc: "When its health reaches one-third or less of its max HP, this Pokemon's Grass-type attacks receive a 50% boost in power.", shortDesc: "When this Pokemon has 1/3 or less of its max HP, its Grass attacks do 1.5x damage.", onModifyAtkPriority: 5, onModifyAtk: function (atk, attacker, defender, move) { if (move.type === 'Grass' && attacker.hp <= attacker.maxhp / 3) { this.debug('Overgrow boost'); return this.chainModify(1.5); } }, onModifySpAPriority: 5, onModifySpA: function (atk, attacker, defender, move) { if (move.type === 'Grass' && attacker.hp <= attacker.maxhp / 3) { this.debug('Overgrow boost'); return this.chainModify(1.5); } }, id: "overgrow", name: "Overgrow", rating: 2, num: 65 }, "owntempo": { desc: "This Pokemon cannot be confused. Gaining this Ability while confused cures it.", shortDesc: "This Pokemon cannot be confused. Gaining this Ability while confused cures it.", onUpdate: function (pokemon) { if (pokemon.volatiles['confusion']) { pokemon.removeVolatile('confusion'); } }, onImmunity: function (type, pokemon) { if (type === 'confusion') { this.add('-immune', pokemon, 'confusion'); return false; } }, id: "owntempo", name: "Own Tempo", rating: 1, num: 20 }, "parentalbond": { desc: "Allows the Pokemon to hit twice with the same move in one turn. Second hit has 0.5x base power. Does not affect Status, multihit, or spread moves (in doubles).", shortDesc: "Hits twice in one turn. Second hit has 0.5x base power.", onModifyMove: function (move, pokemon, target) { if (move.category !== 'Status' && !move.selfdestruct && !move.multihit && ((target.side && target.side.active.length < 2) || move.target in {any:1, normal:1, randomNormal:1})) { move.multihit = 2; pokemon.addVolatile('parentalbond'); } }, effect: { duration: 1, onBasePowerPriority: 8, onBasePower: function (basePower) { if (this.effectData.hit) { return this.chainModify(0.5); } else { this.effectData.hit = true; } } }, id: "parentalbond", name: "Parental Bond", rating: 4.5, num: 184 }, "pickup": { desc: "If an opponent uses a consumable item, Pickup will give the Pokemon the item used, if it is not holding an item. If multiple Pickup Pokemon are in play, one will pick up a copy of the used Berry, and may or may not use it immediately. Works on Berries, Gems, Absorb Bulb, Focus Sash, Herbs, Cell Battery, Red Card, and anything that is thrown with Fling.", shortDesc: "If this Pokemon has no item, it finds one used by an adjacent Pokemon this turn.", onResidualOrder: 26, onResidualSubOrder: 1, onResidual: function (pokemon) { var foe = pokemon.side.foe.randomActive(); if (!foe) return; if (!pokemon.item && foe.lastItem && foe.usedItemThisTurn && foe.lastItem !== 'airballoon' && foe.lastItem !== 'ejectbutton') { pokemon.setItem(foe.lastItem); foe.lastItem = ''; var item = pokemon.getItem(); this.add('-item', pokemon, item, '[from] Pickup'); if (item.isBerry) pokemon.update(); } }, id: "pickup", name: "Pickup", rating: 0, num: 53 }, "pickpocket": { desc: "If this Pokemon has no item, it steals an item off an attacking Pokemon making contact.", shortDesc: "If this Pokemon has no item, it steals an item off a Pokemon making contact.", onAfterDamage: function (damage, target, source, move) { if (source && source !== target && move && move.isContact) { if (target.item) { return; } var yourItem = source.takeItem(target); if (!yourItem) { return; } if (!target.setItem(yourItem)) { source.item = yourItem.id; return; } this.add('-item', target, yourItem, '[from] ability: Pickpocket'); } }, id: "pickpocket", name: "Pickpocket", rating: 1, num: 124 }, "pixilate": { desc: "Turns all of this Pokemon's Normal-typed attacks into Fairy-type and deal 1.3x damage. Does not affect Hidden Power.", shortDesc: "This Pokemon's Normal moves become Fairy-type and do 1.3x damage.", onModifyMove: function (move, pokemon) { if (move.type === 'Normal' && move.id !== 'hiddenpower') { move.type = 'Fairy'; if (move.category !== 'Status') pokemon.addVolatile('pixilate'); } }, effect: { duration: 1, onBasePowerPriority: 8, onBasePower: function (basePower, pokemon, target, move) { return this.chainModify([0x14CD, 0x1000]); } }, id: "pixilate", name: "Pixilate", rating: 3, num: 182 }, "plus": { desc: "This Pokemon's Special Attack receives a 50% boost in double battles if a partner has the Plus or Minus ability.", shortDesc: "If an ally has the Ability Plus or Minus, this Pokemon's Sp. Atk is 1.5x.", onModifySpAPriority: 5, onModifySpA: function (spa, pokemon) { var allyActive = pokemon.side.active; if (allyActive.length === 1) { return; } for (var i = 0; i < allyActive.length; i++) { if (allyActive[i] && allyActive[i].position !== pokemon.position && !allyActive[i].fainted && allyActive[i].hasAbility(['minus', 'plus'])) { return this.chainModify(1.5); } } }, id: "plus", name: "Plus", rating: 0, num: 57 }, "poisonheal": { desc: "If this Pokemon becomes poisoned (including Toxic), it will recover 1/8 of its max HP after each turn.", shortDesc: "This Pokemon is healed by 1/8 of its max HP each turn when poisoned; no HP loss.", onDamage: function (damage, target, source, effect) { if (effect.id === 'psn' || effect.id === 'tox') { this.heal(target.maxhp / 8); return false; } }, id: "poisonheal", name: "Poison Heal", rating: 4, num: 90 }, "poisonpoint": { desc: "If an opponent contact attacks this Pokemon, there is a 30% chance that the opponent will become poisoned.", shortDesc: "30% chance of poisoning a Pokemon making contact with this Pokemon.", onAfterDamage: function (damage, target, source, move) { if (move && move.isContact) { if (this.random(10) < 3) { source.trySetStatus('psn', target, move); } } }, id: "poisonpoint", name: "Poison Point", rating: 2, num: 38 }, "poisontouch": { desc: "This Pokemon's contact attacks have a 30% chance of poisoning the target.", shortDesc: "This Pokemon's contact moves have a 30% chance of poisoning.", // upokecenter says this is implemented as an added secondary effect onModifyMove: function (move) { if (!move || !move.isContact) return; if (!move.secondaries) { move.secondaries = []; } move.secondaries.push({ chance: 30, status: 'psn' }); }, id: "poisontouch", name: "Poison Touch", rating: 2, num: 143 }, "prankster": { desc: "This Pokemon's Status moves have their priority increased by 1 stage.", shortDesc: "This Pokemon's Status moves have their priority increased by 1.", onModifyPriority: function (priority, pokemon, target, move) { if (move && move.category === 'Status') { return priority + 1; } }, id: "prankster", name: "Prankster", rating: 4.5, num: 158 }, "pressure": { desc: "If this Pokemon is the target of a foe's move, that move loses one additional PP.", shortDesc: "If this Pokemon is the target of a foe's move, that move loses one additional PP.", onStart: function (pokemon) { this.add('-ability', pokemon, 'Pressure'); }, onSourceDeductPP: function (pp, target, source) { if (target.side === source.side) return; return pp + 1; }, id: "pressure", name: "Pressure", rating: 1.5, num: 46 }, "primordialsea": { desc: "When this Pokemon enters the battlefield, the weather becomes heavy rain for as long as this Pokemon remains on the battlefield with Primordial Sea.", shortDesc: "The weather becomes heavy rain until this Pokemon leaves battle.", onStart: function (source) { this.setWeather('primordialsea'); }, onEnd: function (pokemon) { if (this.weatherData.source !== pokemon) return; for (var i = 0; i < this.sides.length; i++) { for (var j = 0; j < this.sides[i].active.length; j++) { var target = this.sides[i].active[j]; if (target === pokemon) continue; if (target && target.hp && target.ability === 'primordialsea' && target.ignore['Ability'] !== true) { this.weatherData.source = target; return; } } } this.clearWeather(); }, id: "primordialsea", name: "Primordial Sea", rating: 5, num: 189 }, "protean": { desc: "Right before this Pokemon uses a move, it changes its type to match that move. Hidden Power is interpreted as its Hidden Power type, rather than Normal.", shortDesc: "Right before this Pokemon uses a move, it changes its type to match that move.", onPrepareHit: function (source, target, move) { var type = move.type; if (type && type !== '???' && source.getTypes().join() !== type) { if (!source.setType(type)) return; this.add('-start', source, 'typechange', type, '[from] Protean'); } }, id: "protean", name: "Protean", rating: 4, num: 168 }, "purepower": { desc: "This Pokemon's Attack stat is doubled. Note that this is the Attack stat itself, not the base Attack stat of its species.", shortDesc: "This Pokemon's Attack is doubled.", onModifyAtkPriority: 5, onModifyAtk: function (atk) { return this.chainModify(2); }, id: "purepower", name: "Pure Power", rating: 5, num: 74 }, "quickfeet": { desc: "When this Pokemon is poisoned (including Toxic), burned, paralyzed, asleep (including self-induced Rest) or frozen, its Speed stat receives a 50% boost; the paralysis status' Speed drop is also ignored.", shortDesc: "If this Pokemon is statused, its Speed is 1.5x; paralysis' Speed drop is ignored.", onModifySpe: function (speMod, pokemon) { if (pokemon.status) { return this.chain(speMod, 1.5); } }, id: "quickfeet", name: "Quick Feet", rating: 3, num: 95 }, "raindish": { desc: "If the weather is Rain Dance, this Pokemon recovers 1/16 of its max HP after each turn.", shortDesc: "If the weather is Rain Dance, this Pokemon heals 1/16 of its max HP each turn.", onWeather: function (target, source, effect) { if (effect.id === 'raindance' || effect.id === 'primordialsea') { this.heal(target.maxhp / 16); } }, id: "raindish", name: "Rain Dish", rating: 1.5, num: 44 }, "rattled": { desc: "Raises the user's Speed one stage when hit by a Dark-, Bug-, or Ghost-type move.", shortDesc: "This Pokemon gets +1 Speed if hit by a Dark-, Bug-, or Ghost-type attack.", onAfterDamage: function (damage, target, source, effect) { if (effect && (effect.type === 'Dark' || effect.type === 'Bug' || effect.type === 'Ghost')) { this.boost({spe:1}); } }, id: "rattled", name: "Rattled", rating: 2, num: 155 }, "reckless": { desc: "When this Pokemon uses an attack that causes recoil damage, or an attack that has a chance to cause recoil damage such as Jump Kick and High Jump Kick, the attacks's power receives a 20% boost.", shortDesc: "This Pokemon's attacks with recoil or crash damage do 1.2x damage; not Struggle.", onBasePowerPriority: 8, onBasePower: function (basePower, attacker, defender, move) { if (move.recoil || move.hasCustomRecoil) { this.debug('Reckless boost'); return this.chainModify(1.2); } }, id: "reckless", name: "Reckless", rating: 3, num: 120 }, "refrigerate": { desc: "Turns all of this Pokemon's Normal-typed attacks into Ice-typed and deal 1.3x damage. Does not affect Hidden Power.", shortDesc: "This Pokemon's Normal moves become Ice-type and do 1.3x damage.", onModifyMove: function (move, pokemon) { if (move.type === 'Normal' && move.id !== 'hiddenpower') { move.type = 'Ice'; if (move.category !== 'Status') pokemon.addVolatile('refrigerate'); } }, effect: { duration: 1, onBasePowerPriority: 8, onBasePower: function (basePower, pokemon, target, move) { return this.chainModify([0x14CD, 0x1000]); } }, id: "refrigerate", name: "Refrigerate", rating: 3, num: 174 }, "regenerator": { desc: "This Pokemon heals 1/3 of its max HP when it switches out.", shortDesc: "This Pokemon heals 1/3 of its max HP when it switches out.", onSwitchOut: function (pokemon) { pokemon.heal(pokemon.maxhp / 3); }, id: "regenerator", name: "Regenerator", rating: 4, num: 144 }, "rivalry": { desc: "This Pokemon's attacks do 1.25x damage if their target is the same gender, but 0.75x if their target is the opposite gender.", shortDesc: "This Pokemon's attacks do 1.25x on same gender targets; 0.75x on opposite gender.", onBasePowerPriority: 8, onBasePower: function (basePower, attacker, defender, move) { if (attacker.gender && defender.gender) { if (attacker.gender === defender.gender) { this.debug('Rivalry boost'); return this.chainModify(1.25); } else { this.debug('Rivalry weaken'); return this.chainModify(0.75); } } }, id: "rivalry", name: "Rivalry", rating: 0.5, num: 79 }, "rockhead": { desc: "This Pokemon does not receive recoil damage except from Struggle, Life Orb, or crash damage from Jump Kick or High Jump Kick.", shortDesc: "This Pokemon does not take recoil damage besides Struggle, Life Orb, crash damage.", onModifyMove: function (move) { delete move.recoil; }, id: "rockhead", name: "Rock Head", rating: 3, num: 69 }, "roughskin": { desc: "Causes recoil damage equal to 1/8 of the opponent's max HP if an opponent makes contact.", shortDesc: "This Pokemon causes other Pokemon making contact to lose 1/8 of their max HP.", onAfterDamageOrder: 1, onAfterDamage: function (damage, target, source, move) { if (source && source !== target && move && move.isContact) { this.damage(source.maxhp / 8, source, target, null, true); } }, id: "roughskin", name: "Rough Skin", rating: 3, num: 24 }, "runaway": { desc: "Unless this Pokemon is under the effects of a trapping move or ability, such as Mean Look or Shadow Tag, it will escape from wild Pokemon battles without fail.", shortDesc: "No competitive use.", id: "runaway", name: "Run Away", rating: 0, num: 50 }, "sandforce": { desc: "Raises the power of this Pokemon's Rock, Ground, and Steel-type moves by 1.3x if the weather is Sandstorm. This Pokemon is also immune to residual Sandstorm damage.", shortDesc: "This Pokemon's Rock/Ground/Steel attacks do 1.3x in Sandstorm; immunity to it.", onBasePowerPriority: 8, onBasePower: function (basePower, attacker, defender, move) { if (this.isWeather('sandstorm')) { if (move.type === 'Rock' || move.type === 'Ground' || move.type === 'Steel') { this.debug('Sand Force boost'); return this.chainModify([0x14CD, 0x1000]); // The Sand Force modifier is slightly higher than the normal 1.3 (0x14CC) } } }, onImmunity: function (type, pokemon) { if (type === 'sandstorm') return false; }, id: "sandforce", name: "Sand Force", rating: 2, num: 159 }, "sandrush": { desc: "This Pokemon's Speed is doubled if the weather is Sandstorm. This Pokemon is also immune to residual Sandstorm damage.", shortDesc: "If Sandstorm is active, this Pokemon's Speed is doubled; immunity to Sandstorm.", onModifySpe: function (speMod, pokemon) { if (this.isWeather('sandstorm')) { return this.chain(speMod, 2); } }, onImmunity: function (type, pokemon) { if (type === 'sandstorm') return false; }, id: "sandrush", name: "Sand Rush", rating: 2, num: 146 }, "sandstream": { desc: "When this Pokemon enters the battlefield, the weather becomes Sandstorm (for 5 turns normally, or 8 turns while holding Smooth Rock).", shortDesc: "On switch-in, the weather becomes Sandstorm.", onStart: function (source) { if (this.isWeather(['desolateland', 'primordialsea', 'deltastream'])) { this.add('-ability', source, 'Sand Stream', '[from] ' + this.effectiveWeather(), '[fail]'); return null; } this.setWeather('sandstorm'); }, id: "sandstream", name: "Sand Stream", rating: 4.5, num: 45 }, "sandveil": { desc: "This Pokemon's Evasion is boosted by 1.25x if the weather is Sandstorm. This Pokemon is also immune to residual Sandstorm damage.", shortDesc: "If Sandstorm is active, this Pokemon's evasion is 1.25x; immunity to Sandstorm.", onImmunity: function (type, pokemon) { if (type === 'sandstorm') return false; }, onAccuracy: function (accuracy) { if (typeof accuracy !== 'number') return; if (this.isWeather('sandstorm')) { this.debug('Sand Veil - decreasing accuracy'); return accuracy * 0.8; } }, id: "sandveil", name: "Sand Veil", rating: 1.5, num: 8 }, "sapsipper": { desc: "This Pokemon is immune to Grass moves. If hit by a Grass move, its Attack is increased by one stage (once for each hit of Bullet Seed). Does not affect Aromatherapy, but the move will still trigger an Attack increase.", shortDesc: "This Pokemon's Attack is boosted by 1 if hit by any Grass move; Grass immunity.", onTryHit: function (target, source, move) { if (target !== source && move.type === 'Grass') { if (!this.boost({atk:1})) { this.add('-immune', target, '[msg]'); } return null; } }, onAllyTryHitSide: function (target, source, move) { if (target.side !== source.side) return; if (move.type === 'Grass') { this.boost({atk:1}, this.effectData.target); } }, id: "sapsipper", name: "Sap Sipper", rating: 3.5, num: 157 }, "scrappy": { desc: "This Pokemon has the ability to hit Ghost-type Pokemon with Normal-type and Fighting-type moves. Effectiveness of these moves takes into account the Ghost-type Pokemon's other weaknesses and resistances.", shortDesc: "This Pokemon can hit Ghost-types with Normal- and Fighting-type moves.", onModifyMovePriority: -5, onModifyMove: function (move) { if (move.type in {'Fighting':1, 'Normal':1}) { move.affectedByImmunities = false; } }, id: "scrappy", name: "Scrappy", rating: 3, num: 113 }, "serenegrace": { desc: "This Pokemon's moves have their secondary effect chance doubled. For example, if this Pokemon uses Ice Beam, it will have a 20% chance to freeze its target.", shortDesc: "This Pokemon's moves have their secondary effect chance doubled.", onModifyMove: function (move) { if (move.secondaries && move.id !== 'secretpower') { this.debug('doubling secondary chance'); for (var i = 0; i < move.secondaries.length; i++) { move.secondaries[i].chance *= 2; } } }, id: "serenegrace", name: "Serene Grace", rating: 4, num: 32 }, "shadowtag": { desc: "When this Pokemon enters the field, its non-Ghost-type opponents cannot switch or flee the battle unless they have the same ability, are holding Shed Shell, or they use the moves Baton Pass or U-Turn.", shortDesc: "Prevents foes from switching out normally unless they also have this Ability.", onFoeModifyPokemon: function (pokemon) { if (!pokemon.hasAbility('shadowtag') && this.isAdjacent(pokemon, this.effectData.target)) { pokemon.tryTrap(true); } }, onFoeMaybeTrapPokemon: function (pokemon, source) { if (!source) source = this.effectData.target; if (!pokemon.hasAbility('shadowtag') && this.isAdjacent(pokemon, source)) { pokemon.maybeTrapped = true; } }, id: "shadowtag", name: "Shadow Tag", rating: 5, num: 23 }, "shedskin": { desc: "At the end of each turn, this Pokemon has a 33% chance to heal itself from poison (including Toxic), paralysis, burn, freeze or sleep (including self-induced Rest).", shortDesc: "This Pokemon has a 33% chance to have its status cured at the end of each turn.", onResidualOrder: 5, onResidualSubOrder: 1, onResidual: function (pokemon) { if (pokemon.hp && pokemon.status && this.random(3) === 0) { this.debug('shed skin'); this.add('-activate', pokemon, 'ability: Shed Skin'); pokemon.cureStatus(); } }, id: "shedskin", name: "Shed Skin", rating: 4, num: 61 }, "sheerforce": { desc: "Raises the base power of all moves that have any secondary effects by 30%, but the secondary effects are ignored. Some side effects of moves, such as recoil, draining, stat reduction, and switching out usually aren't considered secondary effects. If a Pokemon with Sheer Force is holding a Life Orb and uses an attack that would be boosted by Sheer Force, then the move gains both boosts and the user receives no Life Orb recoil (only if the attack is boosted by Sheer Force).", shortDesc: "This Pokemon's attacks with secondary effects do 1.3x damage; nullifies the effects.", onModifyMove: function (move, pokemon) { if (move.secondaries) { delete move.secondaries; move.negateSecondary = true; pokemon.addVolatile('sheerforce'); } }, effect: { duration: 1, onBasePowerPriority: 8, onBasePower: function (basePower, pokemon, target, move) { return this.chainModify([0x14CD, 0x1000]); // The Sheer Force modifier is slightly higher than the normal 1.3 (0x14CC) } }, id: "sheerforce", name: "Sheer Force", rating: 4, num: 125 }, "shellarmor": { desc: "Attacks targeting this Pokemon can't be critical hits.", shortDesc: "This Pokemon cannot be struck by a critical hit.", onCriticalHit: false, id: "shellarmor", name: "Shell Armor", rating: 1, num: 75 }, "shielddust": { desc: "If the opponent uses a move that has secondary effects that affect this Pokemon in addition to damage, the move's secondary effects will not trigger (For example, Ice Beam loses its 10% freeze chance).", shortDesc: "This Pokemon is not affected by the secondary effect of another Pokemon's attack.", onTrySecondaryHit: function () { this.debug('Shield Dust prevent secondary'); return null; }, id: "shielddust", name: "Shield Dust", rating: 2, num: 19 }, "simple": { desc: "This Pokemon doubles all of its positive and negative stat modifiers. For example, if this Pokemon uses Curse, its Attack and Defense stats increase by two stages and its Speed stat decreases by two stages.", shortDesc: "This Pokemon has its own stat boosts and drops doubled as they happen.", onBoost: function (boost) { for (var i in boost) { boost[i] *= 2; } }, id: "simple", name: "Simple", rating: 4, num: 86 }, "skilllink": { desc: "When this Pokemon uses an attack that strikes multiple times in one turn, such as Fury Attack or Spike Cannon, such attacks will always strike for the maximum number of hits.", shortDesc: "This Pokemon's multi-hit attacks always hit the maximum number of times.", onModifyMove: function (move) { if (move.multihit && move.multihit.length) { move.multihit = move.multihit[1]; } }, id: "skilllink", name: "Skill Link", rating: 4, num: 92 }, "slowstart": { desc: "After this Pokemon switches into the battle, its Attack and Speed stats are halved for five turns. For example, if this Pokemon has an Attack stat of 400, its Attack will be 200 until the effects of Slow Start wear off.", shortDesc: "On switch-in, this Pokemon's Attack and Speed are halved for 5 turns.", onStart: function (pokemon) { pokemon.addVolatile('slowstart'); }, effect: { duration: 5, onStart: function (target) { this.add('-start', target, 'Slow Start'); }, onModifyAtkPriority: 5, onModifyAtk: function (atk, pokemon) { if (pokemon.ignore['Ability'] === true || pokemon.ability !== 'slowstart') { pokemon.removeVolatile('slowstart'); return; } return this.chainModify(0.5); }, onModifySpe: function (speMod, pokemon) { if (pokemon.ignore['Ability'] === true || pokemon.ability !== 'slowstart') { pokemon.removeVolatile('slowstart'); return; } return this.chain(speMod, 0.5); }, onEnd: function (target) { this.add('-end', target, 'Slow Start'); } }, id: "slowstart", name: "Slow Start", rating: -2, num: 112 }, "sniper": { desc: "When this Pokemon lands a Critical Hit, the damage is increased to another 1.5x.", shortDesc: "If this Pokemon strikes with a critical hit, the damage is increased by 50%.", onModifyDamage: function (damage, source, target, move) { if (move.crit) { this.debug('Sniper boost'); return this.chainModify(1.5); } }, id: "sniper", name: "Sniper", rating: 1, num: 97 }, "snowcloak": { desc: "This Pokemon's Evasion is boosted by 1.25x if the weather is Hail. This Pokemon is also immune to residual Hail damage.", shortDesc: "If Hail is active, this Pokemon's evasion is 1.25x; immunity to Hail.", onImmunity: function (type, pokemon) { if (type === 'hail') return false; }, onAccuracy: function (accuracy) { if (typeof accuracy !== 'number') return; if (this.isWeather('hail')) { this.debug('Snow Cloak - decreasing accuracy'); return accuracy * 0.8; } }, id: "snowcloak", name: "Snow Cloak", rating: 1, num: 81 }, "snowwarning": { desc: "When this Pokemon enters the battlefield, the weather becomes Hail (for 5 turns normally, or 8 turns while holding Icy Rock).", shortDesc: "On switch-in, the weather becomes Hail.", onStart: function (source) { if (this.isWeather(['desolateland', 'primordialsea', 'deltastream'])) { this.add('-ability', source, 'Snow Warning', '[from] ' + this.effectiveWeather(), '[fail]'); return null; } this.setWeather('hail'); }, id: "snowwarning", name: "Snow Warning", rating: 4, num: 117 }, "solarpower": { desc: "If the weather is Sunny Day, this Pokemon's Special Attack is 1.5x, but it loses 1/8 of its max HP at the end of every turn.", shortDesc: "If Sunny Day is active, this Pokemon's Sp. Atk is 1.5x and loses 1/8 max HP per turn.", onModifySpAPriority: 5, onModifySpA: function (spa, pokemon) { if (this.isWeather(['sunnyday', 'desolateland'])) { return this.chainModify(1.5); } }, onWeather: function (target, source, effect) { if (effect.id === 'sunnyday' || effect.id === 'desolateland') { this.damage(target.maxhp / 8); } }, id: "solarpower", name: "Solar Power", rating: 1.5, num: 94 }, "solidrock": { desc: "Super-effective attacks only deal 3/4 their usual damage against this Pokemon.", shortDesc: "This Pokemon receives 3/4 damage from super effective attacks.", onSourceModifyDamage: function (damage, source, target, move) { if (target.runEffectiveness(move) > 0) { this.debug('Solid Rock neutralize'); return this.chainModify(0.75); } }, id: "solidrock", name: "Solid Rock", rating: 3, num: 116 }, "soundproof": { desc: "This Pokemon is immune to the effects of sound-based moves, which are: Bug Buzz, Chatter, Echoed Voice, Grasswhistle, Growl, Heal Bell, Hyper Voice, Metal Sound, Perish Song, Relic Song, Roar, Round, Screech, Sing, Snarl, Snore, Supersonic, and Uproar. This ability doesn't affect Heal Bell.", shortDesc: "This Pokemon is immune to sound-based moves, except Heal Bell.", onTryHit: function (target, source, move) { if (target !== source && move.isSoundBased) { this.add('-immune', target, '[msg]'); return null; } }, id: "soundproof", name: "Soundproof", rating: 2, num: 43 }, "speedboost": { desc: "At the end of every turn, this Pokemon's Speed increases by one stage (except the turn it switched in).", shortDesc: "This Pokemon's Speed is boosted by 1 at the end of each full turn on the field.", onResidualOrder: 26, onResidualSubOrder: 1, onResidual: function (pokemon) { if (pokemon.activeTurns) { this.boost({spe:1}); } }, id: "speedboost", name: "Speed Boost", rating: 4.5, num: 3 }, "stall": { desc: "This Pokemon moves last among Pokemon using the same or greater priority moves.", shortDesc: "This Pokemon moves last among Pokemon using the same or greater priority moves.", onModifyPriority: function (priority) { return priority - 0.1; }, id: "stall", name: "Stall", rating: -1, num: 100 }, "stancechange": { desc: "Only affects Aegislash. If this Pokemon uses a Physical or Special move, it changes to Blade forme. If this Pokemon uses King's Shield, it changes to Shield forme.", shortDesc: "The Pokemon changes form depending on how it battles.", onBeforeMovePriority: 11, onBeforeMove: function (attacker, defender, move) { if (attacker.template.baseSpecies !== 'Aegislash') return; if (move.category === 'Status' && move.id !== 'kingsshield') return; var targetSpecies = (move.id === 'kingsshield' ? 'Aegislash' : 'Aegislash-Blade'); if (attacker.template.species !== targetSpecies && attacker.formeChange(targetSpecies)) { this.add('-formechange', attacker, targetSpecies); } }, id: "stancechange", name: "Stance Change", rating: 4.5, num: 176 }, "static": { desc: "If an opponent contact attacks this Pokemon, there is a 30% chance that the opponent will become paralyzed.", shortDesc: "30% chance of paralyzing a Pokemon making contact with this Pokemon.", onAfterDamage: function (damage, target, source, effect) { if (effect && effect.isContact) { if (this.random(10) < 3) { source.trySetStatus('par', target, effect); } } }, id: "static", name: "Static", rating: 2, num: 9 }, "steadfast": { desc: "If this Pokemon flinches, its Speed increases by one stage.", shortDesc: "If this Pokemon flinches, its Speed is boosted by 1.", onFlinch: function (pokemon) { this.boost({spe: 1}); }, id: "steadfast", name: "Steadfast", rating: 1, num: 80 }, "stench": { desc: "This Pokemon's damaging moves that don't already have a flinch chance gain a 10% chance to cause flinch.", shortDesc: "This Pokemon's attacks without a chance to flinch have a 10% chance to flinch.", onModifyMove: function (move) { if (move.category !== "Status") { this.debug('Adding Stench flinch'); if (!move.secondaries) move.secondaries = []; for (var i = 0; i < move.secondaries.length; i++) { if (move.secondaries[i].volatileStatus === 'flinch') return; } move.secondaries.push({ chance: 10, volatileStatus: 'flinch' }); } }, id: "stench", name: "Stench", rating: 0, num: 1 }, "stickyhold": { desc: "This Pokemon cannot lose its held item due to another Pokemon's attack.", shortDesc: "This Pokemon cannot lose its held item due to another Pokemon's attack.", onTakeItem: function (item, pokemon, source) { if (source && source !== pokemon) return false; }, id: "stickyhold", name: "Sticky Hold", rating: 1, num: 60 }, "stormdrain": { desc: "During double battles, this Pokemon draws any single-target Water-type attack to itself. If an opponent uses an Water-type attack that affects multiple Pokemon, those targets will be hit. This ability does not affect Water Hidden Power, Judgment or Weather Ball. The user is immune to Water and its Special Attack is increased one stage when hit by one.", shortDesc: "This Pokemon draws Water moves to itself to boost Sp. Atk by 1; Water immunity.", onTryHit: function (target, source, move) { if (target !== source && move.type === 'Water') { if (!this.boost({spa:1})) { this.add('-immune', target, '[msg]'); } return null; } }, onAnyRedirectTargetPriority: 1, onAnyRedirectTarget: function (target, source, source2, move) { if (move.type !== 'Water') return; if (this.validTarget(this.effectData.target, source, move.target)) { move.accuracy = true; return this.effectData.target; } }, id: "stormdrain", name: "Storm Drain", rating: 3.5, num: 114 }, "strongjaw": { desc: "This Pokemon receives a 50% power boost for jaw attacks such as Bite and Crunch.", shortDesc: "This Pokemon's bite-based attacks do 1.5x damage.", onBasePowerPriority: 8, onBasePower: function (basePower, attacker, defender, move) { if (move.flags && move.flags['bite']) { return this.chainModify(1.5); } }, id: "strongjaw", name: "Strong Jaw", rating: 3, num: 173 }, "sturdy": { desc: "This Pokemon is immune to OHKO moves, and will survive with 1 HP if hit by an attack which would KO it while at full health.", shortDesc: "If this Pokemon is at full HP, it lives one hit with at least 1HP. OHKO moves fail on it.", onDamagePriority: -100, onDamage: function (damage, target, source, effect) { if (effect && effect.ohko) { this.add('-activate', target, 'Sturdy'); return 0; } if (target.hp === target.maxhp && damage >= target.hp && effect && effect.effectType === 'Move') { this.add('-activate', target, 'Sturdy'); return target.hp - 1; } }, id: "sturdy", name: "Sturdy", rating: 3, num: 5 }, "suctioncups": { desc: "This Pokemon cannot be forced to switch out by another Pokemon's attack or item.", shortDesc: "This Pokemon cannot be forced to switch out by another Pokemon's attack or item.", onDragOutPriority: 1, onDragOut: function (pokemon) { this.add('-activate', pokemon, 'ability: Suction Cups'); return null; }, id: "suctioncups", name: "Suction Cups", rating: 2.5, num: 21 }, "superluck": { desc: "This Pokemon's critical hit ratio is boosted by 1.", shortDesc: "This Pokemon's critical hit ratio is boosted by 1.", onModifyMove: function (move) { move.critRatio++; }, id: "superluck", name: "Super Luck", rating: 1, num: 105 }, "swarm": { desc: "When its health reaches 1/3 or less of its max HP, this Pokemon's Bug-type attacks do 1.5x damage.", shortDesc: "When this Pokemon has 1/3 or less of its max HP, its Bug attacks do 1.5x damage.", onModifyAtkPriority: 5, onModifyAtk: function (atk, attacker, defender, move) { if (move.type === 'Bug' && attacker.hp <= attacker.maxhp / 3) { this.debug('Swarm boost'); return this.chainModify(1.5); } }, onModifySpAPriority: 5, onModifySpA: function (atk, attacker, defender, move) { if (move.type === 'Bug' && attacker.hp <= attacker.maxhp / 3) { this.debug('Swarm boost'); return this.chainModify(1.5); } }, id: "swarm", name: "Swarm", rating: 2, num: 68 }, "sweetveil": { desc: "Prevents allies from being put to Sleep.", shortDesc: "Prevents allies from being put to Sleep.", id: "sweetveil", name: "Sweet Veil", onAllySetStatus: function (status, target, source, effect) { if (status.id === 'slp') { this.debug('Sweet Veil interrupts sleep'); return false; } }, onAllyTryHit: function (target, source, move) { if (move && move.id === 'yawn') { this.debug('Sweet Veil blocking yawn'); return false; } }, rating: 0, num: 175 }, "swiftswim": { desc: "If the weather is Rain Dance, this Pokemon's Speed is doubled.", shortDesc: "If the weather is Rain Dance, this Pokemon's Speed is doubled.", onModifySpe: function (speMod, pokemon) { if (this.isWeather(['raindance', 'primordialsea'])) { return this.chain(speMod, 2); } }, id: "swiftswim", name: "Swift Swim", rating: 2, num: 33 }, "symbiosis": { desc: "This Pokemon immediately passes its item to an ally after their item is consumed.", shortDesc: "This Pokemon passes its item to an ally after their item is consumed.", onAllyAfterUseItem: function (item, pokemon) { var sourceItem = this.effectData.target.getItem(); var noSharing = sourceItem.onTakeItem && sourceItem.onTakeItem(sourceItem, pokemon) === false; if (!sourceItem || noSharing) { return; } sourceItem = this.effectData.target.takeItem(); if (!sourceItem) { return; } if (pokemon.setItem(sourceItem)) { this.add('-activate', pokemon, 'ability: Symbiosis', sourceItem, '[of] ' + this.effectData.target); } }, id: "symbiosis", name: "Symbiosis", rating: 0, num: 180 }, "synchronize": { desc: "If an opponent burns, poisons or paralyzes this Pokemon, it receives the same condition.", shortDesc: "If another Pokemon burns/poisons/paralyzes this Pokemon, it also gets that status.", onAfterSetStatus: function (status, target, source) { if (!source || source === target) return; if (status.id === 'slp' || status.id === 'frz') return; source.trySetStatus(status, target); }, id: "synchronize", name: "Synchronize", rating: 3, num: 28 }, "tangledfeet": { desc: "When this Pokemon is confused, attacks targeting it have a 50% chance of missing.", shortDesc: "This Pokemon's evasion is doubled as long as it is confused.", onAccuracy: function (accuracy, target) { if (typeof accuracy !== 'number') return; if (target && target.volatiles['confusion']) { this.debug('Tangled Feet - decreasing accuracy'); return accuracy * 0.5; } }, id: "tangledfeet", name: "Tangled Feet", rating: 1, num: 77 }, "technician": { desc: "When this Pokemon uses an attack that has 60 Base Power or less (including Struggle), the move's Base Power receives a 50% boost. For example, a move with 60 Base Power effectively becomes a move with 90 Base Power.", shortDesc: "This Pokemon's attacks of 60 Base Power or less do 1.5x damage. Includes Struggle.", onBasePowerPriority: 8, onBasePower: function (basePower, attacker, defender, move) { if (basePower <= 60) { this.debug('Technician boost'); return this.chainModify(1.5); } }, id: "technician", name: "Technician", rating: 4, num: 101 }, "telepathy": { desc: "This Pokemon will not take damage from its allies' spread moves in double and triple battles.", shortDesc: "This Pokemon does not take damage from its allies' attacks.", onTryHit: function (target, source, move) { if (target.side === source.side && move.category !== 'Status') { this.add('-activate', target, 'ability: Telepathy'); return null; } }, id: "telepathy", name: "Telepathy", rating: 0, num: 140 }, "teravolt": { desc: "When this Pokemon uses any move, it nullifies the Ability of any active Pokemon that hinder or empower this Pokemon's attacks. These abilities include Battle Armor, Clear Body, Damp, Dry Skin, Filter, Flash Fire, Flower Gift, Heatproof, Herbivore, Hyper Cutter, Immunity, Inner Focus, Insomnia, Keen Eye, Leaf Guard, Levitate, Lightningrod, Limber, Magma Armor, Marvel Scale, Motor Drive, Oblivious, Own Tempo, Sand Veil, Shell Armor, Shield Dust, Simple, Snow Cloak, Solid Rock, Soundproof, Sticky Hold, Storm Drain, Sturdy, Suction Cups, Tangled Feet, Thick Fat, Unaware, Vital Spirit, Volt Absorb, Water Absorb, Water Veil, White Smoke and Wonder Guard.", shortDesc: "This Pokemon's moves ignore any Ability that could modify the effectiveness.", onStart: function (pokemon) { this.add('-ability', pokemon, 'Teravolt'); }, onAllyModifyPokemon: function (pokemon) { if (this.activePokemon === this.effectData.target && pokemon !== this.activePokemon) { pokemon.ignore['Ability'] = 'A'; } }, onFoeModifyPokemon: function (pokemon) { if (this.activePokemon === this.effectData.target) { pokemon.ignore['Ability'] = 'A'; } }, id: "teravolt", name: "Teravolt", rating: 3, num: 164 }, "thickfat": { desc: "This Pokemon receives half damage from Ice-type and Fire-type attacks.", shortDesc: "This Pokemon receives half damage from Fire- and Ice-type attacks.", onModifyAtkPriority: 6, onSourceModifyAtk: function (atk, attacker, defender, move) { if (move.type === 'Ice' || move.type === 'Fire') { this.debug('Thick Fat weaken'); return this.chainModify(0.5); } }, onModifySpAPriority: 5, onSourceModifySpA: function (atk, attacker, defender, move) { if (move.type === 'Ice' || move.type === 'Fire') { this.debug('Thick Fat weaken'); return this.chainModify(0.5); } }, id: "thickfat", name: "Thick Fat", rating: 3, num: 47 }, "tintedlens": { desc: "This Pokemon's attacks that are not very effective on a target do double damage.", shortDesc: "This Pokemon's attacks that are not very effective on a target do double damage.", onModifyDamage: function (damage, source, target, move) { if (target.runEffectiveness(move) < 0) { this.debug('Tinted Lens boost'); return this.chainModify(2); } }, id: "tintedlens", name: "Tinted Lens", rating: 4, num: 110 }, "torrent": { desc: "When its health reaches 1/3 or less of its max HP, this Pokemon's Water-type attacks do 1.5x damage.", shortDesc: "When this Pokemon has 1/3 or less of its max HP, its Water attacks do 1.5x damage.", onModifyAtkPriority: 5, onModifyAtk: function (atk, attacker, defender, move) { if (move.type === 'Water' && attacker.hp <= attacker.maxhp / 3) { this.debug('Torrent boost'); return this.chainModify(1.5); } }, onModifySpAPriority: 5, onModifySpA: function (atk, attacker, defender, move) { if (move.type === 'Water' && attacker.hp <= attacker.maxhp / 3) { this.debug('Torrent boost'); return this.chainModify(1.5); } }, id: "torrent", name: "Torrent", rating: 2, num: 67 }, "toxicboost": { desc: "When this Pokemon is poisoned, its physical attacks do 1.5x damage.", shortDesc: "When this Pokemon is poisoned, its physical attacks do 1.5x damage.", onBasePowerPriority: 8, onBasePower: function (basePower, attacker, defender, move) { if ((attacker.status === 'psn' || attacker.status === 'tox') && move.category === 'Physical') { return this.chainModify(1.5); } }, id: "toxicboost", name: "Toxic Boost", rating: 3, num: 137 }, "toughclaws": { desc: "This Pokemon's contact attacks do 33% more damage.", shortDesc: "This Pokemon's contact attacks do 1.33x damage.", onBasePowerPriority: 8, onBasePower: function (basePower, attacker, defender, move) { if (move.isContact) { return this.chainModify(1.33); } }, id: "toughclaws", name: "Tough Claws", rating: 3, num: 181 }, "trace": { desc: "When this Pokemon enters the field, it temporarily copies an opponent's ability. This ability remains with this Pokemon until it leaves the field.", shortDesc: "On switch-in, or when it can, this Pokemon copies a random adjacent foe's Ability.", onUpdate: function (pokemon) { var possibleTargets = []; for (var i = 0; i < pokemon.side.foe.active.length; i++) { if (pokemon.side.foe.active[i] && !pokemon.side.foe.active[i].fainted) possibleTargets.push(pokemon.side.foe.active[i]); } while (possibleTargets.length) { var rand = 0; if (possibleTargets.length > 1) rand = this.random(possibleTargets.length); var target = possibleTargets[rand]; var ability = this.getAbility(target.ability); var bannedAbilities = {flowergift:1, forecast:1, illusion:1, imposter:1, multitype:1, stancechange:1, trace:1, zenmode:1}; if (bannedAbilities[target.ability]) { possibleTargets.splice(rand, 1); continue; } this.add('-ability', pokemon, ability, '[from] ability: Trace', '[of] ' + target); pokemon.setAbility(ability); return; } }, id: "trace", name: "Trace", rating: 3.5, num: 36 }, "truant": { desc: "After this Pokemon is switched into battle, it skips every other turn.", shortDesc: "This Pokemon skips every other turn instead of using a move.", onBeforeMovePriority: 9, onBeforeMove: function (pokemon, target, move) { if (pokemon.removeVolatile('truant')) { this.add('cant', pokemon, 'ability: Truant', move); return false; } pokemon.addVolatile('truant'); }, effect: { duration: 2 }, id: "truant", name: "Truant", rating: -2, num: 54 }, "turboblaze": { desc: "When this Pokemon uses any move, it nullifies the Ability of any active Pokemon that hinder or empower this Pokemon's attacks. These abilities include Battle Armor, Clear Body, Damp, Dry Skin, Filter, Flash Fire, Flower Gift, Heatproof, Herbivore, Hyper Cutter, Immunity, Inner Focus, Insomnia, Keen Eye, Leaf Guard, Levitate, Lightningrod, Limber, Magma Armor, Marvel Scale, Motor Drive, Oblivious, Own Tempo, Sand Veil, Shell Armor, Shield Dust, Simple, Snow Cloak, Solid Rock, Soundproof, Sticky Hold, Storm Drain, Sturdy, Suction Cups, Tangled Feet, Thick Fat, Unaware, Vital Spirit, Volt Absorb, Water Absorb, Water Veil, White Smoke and Wonder Guard.", shortDesc: "This Pokemon's moves ignore any Ability that could modify the effectiveness.", onStart: function (pokemon) { this.add('-ability', pokemon, 'Turboblaze'); }, onAllyModifyPokemon: function (pokemon) { if (this.activePokemon === this.effectData.target && pokemon !== this.activePokemon) { pokemon.ignore['Ability'] = 'A'; } }, onFoeModifyPokemon: function (pokemon) { if (this.activePokemon === this.effectData.target) { pokemon.ignore['Ability'] = 'A'; } }, id: "turboblaze", name: "Turboblaze", rating: 3, num: 163 }, "unaware": { desc: "This Pokemon ignores an opponent's stat boosts for Attack, Defense, Special Attack and Special Defense. These boosts will still affect Base Power calculation for Punishment and Stored Power.", shortDesc: "This Pokemon ignores other Pokemon's stat changes when taking or doing damage.", id: "unaware", name: "Unaware", onModifyMove: function (move, user, target) { move.ignoreEvasion = true; move.ignoreDefensive = true; }, onSourceModifyMove: function (move, user, target) { if (user.hasAbility(['moldbreaker', 'turboblaze', 'teravolt'])) return; move.ignoreAccuracy = true; move.ignoreOffensive = true; }, rating: 3, num: 109 }, "unburden": { desc: "Doubles this Pokemon's Speed if it loses its held item (such as by eating Berries, using Gems, or via Thief, Knock Off, etc).", shortDesc: "Speed is doubled on held item loss; boost is lost if it switches, gets new item/Ability.", onUseItem: function (item, pokemon) { pokemon.addVolatile('unburden'); }, onTakeItem: function (item, pokemon) { pokemon.addVolatile('unburden'); }, effect: { onModifySpe: function (speMod, pokemon) { if (pokemon.ignore['Ability'] === true || pokemon.ability !== 'unburden') { pokemon.removeVolatile('unburden'); return; } if (!pokemon.item) { return this.chain(speMod, 2); } } }, id: "unburden", name: "Unburden", rating: 3.5, num: 84 }, "unnerve": { desc: "While this Pokemon is active, prevents opposing Pokemon from using their Berries.", shortDesc: "While this Pokemon is active, prevents opposing Pokemon from using their Berries.", onStart: function (pokemon) { this.add('-ability', pokemon, 'Unnerve', pokemon.side.foe); }, onFoeEatItem: false, id: "unnerve", name: "Unnerve", rating: 1, num: 127 }, "victorystar": { desc: "Raises every friendly Pokemon's Accuracy, including this Pokemon's, by 10% (multiplied).", shortDesc: "This Pokemon and its allies' moves have their accuracy boosted to 1.1x.", onAllyModifyMove: function (move) { if (typeof move.accuracy === 'number') { move.accuracy *= 1.1; } }, id: "victorystar", name: "Victory Star", rating: 2, num: 162 }, "vitalspirit": { desc: "This Pokemon cannot fall asleep (Rest will fail if it tries to use it). Gaining this Ability while asleep cures it.", shortDesc: "This Pokemon cannot fall asleep. Gaining this Ability while asleep cures it.", onUpdate: function (pokemon) { if (pokemon.status === 'slp') { pokemon.cureStatus(); } }, onImmunity: function (type) { if (type === 'slp') return false; }, id: "vitalspirit", name: "Vital Spirit", rating: 2, num: 72 }, "voltabsorb": { desc: "This Pokemon is immune to Electric moves. If hit by an Electric move, it recovers 25% of its max HP.", shortDesc: "This Pokemon heals 1/4 of its max HP when hit by Electric moves; Electric immunity.", onTryHit: function (target, source, move) { if (target !== source && move.type === 'Electric') { if (!this.heal(target.maxhp / 4)) { this.add('-immune', target, '[msg]'); } return null; } }, id: "voltabsorb", name: "Volt Absorb", rating: 3.5, num: 10 }, "waterabsorb": { desc: "This Pokemon is immune to Water moves. If hit by an Water move, it recovers 25% of its max HP.", shortDesc: "This Pokemon heals 1/4 of its max HP when hit by Water moves; Water immunity.", onTryHit: function (target, source, move) { if (target !== source && move.type === 'Water') { if (!this.heal(target.maxhp / 4)) { this.add('-immune', target, '[msg]'); } return null; } }, id: "waterabsorb", name: "Water Absorb", rating: 3.5, num: 11 }, "waterveil": { desc: "This Pokemon cannot become burned. Gaining this Ability while burned cures it.", shortDesc: "This Pokemon cannot be burned. Gaining this Ability while burned cures it.", onUpdate: function (pokemon) { if (pokemon.status === 'brn') { pokemon.cureStatus(); } }, onImmunity: function (type, pokemon) { if (type === 'brn') return false; }, id: "waterveil", name: "Water Veil", rating: 1.5, num: 41 }, "weakarmor": { desc: "Causes physical moves to lower the Pokemon's Defense and increase its Speed stat by one stage.", shortDesc: "If a physical attack hits this Pokemon, Defense is lowered 1 and Speed is boosted 1.", onAfterDamage: function (damage, target, source, move) { if (move.category === 'Physical') { this.boost({spe:1, def:-1}); } }, id: "weakarmor", name: "Weak Armor", rating: 0, num: 133 }, "whitesmoke": { desc: "Opponents cannot reduce this Pokemon's stats; they can, however, modify stat changes with Power Swap, Guard Swap and Heart Swap and inflict stat boosts with Swagger and Flatter. This ability does not prevent self-inflicted stat reductions. [Field Effect]\u00a0If this Pokemon is in the lead spot, the rate of wild Pokemon battles decreases by 50%.", shortDesc: "Prevents other Pokemon from lowering this Pokemon's stat stages.", onBoost: function (boost, target, source, effect) { if (source && target === source) return; var showMsg = false; for (var i in boost) { if (boost[i] < 0) { delete boost[i]; showMsg = true; } } if (showMsg && !effect.secondaries) this.add("-fail", target, "unboost", "[from] ability: White Smoke", "[of] " + target); }, id: "whitesmoke", name: "White Smoke", rating: 2, num: 73 }, "wonderguard": { desc: "This Pokemon only receives damage from attacks belonging to types that cause Super Effective to this Pokemon. Wonder Guard does not protect a Pokemon from status ailments (burn, freeze, paralysis, poison, sleep, Toxic or any of their side effects or damage), recoil damage nor the moves Beat Up, Bide, Doom Desire, Fire Fang, Future Sight, Hail, Leech Seed, Sandstorm, Spikes, Stealth Rock and Struggle. Wonder Guard cannot be Skill Swapped nor Role Played. Trace, however, does copy Wonder Guard.", shortDesc: "This Pokemon can only be damaged by super effective moves and indirect damage.", onTryHit: function (target, source, move) { if (target === source || move.category === 'Status' || move.type === '???' || move.id === 'struggle' || move.isFutureMove) return; this.debug('Wonder Guard immunity: ' + move.id); if (target.runEffectiveness(move) <= 0) { this.add('-activate', target, 'ability: Wonder Guard'); return null; } }, id: "wonderguard", name: "Wonder Guard", rating: 5, num: 25 }, "wonderskin": { desc: "Causes the chance of a status move working to be halved. It does not affect moves that inflict status as a secondary effect like Thunder's chance to paralyze.", shortDesc: "All status moves with a set % accuracy are 50% accurate if used on this Pokemon.", onAccuracyPriority: 10, onAccuracy: function (accuracy, target, source, move) { if (move.category === 'Status' && typeof move.accuracy === 'number') { this.debug('Wonder Skin - setting accuracy to 50'); return 50; } }, id: "wonderskin", name: "Wonder Skin", rating: 3, num: 147 }, "zenmode": { desc: "When Darmanitan's HP drops to below half, it will enter Zen Mode at the end of the turn. If it loses its ability, or recovers HP to above half while in Zen mode, it will change back. This ability only works on Darmanitan, even if it is copied by Role Play, Entrainment, or swapped with Skill Swap.", shortDesc: "If this Pokemon is Darmanitan, it changes to Zen Mode whenever it is below half HP.", onResidualOrder: 27, onResidual: function (pokemon) { if (pokemon.baseTemplate.species !== 'Darmanitan') { return; } if (pokemon.hp <= pokemon.maxhp / 2 && pokemon.template.speciesid === 'darmanitan') { pokemon.addVolatile('zenmode'); } else if (pokemon.hp > pokemon.maxhp / 2 && pokemon.template.speciesid === 'darmanitanzen') { pokemon.removeVolatile('zenmode'); } }, effect: { onStart: function (pokemon) { if (pokemon.formeChange('Darmanitan-Zen')) { this.add('-formechange', pokemon, 'Darmanitan-Zen'); } else { return false; } }, onEnd: function (pokemon) { if (pokemon.formeChange('Darmanitan')) { this.add('-formechange', pokemon, 'Darmanitan'); } else { return false; } }, onUpdate: function (pokemon) { if (!pokemon.hasAbility('zenmode')) { pokemon.transformed = false; pokemon.removeVolatile('zenmode'); } } }, id: "zenmode", name: "Zen Mode", rating: -1, num: 161 }, // CAP "mountaineer": { desc: "On switch-in, this Pokemon avoids all Rock-type attacks and Stealth Rock.", shortDesc: "This Pokemon avoids all Rock-type attacks and hazards when switching in.", onDamage: function (damage, target, source, effect) { if (effect && effect.id === 'stealthrock') { return false; } }, onImmunity: function (type, target) { if (type === 'Rock' && !target.activeTurns) { return false; } }, id: "mountaineer", isNonstandard: true, name: "Mountaineer", rating: 3.5, num: -2 }, "rebound": { desc: "On switch-in, this Pokemon blocks certain status moves and uses the move itself.", shortDesc: "It can reflect the effect of status moves when switching in.", id: "rebound", isNonstandard: true, name: "Rebound", onTryHitPriority: 1, onTryHit: function (target, source, move) { if (this.effectData.target.activeTurns) return; if (target === source) return; if (move.hasBounced) return; if (typeof move.isBounceable === 'undefined') { move.isBounceable = !!(move.category === 'Status' && (move.status || move.boosts || move.volatileStatus === 'confusion' || move.forceSwitch)); } if (move.isBounceable) { var newMove = this.getMoveCopy(move.id); newMove.hasBounced = true; this.useMove(newMove, target, source); return null; } }, onAllyTryHitSide: function (target, source, move) { if (this.effectData.target.activeTurns) return; if (target.side === source.side) return; if (move.hasBounced) return; if (typeof move.isBounceable === 'undefined') { move.isBounceable = !!(move.category === 'Status' && (move.status || move.boosts || move.volatileStatus === 'confusion' || move.forceSwitch)); } if (move.isBounceable) { var newMove = this.getMoveCopy(move.id); newMove.hasBounced = true; this.useMove(newMove, target, source); return null; } }, effect: { duration: 1 }, rating: 4, num: -3 }, "persistent": { desc: "The duration of certain field effects is increased by 2 turns if used by this Pokemon.", shortDesc: "Increases the duration of many field effects by two turns when used by this Pokemon.", id: "persistent", isNonstandard: true, name: "Persistent", // implemented in the corresponding move rating: 4, num: -4 } };
mit
jaredkoontz/leetcode
algorithms/cpp/findPeakElement/findPeakElement.cpp
3304
// Source : https://oj.leetcode.com/problems/find-peak-element/ // Author : Hao Chen // Date : 2014-12-05 /********************************************************************************** * * A peak element is an element that is greater than its neighbors. * * Given an input array where num[i] ≠ num[i+1], find a peak element and return its index. * * You may imagine that num[-1] = num[n] = -∞. * * For example, in array [1, 2, 3, 1], 3 is a peak element and your function should return the index number 2. * * click to show spoilers. * * Note: * Your solution should be in logarithmic complexity. * * Credits:Special thanks to @ts for adding this problem and creating all test cases. * **********************************************************************************/ #include <iostream> #include <vector> using namespace std; /* * Binary search is common idea here. * * However, you need to think about two senarios: * * 1) Becasue we need check `num[mid-1]`, `num[mid]`, `num[mid+1]`, * So, we need make sure there hasn't out-of-boundary issue. * * * * 2) There are multiple Peak elements. * * For example: [1,2,1,2,1], or [ 1,2,3,1,2,1] * * LeetCode doesn't tell you what the expected result is. I guess: * * 2.1) for [1,2,1,2,1] you can return either 1 or 3, because both them are peak elements * * 2.1) for [1,2,3,2,4,2,1] it should return 4, because num[4] is the real peak. but Leetcode accept either 2 or 4 * */ int findPeakElement(const vector<int> &num) { int n = num.size(); int low = 0; int high = n - 1; int mid = 0, v1, v2; while ( low < high ) { // Find the index of middle element mid = low + ( high - low ) / 2; // Compare middle element with its neighbours (if neighbours exist) if ( ( mid == 0 || num[mid] > num[mid-1] ) && ( mid == n-1 || num[mid] > num[mid+1] ) ){ return mid; } // If middle element is not peak and its left neighbor is greater than it // then left half must have a peak element if (mid >0 && num[mid-1] > num[mid]){ high = mid - 1; // If middle element is not peak and its right neighbor is greater than it // then right half must have a peak element }else{ low = mid + 1; } } return low; } void printVector(vector<int> &n) { cout << "[ "; int i; for(i=0; i<n.size(); i++){ cout << n[i] << (i==n.size()-1 ? " ]" : ", "); } cout << endl; } void test(int a[], int n) { vector<int> v(a, a+n); cout << "Peak Index = " << findPeakElement(v) << "\t"; printVector(v); } #define TEST(a) test(a, sizeof(a)/sizeof(a[0])) int main(int argc, char**argv) { int n0[] = {1}; TEST(n0); int n1[] = {1,2}; TEST(n1); int n2[] = {2,1}; TEST(n2); int n3[] = {1,2,3}; TEST(n3); int n4[] = {3,2,1}; TEST(n4); int n5[] = {1,2,3,2}; TEST(n5); int n6[] = {0,1,2,9,7,5,4,2,1}; TEST(n6); int n7[] = {1,2,1,2,1}; TEST(n7); int n8[] = {1,2,1,2,3,1}; TEST(n8); int n9[] = {1,2,3,2,4,2,1}; TEST(n9); int n10[] = {1,3,1,2,1,3,1}; TEST(n10); return 0; }
mit
bkaankose/UWPCommunityToolkit
Microsoft.Toolkit.Uwp.Services/Services/Facebook/FacebookRequestSource.cs
4759
// ****************************************************************** // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THE CODE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH // THE CODE OR THE USE OR OTHER DEALINGS IN THE CODE. // ****************************************************************** using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Newtonsoft.Json; using Windows.Foundation.Collections; using winsdkfb; using winsdkfb.Graph; namespace Microsoft.Toolkit.Uwp.Services.Facebook { /// <summary> /// Type to handle paged requests to Facebook Graph. /// </summary> /// <typeparam name="T">Strong type to return.</typeparam> public class FacebookRequestSource<T> : Collections.IIncrementalSource<T> { private bool _isFirstCall = true; private FBPaginatedArray _paginatedArray; private FacebookDataConfig _config; private string _fields; private PropertySet _propertySet; private FBJsonClassFactory _factory; private string _limit; private int _maxPages; /// <summary> /// Initializes a new instance of the <see cref="FacebookRequestSource{T}"/> class. /// </summary> public FacebookRequestSource() { } /// <summary> /// Initializes a new instance of the <see cref="FacebookRequestSource{T}"/> class. /// </summary> /// <param name="config">Config containing query information.</param> /// <param name="fields">Comma-separated list of properties expected in the JSON response. Accompanying properties must be found on the strong-typed T.</param> /// <param name="limit">A string representation of the number of records for page - i.e. pageSize.</param> /// <param name="maxPages">Upper limit of pages to return.</param> public FacebookRequestSource(FacebookDataConfig config, string fields, string limit, int maxPages) { _config = config; _fields = fields; _limit = limit; _maxPages = maxPages; _propertySet = new PropertySet { { "fields", _fields }, { "limit", _limit } }; _factory = new FBJsonClassFactory(s => JsonConvert.DeserializeObject(s, typeof(T))); // FBPaginatedArray does not allow us to set page size per request so we must go with first supplied - see https://github.com/Microsoft/winsdkfb/issues/221 _paginatedArray = new FBPaginatedArray(_config.Query, _propertySet, _factory); } /// <summary> /// Returns strong typed page of data. /// </summary> /// <param name="pageIndex">Page number.</param> /// <param name="pageSize">Size of page.</param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>Strong typed page of data.</returns> public async Task<IEnumerable<T>> GetPagedItemsAsync(int pageIndex, int pageSize, CancellationToken cancellationToken = default(CancellationToken)) { if (_isFirstCall) { var result = await _paginatedArray.FirstAsync(); return ProcessResult(result); } else { if (cancellationToken.IsCancellationRequested) { return null; } if (_paginatedArray.HasNext && (pageIndex < _maxPages)) { var result = await _paginatedArray.NextAsync(); return ProcessResult(result); } else { return null; } } } private IEnumerable<T> ProcessResult(FBResult result) { List<T> items = new List<T>(); if (result.Succeeded) { IReadOnlyList<object> processedResults = (IReadOnlyList<object>)result.Object; foreach (T processedResult in processedResults) { items.Add(processedResult); } _isFirstCall = false; return items; } throw new Exception(result.ErrorInfo?.Message); } } }
mit
mcliment/DefinitelyTyped
types/carbon__icons-react/lib/letter--Ww/20.d.ts
218
import * as React from "react"; import { CarbonIconProps } from "../../"; declare const LetterWw20: React.ForwardRefExoticComponent< CarbonIconProps & React.RefAttributes<SVGSVGElement> >; export default LetterWw20;
mit
CKOTech/checkout-magento-plugin
app/code/community/Checkoutcom/Ckopayment/Block/Customer/Cards.php
1138
<?php class Checkoutcom_Ckopayment_Block_Customer_Cards extends Mage_Core_Block_Template { /** * Return array with customer card list * * @return array */ public function getCustomerCardList() { $result = array(); $customerId = Mage::getModel('ckopayment/checkoutcomCards')->getCustomerId(); if (empty($customerId)) { return $result; } $customerCardModel = Mage::getModel('ckopayment/customerCard'); $cardCollection = $customerCardModel->getCustomerCardList($customerId); if (!$cardCollection->count()) { return $result; } foreach ($cardCollection as $index => $card) { if ($card->getSaveCard() == '') { continue; } $result[$index]['title'] = sprintf('•••• %s', $card->getLastFour()); $result[$index]['value'] = $card->getId(); //$customerCardModel->getCardSecret($card->getId(), $card->getLastFour(), $card->getCardScheme()); $result[$index]['type'] = $card->getCardScheme(); } return $result; } }
mit
lunastorm/wissbi
3rd_party/libcxx/test/strings/basic.string/string.modifiers/string_replace/size_size_size_char.pass.cpp
20736
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <string> // basic_string<charT,traits,Allocator>& // replace(size_type pos, size_type n1, size_type n2, charT c); #include <string> #include <stdexcept> #include <algorithm> #include <cassert> typedef std::string S; void test(S s, S::size_type pos, S::size_type n1, S::size_type n2, S::value_type c, S expected) { S::size_type old_size = s.size(); S s0 = s; try { s.replace(pos, n1, n2, c); assert(s.__invariants()); assert(pos <= old_size); assert(s == expected); S::size_type xlen = std::min(n1, old_size - pos); S::size_type rlen = n2; assert(s.size() == old_size - xlen + rlen); } catch (std::out_of_range&) { assert(pos > old_size); assert(s == s0); } } void test0() { test(S(""), 0, 0, 0, '2', S("")); test(S(""), 0, 0, 5, '2', S("22222")); test(S(""), 0, 0, 10, '2', S("2222222222")); test(S(""), 0, 0, 20, '2', S("22222222222222222222")); test(S(""), 0, 1, 0, '2', S("")); test(S(""), 0, 1, 5, '2', S("22222")); test(S(""), 0, 1, 10, '2', S("2222222222")); test(S(""), 0, 1, 20, '2', S("22222222222222222222")); test(S(""), 1, 0, 0, '2', S("can't happen")); test(S(""), 1, 0, 5, '2', S("can't happen")); test(S(""), 1, 0, 10, '2', S("can't happen")); test(S(""), 1, 0, 20, '2', S("can't happen")); test(S("abcde"), 0, 0, 0, '2', S("abcde")); test(S("abcde"), 0, 0, 5, '2', S("22222abcde")); test(S("abcde"), 0, 0, 10, '2', S("2222222222abcde")); test(S("abcde"), 0, 0, 20, '2', S("22222222222222222222abcde")); test(S("abcde"), 0, 1, 0, '2', S("bcde")); test(S("abcde"), 0, 1, 5, '2', S("22222bcde")); test(S("abcde"), 0, 1, 10, '2', S("2222222222bcde")); test(S("abcde"), 0, 1, 20, '2', S("22222222222222222222bcde")); test(S("abcde"), 0, 2, 0, '2', S("cde")); test(S("abcde"), 0, 2, 5, '2', S("22222cde")); test(S("abcde"), 0, 2, 10, '2', S("2222222222cde")); test(S("abcde"), 0, 2, 20, '2', S("22222222222222222222cde")); test(S("abcde"), 0, 4, 0, '2', S("e")); test(S("abcde"), 0, 4, 5, '2', S("22222e")); test(S("abcde"), 0, 4, 10, '2', S("2222222222e")); test(S("abcde"), 0, 4, 20, '2', S("22222222222222222222e")); test(S("abcde"), 0, 5, 0, '2', S("")); test(S("abcde"), 0, 5, 5, '2', S("22222")); test(S("abcde"), 0, 5, 10, '2', S("2222222222")); test(S("abcde"), 0, 5, 20, '2', S("22222222222222222222")); test(S("abcde"), 0, 6, 0, '2', S("")); test(S("abcde"), 0, 6, 5, '2', S("22222")); test(S("abcde"), 0, 6, 10, '2', S("2222222222")); test(S("abcde"), 0, 6, 20, '2', S("22222222222222222222")); test(S("abcde"), 1, 0, 0, '2', S("abcde")); test(S("abcde"), 1, 0, 5, '2', S("a22222bcde")); test(S("abcde"), 1, 0, 10, '2', S("a2222222222bcde")); test(S("abcde"), 1, 0, 20, '2', S("a22222222222222222222bcde")); test(S("abcde"), 1, 1, 0, '2', S("acde")); test(S("abcde"), 1, 1, 5, '2', S("a22222cde")); test(S("abcde"), 1, 1, 10, '2', S("a2222222222cde")); test(S("abcde"), 1, 1, 20, '2', S("a22222222222222222222cde")); test(S("abcde"), 1, 2, 0, '2', S("ade")); test(S("abcde"), 1, 2, 5, '2', S("a22222de")); test(S("abcde"), 1, 2, 10, '2', S("a2222222222de")); test(S("abcde"), 1, 2, 20, '2', S("a22222222222222222222de")); test(S("abcde"), 1, 3, 0, '2', S("ae")); test(S("abcde"), 1, 3, 5, '2', S("a22222e")); test(S("abcde"), 1, 3, 10, '2', S("a2222222222e")); test(S("abcde"), 1, 3, 20, '2', S("a22222222222222222222e")); test(S("abcde"), 1, 4, 0, '2', S("a")); test(S("abcde"), 1, 4, 5, '2', S("a22222")); test(S("abcde"), 1, 4, 10, '2', S("a2222222222")); test(S("abcde"), 1, 4, 20, '2', S("a22222222222222222222")); test(S("abcde"), 1, 5, 0, '2', S("a")); test(S("abcde"), 1, 5, 5, '2', S("a22222")); test(S("abcde"), 1, 5, 10, '2', S("a2222222222")); test(S("abcde"), 1, 5, 20, '2', S("a22222222222222222222")); test(S("abcde"), 2, 0, 0, '2', S("abcde")); test(S("abcde"), 2, 0, 5, '2', S("ab22222cde")); test(S("abcde"), 2, 0, 10, '2', S("ab2222222222cde")); test(S("abcde"), 2, 0, 20, '2', S("ab22222222222222222222cde")); test(S("abcde"), 2, 1, 0, '2', S("abde")); test(S("abcde"), 2, 1, 5, '2', S("ab22222de")); test(S("abcde"), 2, 1, 10, '2', S("ab2222222222de")); test(S("abcde"), 2, 1, 20, '2', S("ab22222222222222222222de")); test(S("abcde"), 2, 2, 0, '2', S("abe")); test(S("abcde"), 2, 2, 5, '2', S("ab22222e")); test(S("abcde"), 2, 2, 10, '2', S("ab2222222222e")); test(S("abcde"), 2, 2, 20, '2', S("ab22222222222222222222e")); test(S("abcde"), 2, 3, 0, '2', S("ab")); test(S("abcde"), 2, 3, 5, '2', S("ab22222")); test(S("abcde"), 2, 3, 10, '2', S("ab2222222222")); test(S("abcde"), 2, 3, 20, '2', S("ab22222222222222222222")); test(S("abcde"), 2, 4, 0, '2', S("ab")); test(S("abcde"), 2, 4, 5, '2', S("ab22222")); test(S("abcde"), 2, 4, 10, '2', S("ab2222222222")); test(S("abcde"), 2, 4, 20, '2', S("ab22222222222222222222")); test(S("abcde"), 4, 0, 0, '2', S("abcde")); test(S("abcde"), 4, 0, 5, '2', S("abcd22222e")); test(S("abcde"), 4, 0, 10, '2', S("abcd2222222222e")); test(S("abcde"), 4, 0, 20, '2', S("abcd22222222222222222222e")); test(S("abcde"), 4, 1, 0, '2', S("abcd")); test(S("abcde"), 4, 1, 5, '2', S("abcd22222")); test(S("abcde"), 4, 1, 10, '2', S("abcd2222222222")); test(S("abcde"), 4, 1, 20, '2', S("abcd22222222222222222222")); test(S("abcde"), 4, 2, 0, '2', S("abcd")); test(S("abcde"), 4, 2, 5, '2', S("abcd22222")); test(S("abcde"), 4, 2, 10, '2', S("abcd2222222222")); test(S("abcde"), 4, 2, 20, '2', S("abcd22222222222222222222")); test(S("abcde"), 5, 0, 0, '2', S("abcde")); test(S("abcde"), 5, 0, 5, '2', S("abcde22222")); test(S("abcde"), 5, 0, 10, '2', S("abcde2222222222")); test(S("abcde"), 5, 0, 20, '2', S("abcde22222222222222222222")); test(S("abcde"), 5, 1, 0, '2', S("abcde")); test(S("abcde"), 5, 1, 5, '2', S("abcde22222")); test(S("abcde"), 5, 1, 10, '2', S("abcde2222222222")); test(S("abcde"), 5, 1, 20, '2', S("abcde22222222222222222222")); } void test1() { test(S("abcde"), 6, 0, 0, '2', S("can't happen")); test(S("abcde"), 6, 0, 5, '2', S("can't happen")); test(S("abcde"), 6, 0, 10, '2', S("can't happen")); test(S("abcde"), 6, 0, 20, '2', S("can't happen")); test(S("abcdefghij"), 0, 0, 0, '2', S("abcdefghij")); test(S("abcdefghij"), 0, 0, 5, '2', S("22222abcdefghij")); test(S("abcdefghij"), 0, 0, 10, '2', S("2222222222abcdefghij")); test(S("abcdefghij"), 0, 0, 20, '2', S("22222222222222222222abcdefghij")); test(S("abcdefghij"), 0, 1, 0, '2', S("bcdefghij")); test(S("abcdefghij"), 0, 1, 5, '2', S("22222bcdefghij")); test(S("abcdefghij"), 0, 1, 10, '2', S("2222222222bcdefghij")); test(S("abcdefghij"), 0, 1, 20, '2', S("22222222222222222222bcdefghij")); test(S("abcdefghij"), 0, 5, 0, '2', S("fghij")); test(S("abcdefghij"), 0, 5, 5, '2', S("22222fghij")); test(S("abcdefghij"), 0, 5, 10, '2', S("2222222222fghij")); test(S("abcdefghij"), 0, 5, 20, '2', S("22222222222222222222fghij")); test(S("abcdefghij"), 0, 9, 0, '2', S("j")); test(S("abcdefghij"), 0, 9, 5, '2', S("22222j")); test(S("abcdefghij"), 0, 9, 10, '2', S("2222222222j")); test(S("abcdefghij"), 0, 9, 20, '2', S("22222222222222222222j")); test(S("abcdefghij"), 0, 10, 0, '2', S("")); test(S("abcdefghij"), 0, 10, 5, '2', S("22222")); test(S("abcdefghij"), 0, 10, 10, '2', S("2222222222")); test(S("abcdefghij"), 0, 10, 20, '2', S("22222222222222222222")); test(S("abcdefghij"), 0, 11, 0, '2', S("")); test(S("abcdefghij"), 0, 11, 5, '2', S("22222")); test(S("abcdefghij"), 0, 11, 10, '2', S("2222222222")); test(S("abcdefghij"), 0, 11, 20, '2', S("22222222222222222222")); test(S("abcdefghij"), 1, 0, 0, '2', S("abcdefghij")); test(S("abcdefghij"), 1, 0, 5, '2', S("a22222bcdefghij")); test(S("abcdefghij"), 1, 0, 10, '2', S("a2222222222bcdefghij")); test(S("abcdefghij"), 1, 0, 20, '2', S("a22222222222222222222bcdefghij")); test(S("abcdefghij"), 1, 1, 0, '2', S("acdefghij")); test(S("abcdefghij"), 1, 1, 5, '2', S("a22222cdefghij")); test(S("abcdefghij"), 1, 1, 10, '2', S("a2222222222cdefghij")); test(S("abcdefghij"), 1, 1, 20, '2', S("a22222222222222222222cdefghij")); test(S("abcdefghij"), 1, 4, 0, '2', S("afghij")); test(S("abcdefghij"), 1, 4, 5, '2', S("a22222fghij")); test(S("abcdefghij"), 1, 4, 10, '2', S("a2222222222fghij")); test(S("abcdefghij"), 1, 4, 20, '2', S("a22222222222222222222fghij")); test(S("abcdefghij"), 1, 8, 0, '2', S("aj")); test(S("abcdefghij"), 1, 8, 5, '2', S("a22222j")); test(S("abcdefghij"), 1, 8, 10, '2', S("a2222222222j")); test(S("abcdefghij"), 1, 8, 20, '2', S("a22222222222222222222j")); test(S("abcdefghij"), 1, 9, 0, '2', S("a")); test(S("abcdefghij"), 1, 9, 5, '2', S("a22222")); test(S("abcdefghij"), 1, 9, 10, '2', S("a2222222222")); test(S("abcdefghij"), 1, 9, 20, '2', S("a22222222222222222222")); test(S("abcdefghij"), 1, 10, 0, '2', S("a")); test(S("abcdefghij"), 1, 10, 5, '2', S("a22222")); test(S("abcdefghij"), 1, 10, 10, '2', S("a2222222222")); test(S("abcdefghij"), 1, 10, 20, '2', S("a22222222222222222222")); test(S("abcdefghij"), 5, 0, 0, '2', S("abcdefghij")); test(S("abcdefghij"), 5, 0, 5, '2', S("abcde22222fghij")); test(S("abcdefghij"), 5, 0, 10, '2', S("abcde2222222222fghij")); test(S("abcdefghij"), 5, 0, 20, '2', S("abcde22222222222222222222fghij")); test(S("abcdefghij"), 5, 1, 0, '2', S("abcdeghij")); test(S("abcdefghij"), 5, 1, 5, '2', S("abcde22222ghij")); test(S("abcdefghij"), 5, 1, 10, '2', S("abcde2222222222ghij")); test(S("abcdefghij"), 5, 1, 20, '2', S("abcde22222222222222222222ghij")); test(S("abcdefghij"), 5, 2, 0, '2', S("abcdehij")); test(S("abcdefghij"), 5, 2, 5, '2', S("abcde22222hij")); test(S("abcdefghij"), 5, 2, 10, '2', S("abcde2222222222hij")); test(S("abcdefghij"), 5, 2, 20, '2', S("abcde22222222222222222222hij")); test(S("abcdefghij"), 5, 4, 0, '2', S("abcdej")); test(S("abcdefghij"), 5, 4, 5, '2', S("abcde22222j")); test(S("abcdefghij"), 5, 4, 10, '2', S("abcde2222222222j")); test(S("abcdefghij"), 5, 4, 20, '2', S("abcde22222222222222222222j")); test(S("abcdefghij"), 5, 5, 0, '2', S("abcde")); test(S("abcdefghij"), 5, 5, 5, '2', S("abcde22222")); test(S("abcdefghij"), 5, 5, 10, '2', S("abcde2222222222")); test(S("abcdefghij"), 5, 5, 20, '2', S("abcde22222222222222222222")); test(S("abcdefghij"), 5, 6, 0, '2', S("abcde")); test(S("abcdefghij"), 5, 6, 5, '2', S("abcde22222")); test(S("abcdefghij"), 5, 6, 10, '2', S("abcde2222222222")); test(S("abcdefghij"), 5, 6, 20, '2', S("abcde22222222222222222222")); test(S("abcdefghij"), 9, 0, 0, '2', S("abcdefghij")); test(S("abcdefghij"), 9, 0, 5, '2', S("abcdefghi22222j")); test(S("abcdefghij"), 9, 0, 10, '2', S("abcdefghi2222222222j")); test(S("abcdefghij"), 9, 0, 20, '2', S("abcdefghi22222222222222222222j")); test(S("abcdefghij"), 9, 1, 0, '2', S("abcdefghi")); test(S("abcdefghij"), 9, 1, 5, '2', S("abcdefghi22222")); test(S("abcdefghij"), 9, 1, 10, '2', S("abcdefghi2222222222")); test(S("abcdefghij"), 9, 1, 20, '2', S("abcdefghi22222222222222222222")); test(S("abcdefghij"), 9, 2, 0, '2', S("abcdefghi")); test(S("abcdefghij"), 9, 2, 5, '2', S("abcdefghi22222")); test(S("abcdefghij"), 9, 2, 10, '2', S("abcdefghi2222222222")); test(S("abcdefghij"), 9, 2, 20, '2', S("abcdefghi22222222222222222222")); test(S("abcdefghij"), 10, 0, 0, '2', S("abcdefghij")); test(S("abcdefghij"), 10, 0, 5, '2', S("abcdefghij22222")); test(S("abcdefghij"), 10, 0, 10, '2', S("abcdefghij2222222222")); test(S("abcdefghij"), 10, 0, 20, '2', S("abcdefghij22222222222222222222")); test(S("abcdefghij"), 10, 1, 0, '2', S("abcdefghij")); test(S("abcdefghij"), 10, 1, 5, '2', S("abcdefghij22222")); test(S("abcdefghij"), 10, 1, 10, '2', S("abcdefghij2222222222")); test(S("abcdefghij"), 10, 1, 20, '2', S("abcdefghij22222222222222222222")); test(S("abcdefghij"), 11, 0, 0, '2', S("can't happen")); test(S("abcdefghij"), 11, 0, 5, '2', S("can't happen")); test(S("abcdefghij"), 11, 0, 10, '2', S("can't happen")); test(S("abcdefghij"), 11, 0, 20, '2', S("can't happen")); } void test2() { test(S("abcdefghijklmnopqrst"), 0, 0, 0, '2', S("abcdefghijklmnopqrst")); test(S("abcdefghijklmnopqrst"), 0, 0, 5, '2', S("22222abcdefghijklmnopqrst")); test(S("abcdefghijklmnopqrst"), 0, 0, 10, '2', S("2222222222abcdefghijklmnopqrst")); test(S("abcdefghijklmnopqrst"), 0, 0, 20, '2', S("22222222222222222222abcdefghijklmnopqrst")); test(S("abcdefghijklmnopqrst"), 0, 1, 0, '2', S("bcdefghijklmnopqrst")); test(S("abcdefghijklmnopqrst"), 0, 1, 5, '2', S("22222bcdefghijklmnopqrst")); test(S("abcdefghijklmnopqrst"), 0, 1, 10, '2', S("2222222222bcdefghijklmnopqrst")); test(S("abcdefghijklmnopqrst"), 0, 1, 20, '2', S("22222222222222222222bcdefghijklmnopqrst")); test(S("abcdefghijklmnopqrst"), 0, 10, 0, '2', S("klmnopqrst")); test(S("abcdefghijklmnopqrst"), 0, 10, 5, '2', S("22222klmnopqrst")); test(S("abcdefghijklmnopqrst"), 0, 10, 10, '2', S("2222222222klmnopqrst")); test(S("abcdefghijklmnopqrst"), 0, 10, 20, '2', S("22222222222222222222klmnopqrst")); test(S("abcdefghijklmnopqrst"), 0, 19, 0, '2', S("t")); test(S("abcdefghijklmnopqrst"), 0, 19, 5, '2', S("22222t")); test(S("abcdefghijklmnopqrst"), 0, 19, 10, '2', S("2222222222t")); test(S("abcdefghijklmnopqrst"), 0, 19, 20, '2', S("22222222222222222222t")); test(S("abcdefghijklmnopqrst"), 0, 20, 0, '2', S("")); test(S("abcdefghijklmnopqrst"), 0, 20, 5, '2', S("22222")); test(S("abcdefghijklmnopqrst"), 0, 20, 10, '2', S("2222222222")); test(S("abcdefghijklmnopqrst"), 0, 20, 20, '2', S("22222222222222222222")); test(S("abcdefghijklmnopqrst"), 0, 21, 0, '2', S("")); test(S("abcdefghijklmnopqrst"), 0, 21, 5, '2', S("22222")); test(S("abcdefghijklmnopqrst"), 0, 21, 10, '2', S("2222222222")); test(S("abcdefghijklmnopqrst"), 0, 21, 20, '2', S("22222222222222222222")); test(S("abcdefghijklmnopqrst"), 1, 0, 0, '2', S("abcdefghijklmnopqrst")); test(S("abcdefghijklmnopqrst"), 1, 0, 5, '2', S("a22222bcdefghijklmnopqrst")); test(S("abcdefghijklmnopqrst"), 1, 0, 10, '2', S("a2222222222bcdefghijklmnopqrst")); test(S("abcdefghijklmnopqrst"), 1, 0, 20, '2', S("a22222222222222222222bcdefghijklmnopqrst")); test(S("abcdefghijklmnopqrst"), 1, 1, 0, '2', S("acdefghijklmnopqrst")); test(S("abcdefghijklmnopqrst"), 1, 1, 5, '2', S("a22222cdefghijklmnopqrst")); test(S("abcdefghijklmnopqrst"), 1, 1, 10, '2', S("a2222222222cdefghijklmnopqrst")); test(S("abcdefghijklmnopqrst"), 1, 1, 20, '2', S("a22222222222222222222cdefghijklmnopqrst")); test(S("abcdefghijklmnopqrst"), 1, 9, 0, '2', S("aklmnopqrst")); test(S("abcdefghijklmnopqrst"), 1, 9, 5, '2', S("a22222klmnopqrst")); test(S("abcdefghijklmnopqrst"), 1, 9, 10, '2', S("a2222222222klmnopqrst")); test(S("abcdefghijklmnopqrst"), 1, 9, 20, '2', S("a22222222222222222222klmnopqrst")); test(S("abcdefghijklmnopqrst"), 1, 18, 0, '2', S("at")); test(S("abcdefghijklmnopqrst"), 1, 18, 5, '2', S("a22222t")); test(S("abcdefghijklmnopqrst"), 1, 18, 10, '2', S("a2222222222t")); test(S("abcdefghijklmnopqrst"), 1, 18, 20, '2', S("a22222222222222222222t")); test(S("abcdefghijklmnopqrst"), 1, 19, 0, '2', S("a")); test(S("abcdefghijklmnopqrst"), 1, 19, 5, '2', S("a22222")); test(S("abcdefghijklmnopqrst"), 1, 19, 10, '2', S("a2222222222")); test(S("abcdefghijklmnopqrst"), 1, 19, 20, '2', S("a22222222222222222222")); test(S("abcdefghijklmnopqrst"), 1, 20, 0, '2', S("a")); test(S("abcdefghijklmnopqrst"), 1, 20, 5, '2', S("a22222")); test(S("abcdefghijklmnopqrst"), 1, 20, 10, '2', S("a2222222222")); test(S("abcdefghijklmnopqrst"), 1, 20, 20, '2', S("a22222222222222222222")); test(S("abcdefghijklmnopqrst"), 10, 0, 0, '2', S("abcdefghijklmnopqrst")); test(S("abcdefghijklmnopqrst"), 10, 0, 5, '2', S("abcdefghij22222klmnopqrst")); test(S("abcdefghijklmnopqrst"), 10, 0, 10, '2', S("abcdefghij2222222222klmnopqrst")); test(S("abcdefghijklmnopqrst"), 10, 0, 20, '2', S("abcdefghij22222222222222222222klmnopqrst")); test(S("abcdefghijklmnopqrst"), 10, 1, 0, '2', S("abcdefghijlmnopqrst")); test(S("abcdefghijklmnopqrst"), 10, 1, 5, '2', S("abcdefghij22222lmnopqrst")); test(S("abcdefghijklmnopqrst"), 10, 1, 10, '2', S("abcdefghij2222222222lmnopqrst")); test(S("abcdefghijklmnopqrst"), 10, 1, 20, '2', S("abcdefghij22222222222222222222lmnopqrst")); test(S("abcdefghijklmnopqrst"), 10, 5, 0, '2', S("abcdefghijpqrst")); test(S("abcdefghijklmnopqrst"), 10, 5, 5, '2', S("abcdefghij22222pqrst")); test(S("abcdefghijklmnopqrst"), 10, 5, 10, '2', S("abcdefghij2222222222pqrst")); test(S("abcdefghijklmnopqrst"), 10, 5, 20, '2', S("abcdefghij22222222222222222222pqrst")); test(S("abcdefghijklmnopqrst"), 10, 9, 0, '2', S("abcdefghijt")); test(S("abcdefghijklmnopqrst"), 10, 9, 5, '2', S("abcdefghij22222t")); test(S("abcdefghijklmnopqrst"), 10, 9, 10, '2', S("abcdefghij2222222222t")); test(S("abcdefghijklmnopqrst"), 10, 9, 20, '2', S("abcdefghij22222222222222222222t")); test(S("abcdefghijklmnopqrst"), 10, 10, 0, '2', S("abcdefghij")); test(S("abcdefghijklmnopqrst"), 10, 10, 5, '2', S("abcdefghij22222")); test(S("abcdefghijklmnopqrst"), 10, 10, 10, '2', S("abcdefghij2222222222")); test(S("abcdefghijklmnopqrst"), 10, 10, 20, '2', S("abcdefghij22222222222222222222")); test(S("abcdefghijklmnopqrst"), 10, 11, 0, '2', S("abcdefghij")); test(S("abcdefghijklmnopqrst"), 10, 11, 5, '2', S("abcdefghij22222")); test(S("abcdefghijklmnopqrst"), 10, 11, 10, '2', S("abcdefghij2222222222")); test(S("abcdefghijklmnopqrst"), 10, 11, 20, '2', S("abcdefghij22222222222222222222")); test(S("abcdefghijklmnopqrst"), 19, 0, 0, '2', S("abcdefghijklmnopqrst")); test(S("abcdefghijklmnopqrst"), 19, 0, 5, '2', S("abcdefghijklmnopqrs22222t")); test(S("abcdefghijklmnopqrst"), 19, 0, 10, '2', S("abcdefghijklmnopqrs2222222222t")); test(S("abcdefghijklmnopqrst"), 19, 0, 20, '2', S("abcdefghijklmnopqrs22222222222222222222t")); test(S("abcdefghijklmnopqrst"), 19, 1, 0, '2', S("abcdefghijklmnopqrs")); test(S("abcdefghijklmnopqrst"), 19, 1, 5, '2', S("abcdefghijklmnopqrs22222")); test(S("abcdefghijklmnopqrst"), 19, 1, 10, '2', S("abcdefghijklmnopqrs2222222222")); test(S("abcdefghijklmnopqrst"), 19, 1, 20, '2', S("abcdefghijklmnopqrs22222222222222222222")); test(S("abcdefghijklmnopqrst"), 19, 2, 0, '2', S("abcdefghijklmnopqrs")); test(S("abcdefghijklmnopqrst"), 19, 2, 5, '2', S("abcdefghijklmnopqrs22222")); test(S("abcdefghijklmnopqrst"), 19, 2, 10, '2', S("abcdefghijklmnopqrs2222222222")); test(S("abcdefghijklmnopqrst"), 19, 2, 20, '2', S("abcdefghijklmnopqrs22222222222222222222")); test(S("abcdefghijklmnopqrst"), 20, 0, 0, '2', S("abcdefghijklmnopqrst")); test(S("abcdefghijklmnopqrst"), 20, 0, 5, '2', S("abcdefghijklmnopqrst22222")); test(S("abcdefghijklmnopqrst"), 20, 0, 10, '2', S("abcdefghijklmnopqrst2222222222")); test(S("abcdefghijklmnopqrst"), 20, 0, 20, '2', S("abcdefghijklmnopqrst22222222222222222222")); test(S("abcdefghijklmnopqrst"), 20, 1, 0, '2', S("abcdefghijklmnopqrst")); test(S("abcdefghijklmnopqrst"), 20, 1, 5, '2', S("abcdefghijklmnopqrst22222")); test(S("abcdefghijklmnopqrst"), 20, 1, 10, '2', S("abcdefghijklmnopqrst2222222222")); test(S("abcdefghijklmnopqrst"), 20, 1, 20, '2', S("abcdefghijklmnopqrst22222222222222222222")); test(S("abcdefghijklmnopqrst"), 21, 0, 0, '2', S("can't happen")); test(S("abcdefghijklmnopqrst"), 21, 0, 5, '2', S("can't happen")); test(S("abcdefghijklmnopqrst"), 21, 0, 10, '2', S("can't happen")); test(S("abcdefghijklmnopqrst"), 21, 0, 20, '2', S("can't happen")); } int main() { test0(); test1(); test2(); }
mit
eugeniashurko/ReGraph
docs/genindex.html
35172
<!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/html; charset=utf-8" /> <title>Index &#8212; ReGraph 1.0 documentation</title> <link rel="stylesheet" href="_static/alabaster.css" type="text/css" /> <link rel="stylesheet" href="_static/pygments.css" type="text/css" /> <script type="text/javascript"> var DOCUMENTATION_OPTIONS = { URL_ROOT: './', VERSION: '1.0', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', HAS_SOURCE: true, SOURCELINK_SUFFIX: '.txt' }; </script> <script type="text/javascript" src="_static/jquery.js"></script> <script type="text/javascript" src="_static/underscore.js"></script> <script type="text/javascript" src="_static/doctools.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script> <link rel="index" title="Index" href="#" /> <link rel="search" title="Search" href="search.html" /> <link rel="stylesheet" href="_static/custom.css" type="text/css" /> <meta name="viewport" content="width=device-width, initial-scale=0.9, maximum-scale=0.9" /> </head> <body> <div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body" role="main"> <h1 id="index">Index</h1> <div class="genindex-jumpbox"> <a href="#A"><strong>A</strong></a> | <a href="#C"><strong>C</strong></a> | <a href="#D"><strong>D</strong></a> | <a href="#E"><strong>E</strong></a> | <a href="#F"><strong>F</strong></a> | <a href="#G"><strong>G</strong></a> | <a href="#H"><strong>H</strong></a> | <a href="#I"><strong>I</strong></a> | <a href="#L"><strong>L</strong></a> | <a href="#M"><strong>M</strong></a> | <a href="#N"><strong>N</strong></a> | <a href="#P"><strong>P</strong></a> | <a href="#R"><strong>R</strong></a> | <a href="#S"><strong>S</strong></a> | <a href="#T"><strong>T</strong></a> | <a href="#U"><strong>U</strong></a> </div> <h2 id="A">A</h2> <table style="width: 100%" class="indextable genindextable"><tr> <td style="width: 33%; vertical-align: top;"><ul> <li><a href="attribute_sets.html#regraph.attribute_sets.FiniteSet.add">add() (regraph.attribute_sets.FiniteSet method)</a> </li> <li><a href="hierarchy.html#regraph.hierarchy.AttributeContainter.add_attrs">add_attrs() (regraph.hierarchy.AttributeContainter method)</a> <ul> <li><a href="hierarchy.html#regraph.hierarchy.Hierarchy.add_attrs">(regraph.hierarchy.Hierarchy method)</a> </li> </ul></li> <li><a href="primitives.html#regraph.primitives.add_edge">add_edge() (in module regraph.primitives)</a> <ul> <li><a href="rules.html#regraph.rules.Rule.add_edge">(regraph.rules.Rule method)</a> </li> </ul></li> <li><a href="primitives.html#regraph.primitives.add_edge_attrs">add_edge_attrs() (in module regraph.primitives)</a> <ul> <li><a href="rules.html#regraph.rules.Rule.add_edge_attrs">(regraph.rules.Rule method)</a> </li> </ul></li> <li><a href="rules.html#regraph.rules.Rule.add_edge_rhs">add_edge_rhs() (regraph.rules.Rule method)</a> </li> <li><a href="primitives.html#regraph.primitives.add_edges_from">add_edges_from() (in module regraph.primitives)</a> </li> <li><a href="hierarchy.html#regraph.hierarchy.Hierarchy.add_graph">add_graph() (regraph.hierarchy.Hierarchy method)</a> </li> <li><a href="primitives.html#regraph.primitives.add_node">add_node() (in module regraph.primitives)</a> <ul> <li><a href="rules.html#regraph.rules.Rule.add_node">(regraph.rules.Rule method)</a> </li> </ul></li> <li><a href="primitives.html#regraph.primitives.add_node_attrs">add_node_attrs() (in module regraph.primitives)</a> <ul> <li><a href="rules.html#regraph.rules.Rule.add_node_attrs">(regraph.rules.Rule method)</a> </li> </ul></li> <li><a href="rules.html#regraph.rules.Rule.add_node_attrs_rhs">add_node_attrs_rhs() (regraph.rules.Rule method)</a> </li> <li><a href="primitives.html#regraph.primitives.add_node_new_id">add_node_new_id() (in module regraph.primitives)</a> </li> <li><a href="hierarchy.html#regraph.hierarchy.Hierarchy.add_node_type">add_node_type() (regraph.hierarchy.Hierarchy method)</a> </li> <li><a href="primitives.html#regraph.primitives.add_nodes_from">add_nodes_from() (in module regraph.primitives)</a> </li> </ul></td> <td style="width: 33%; vertical-align: top;"><ul> <li><a href="hierarchy.html#regraph.hierarchy.Hierarchy.add_relation">add_relation() (regraph.hierarchy.Hierarchy method)</a> </li> <li><a href="hierarchy.html#regraph.hierarchy.Hierarchy.add_rule">add_rule() (regraph.hierarchy.Hierarchy method)</a> </li> <li><a href="hierarchy.html#regraph.hierarchy.Hierarchy.add_rule_typing">add_rule_typing() (regraph.hierarchy.Hierarchy method)</a> </li> <li><a href="hierarchy.html#regraph.hierarchy.Hierarchy.add_typing">add_typing() (regraph.hierarchy.Hierarchy method)</a> </li> <li><a href="rules.html#regraph.rules.Rule.added_edge_attrs">added_edge_attrs() (regraph.rules.Rule method)</a> </li> <li><a href="rules.html#regraph.rules.Rule.added_edges">added_edges() (regraph.rules.Rule method)</a> </li> <li><a href="rules.html#regraph.rules.Rule.added_node_attrs">added_node_attrs() (regraph.rules.Rule method)</a> </li> <li><a href="rules.html#regraph.rules.Rule.added_nodes">added_nodes() (regraph.rules.Rule method)</a> </li> <li><a href="hierarchy.html#regraph.hierarchy.Hierarchy.adjacent_relations">adjacent_relations() (regraph.hierarchy.Hierarchy method)</a> </li> <li><a href="hierarchy.html#regraph.hierarchy.RuleTyping.all_total">all_total() (regraph.hierarchy.RuleTyping method)</a> </li> <li><a href="primitives.html#regraph.primitives.append_to_node_names">append_to_node_names() (in module regraph.primitives)</a> </li> <li><a href="hierarchy.html#regraph.hierarchy.Hierarchy.apply_rule">apply_rule() (regraph.hierarchy.Hierarchy method)</a> </li> <li><a href="rules.html#regraph.rules.Rule.apply_to">apply_to() (regraph.rules.Rule method)</a> </li> <li><a href="hierarchy.html#regraph.hierarchy.AttributeContainter">AttributeContainter (class in regraph.hierarchy)</a> </li> <li><a href="attribute_sets.html#regraph.attribute_sets.AttributeSet">AttributeSet (class in regraph.attribute_sets)</a> </li> <li><a href="exceptions.html#regraph.exceptions.AttributeSetError">AttributeSetError</a> </li> <li><a href="hierarchy.html#regraph.hierarchy.AttributeContainter.attrs_from_json">attrs_from_json() (regraph.hierarchy.AttributeContainter static method)</a> </li> <li><a href="hierarchy.html#regraph.hierarchy.AttributeContainter.attrs_to_json">attrs_to_json() (regraph.hierarchy.AttributeContainter method)</a> </li> </ul></td> </tr></table> <h2 id="C">C</h2> <table style="width: 100%" class="indextable genindextable"><tr> <td style="width: 33%; vertical-align: top;"><ul> <li><a href="hierarchy.html#regraph.hierarchy.Hierarchy.child_rule_from_nodes">child_rule_from_nodes() (regraph.hierarchy.Hierarchy method)</a> </li> <li><a href="primitives.html#regraph.primitives.clone_node">clone_node() (in module regraph.primitives)</a> <ul> <li><a href="rules.html#regraph.rules.Rule.clone_node">(regraph.rules.Rule method)</a> </li> </ul></li> <li><a href="rules.html#regraph.rules.Rule.clone_rhs_node">clone_rhs_node() (regraph.rules.Rule method)</a> </li> </ul></td> <td style="width: 33%; vertical-align: top;"><ul> <li><a href="rules.html#regraph.rules.Rule.cloned_nodes">cloned_nodes() (regraph.rules.Rule method)</a> </li> <li><a href="hierarchy.html#regraph.hierarchy.Hierarchy.compose_path_typing">compose_path_typing() (regraph.hierarchy.Hierarchy method)</a> </li> <li><a href="attribute_sets.html#regraph.attribute_sets.IntegerSet.contains">contains() (regraph.attribute_sets.IntegerSet method)</a> </li> <li><a href="primitives.html#regraph.primitives.copy_node">copy_node() (in module regraph.primitives)</a> </li> </ul></td> </tr></table> <h2 id="D">D</h2> <table style="width: 100%" class="indextable genindextable"><tr> <td style="width: 33%; vertical-align: top;"><ul> <li><a href="hierarchy.html#regraph.hierarchy.Hierarchy.descendents">descendents() (regraph.hierarchy.Hierarchy method)</a> </li> <li><a href="attribute_sets.html#regraph.attribute_sets.AttributeSet.difference">difference() (regraph.attribute_sets.AttributeSet method)</a> <ul> <li><a href="attribute_sets.html#regraph.attribute_sets.EmptySet.difference">(regraph.attribute_sets.EmptySet method)</a> </li> <li><a href="attribute_sets.html#regraph.attribute_sets.FiniteSet.difference">(regraph.attribute_sets.FiniteSet method)</a> </li> <li><a href="attribute_sets.html#regraph.attribute_sets.IntegerSet.difference">(regraph.attribute_sets.IntegerSet method)</a> </li> <li><a href="attribute_sets.html#regraph.attribute_sets.RegexSet.difference">(regraph.attribute_sets.RegexSet method)</a> </li> <li><a href="attribute_sets.html#regraph.attribute_sets.UniversalSet.difference">(regraph.attribute_sets.UniversalSet method)</a> </li> </ul></li> </ul></td> </tr></table> <h2 id="E">E</h2> <table style="width: 100%" class="indextable genindextable"><tr> <td style="width: 33%; vertical-align: top;"><ul> <li><a href="attribute_sets.html#regraph.attribute_sets.IntegerSet.empty">empty() (regraph.attribute_sets.IntegerSet class method)</a> <ul> <li><a href="attribute_sets.html#regraph.attribute_sets.RegexSet.empty">(regraph.attribute_sets.RegexSet class method)</a> </li> </ul></li> <li><a href="attribute_sets.html#regraph.attribute_sets.EmptySet">EmptySet (class in regraph.attribute_sets)</a> </li> </ul></td> <td style="width: 33%; vertical-align: top;"><ul> <li><a href="primitives.html#regraph.primitives.equal">equal() (in module regraph.primitives)</a> </li> <li><a href="primitives.html#regraph.primitives.exists_edge">exists_edge() (in module regraph.primitives)</a> </li> <li><a href="hierarchy.html#regraph.hierarchy.Hierarchy.export">export() (regraph.hierarchy.Hierarchy method)</a> </li> <li><a href="primitives.html#regraph.primitives.export_graph">export_graph() (in module regraph.primitives)</a> </li> </ul></td> </tr></table> <h2 id="F">F</h2> <table style="width: 100%" class="indextable genindextable"><tr> <td style="width: 33%; vertical-align: top;"><ul> <li><a href="primitives.html#regraph.primitives.filter_edges_by_attributes">filter_edges_by_attributes() (in module regraph.primitives)</a> </li> <li><a href="primitives.html#regraph.primitives.find_matching">find_matching() (in module regraph.primitives)</a> <ul> <li><a href="hierarchy.html#regraph.hierarchy.Hierarchy.find_matching">(regraph.hierarchy.Hierarchy method)</a> </li> </ul></li> <li><a href="primitives.html#regraph.primitives.find_matching_with_types">find_matching_with_types() (in module regraph.primitives)</a> </li> <li><a href="hierarchy.html#regraph.hierarchy.Hierarchy.find_rule_matching">find_rule_matching() (regraph.hierarchy.Hierarchy method)</a> </li> <li><a href="attribute_sets.html#regraph.attribute_sets.FiniteSet">FiniteSet (class in regraph.attribute_sets)</a> </li> </ul></td> <td style="width: 33%; vertical-align: top;"><ul> <li><a href="exceptions.html#regraph.exceptions.FormulaError">FormulaError</a> </li> <li><a href="attribute_sets.html#regraph.attribute_sets.IntegerSet.from_finite_set">from_finite_set() (regraph.attribute_sets.IntegerSet class method)</a> <ul> <li><a href="attribute_sets.html#regraph.attribute_sets.RegexSet.from_finite_set">(regraph.attribute_sets.RegexSet class method)</a> </li> </ul></li> <li><a href="attribute_sets.html#regraph.attribute_sets.AttributeSet.from_json">from_json() (regraph.attribute_sets.AttributeSet class method)</a> <ul> <li><a href="hierarchy.html#regraph.hierarchy.Hierarchy.from_json">(regraph.hierarchy.Hierarchy class method)</a> </li> <li><a href="rules.html#regraph.rules.Rule.from_json">(regraph.rules.Rule class method)</a> </li> </ul></li> <li><a href="rules.html#regraph.rules.Rule.from_transform">from_transform() (regraph.rules.Rule class method)</a> </li> </ul></td> </tr></table> <h2 id="G">G</h2> <table style="width: 100%" class="indextable genindextable"><tr> <td style="width: 33%; vertical-align: top;"><ul> <li><a href="hierarchy.html#regraph.hierarchy.Hierarchy.get_ancestors">get_ancestors() (regraph.hierarchy.Hierarchy method)</a> </li> <li><a href="primitives.html#regraph.primitives.get_edge">get_edge() (in module regraph.primitives)</a> </li> <li><a href="primitives.html#regraph.primitives.get_relabeled_graph">get_relabeled_graph() (in module regraph.primitives)</a> </li> <li><a href="hierarchy.html#regraph.hierarchy.Hierarchy.get_rule_typing">get_rule_typing() (regraph.hierarchy.Hierarchy method)</a> </li> <li><a href="hierarchy.html#regraph.hierarchy.Hierarchy.get_typing">get_typing() (regraph.hierarchy.Hierarchy method)</a> </li> <li><a href="hierarchy.html#regraph.hierarchy.Hierarchy.graph_dict_factory">graph_dict_factory (regraph.hierarchy.Hierarchy attribute)</a> </li> </ul></td> <td style="width: 33%; vertical-align: top;"><ul> <li><a href="primitives.html#regraph.primitives.graph_from_json">graph_from_json() (in module regraph.primitives)</a> </li> <li><a href="primitives.html#regraph.primitives.graph_to_json">graph_to_json() (in module regraph.primitives)</a> </li> <li><a href="exceptions.html#regraph.exceptions.GraphAttrsWarning">GraphAttrsWarning</a> </li> <li><a href="exceptions.html#regraph.exceptions.GraphError">GraphError</a> </li> <li><a href="hierarchy.html#regraph.hierarchy.GraphNode">GraphNode (class in regraph.hierarchy)</a> </li> <li><a href="hierarchy.html#regraph.hierarchy.GraphRelation">GraphRelation (class in regraph.hierarchy)</a> </li> </ul></td> </tr></table> <h2 id="H">H</h2> <table style="width: 100%" class="indextable genindextable"><tr> <td style="width: 33%; vertical-align: top;"><ul> <li><a href="hierarchy.html#regraph.hierarchy.Hierarchy">Hierarchy (class in regraph.hierarchy)</a> </li> </ul></td> <td style="width: 33%; vertical-align: top;"><ul> <li><a href="exceptions.html#regraph.exceptions.HierarchyError">HierarchyError</a> </li> </ul></td> </tr></table> <h2 id="I">I</h2> <table style="width: 100%" class="indextable genindextable"><tr> <td style="width: 33%; vertical-align: top;"><ul> <li><a href="attribute_sets.html#regraph.attribute_sets.IntegerSet">IntegerSet (class in regraph.attribute_sets)</a> </li> <li><a href="attribute_sets.html#regraph.attribute_sets.AttributeSet.intersect">intersect() (regraph.attribute_sets.AttributeSet method)</a> <ul> <li><a href="attribute_sets.html#regraph.attribute_sets.EmptySet.intersect">(regraph.attribute_sets.EmptySet method)</a> </li> </ul></li> <li><a href="attribute_sets.html#regraph.attribute_sets.FiniteSet.intersection">intersection() (regraph.attribute_sets.FiniteSet method)</a> <ul> <li><a href="attribute_sets.html#regraph.attribute_sets.IntegerSet.intersection">(regraph.attribute_sets.IntegerSet method)</a> </li> <li><a href="attribute_sets.html#regraph.attribute_sets.RegexSet.intersection">(regraph.attribute_sets.RegexSet method)</a> </li> <li><a href="attribute_sets.html#regraph.attribute_sets.UniversalSet.intersection">(regraph.attribute_sets.UniversalSet method)</a> </li> </ul></li> <li><a href="exceptions.html#regraph.exceptions.InvalidHomomorphism">InvalidHomomorphism</a> </li> <li><a href="attribute_sets.html#regraph.attribute_sets.EmptySet.is_empty">is_empty() (regraph.attribute_sets.EmptySet method)</a> <ul> <li><a href="attribute_sets.html#regraph.attribute_sets.FiniteSet.is_empty">(regraph.attribute_sets.FiniteSet method)</a> </li> <li><a href="attribute_sets.html#regraph.attribute_sets.IntegerSet.is_empty">(regraph.attribute_sets.IntegerSet method)</a> </li> <li><a href="attribute_sets.html#regraph.attribute_sets.RegexSet.is_empty">(regraph.attribute_sets.RegexSet method)</a> </li> <li><a href="attribute_sets.html#regraph.attribute_sets.UniversalSet.is_empty">(regraph.attribute_sets.UniversalSet method)</a> </li> </ul></li> </ul></td> <td style="width: 33%; vertical-align: top;"><ul> <li><a href="rules.html#regraph.rules.Rule.is_relaxing">is_relaxing() (regraph.rules.Rule method)</a> </li> <li><a href="rules.html#regraph.rules.Rule.is_restrictive">is_restrictive() (regraph.rules.Rule method)</a> </li> <li><a href="hierarchy.html#regraph.hierarchy.Typing.is_total">is_total() (regraph.hierarchy.Typing method)</a> </li> <li><a href="attribute_sets.html#regraph.attribute_sets.EmptySet.is_universal">is_universal() (regraph.attribute_sets.EmptySet method)</a> <ul> <li><a href="attribute_sets.html#regraph.attribute_sets.FiniteSet.is_universal">(regraph.attribute_sets.FiniteSet method)</a> </li> <li><a href="attribute_sets.html#regraph.attribute_sets.IntegerSet.is_universal">(regraph.attribute_sets.IntegerSet method)</a> </li> <li><a href="attribute_sets.html#regraph.attribute_sets.RegexSet.is_universal">(regraph.attribute_sets.RegexSet method)</a> </li> <li><a href="attribute_sets.html#regraph.attribute_sets.UniversalSet.is_universal">(regraph.attribute_sets.UniversalSet method)</a> </li> </ul></li> <li><a href="attribute_sets.html#regraph.attribute_sets.AttributeSet.issubset">issubset() (regraph.attribute_sets.AttributeSet method)</a> <ul> <li><a href="attribute_sets.html#regraph.attribute_sets.EmptySet.issubset">(regraph.attribute_sets.EmptySet method)</a> </li> <li><a href="attribute_sets.html#regraph.attribute_sets.FiniteSet.issubset">(regraph.attribute_sets.FiniteSet method)</a> </li> <li><a href="attribute_sets.html#regraph.attribute_sets.IntegerSet.issubset">(regraph.attribute_sets.IntegerSet method)</a> </li> <li><a href="attribute_sets.html#regraph.attribute_sets.RegexSet.issubset">(regraph.attribute_sets.RegexSet method)</a> </li> <li><a href="attribute_sets.html#regraph.attribute_sets.UniversalSet.issubset">(regraph.attribute_sets.UniversalSet method)</a> </li> </ul></li> </ul></td> </tr></table> <h2 id="L">L</h2> <table style="width: 100%" class="indextable genindextable"><tr> <td style="width: 33%; vertical-align: top;"><ul> <li><a href="hierarchy.html#regraph.hierarchy.GraphRelation.left_domain">left_domain() (regraph.hierarchy.GraphRelation method)</a> </li> </ul></td> <td style="width: 33%; vertical-align: top;"><ul> <li><a href="hierarchy.html#regraph.hierarchy.Hierarchy.load">load() (regraph.hierarchy.Hierarchy class method)</a> </li> <li><a href="primitives.html#regraph.primitives.load_graph">load_graph() (in module regraph.primitives)</a> </li> </ul></td> </tr></table> <h2 id="M">M</h2> <table style="width: 100%" class="indextable genindextable"><tr> <td style="width: 33%; vertical-align: top;"><ul> <li><a href="attribute_sets.html#regraph.attribute_sets.RegexSet.match">match() (regraph.attribute_sets.RegexSet method)</a> </li> <li><a href="hierarchy.html#regraph.hierarchy.Hierarchy.merge_by_attr">merge_by_attr() (regraph.hierarchy.Hierarchy method)</a> </li> <li><a href="hierarchy.html#regraph.hierarchy.Hierarchy.merge_by_id">merge_by_id() (regraph.hierarchy.Hierarchy method)</a> </li> <li><a href="rules.html#regraph.rules.Rule.merge_node_list">merge_node_list() (regraph.rules.Rule method)</a> </li> </ul></td> <td style="width: 33%; vertical-align: top;"><ul> <li><a href="primitives.html#regraph.primitives.merge_nodes">merge_nodes() (in module regraph.primitives)</a> <ul> <li><a href="rules.html#regraph.rules.Rule.merge_nodes">(regraph.rules.Rule method)</a> </li> </ul></li> <li><a href="rules.html#regraph.rules.Rule.merge_nodes_rhs">merge_nodes_rhs() (regraph.rules.Rule method)</a> </li> <li><a href="rules.html#regraph.rules.Rule.merged_nodes">merged_nodes() (regraph.rules.Rule method)</a> </li> </ul></td> </tr></table> <h2 id="N">N</h2> <table style="width: 100%" class="indextable genindextable"><tr> <td style="width: 33%; vertical-align: top;"><ul> <li><a href="hierarchy.html#regraph.hierarchy.Hierarchy.new_graph_from_nodes">new_graph_from_nodes() (regraph.hierarchy.Hierarchy method)</a> </li> </ul></td> <td style="width: 33%; vertical-align: top;"><ul> <li><a href="hierarchy.html#regraph.hierarchy.Hierarchy.node_type">node_type() (regraph.hierarchy.Hierarchy method)</a> </li> </ul></td> </tr></table> <h2 id="P">P</h2> <table style="width: 100%" class="indextable genindextable"><tr> <td style="width: 33%; vertical-align: top;"><ul> <li><a href="exceptions.html#regraph.exceptions.ParsingError">ParsingError</a> </li> </ul></td> <td style="width: 33%; vertical-align: top;"><ul> <li><a href="primitives.html#regraph.primitives.print_graph">print_graph() (in module regraph.primitives)</a> </li> </ul></td> </tr></table> <h2 id="R">R</h2> <table style="width: 100%" class="indextable genindextable"><tr> <td style="width: 33%; vertical-align: top;"><ul> <li><a href="attribute_sets.html#regraph.attribute_sets.RegexSet">RegexSet (class in regraph.attribute_sets)</a> </li> <li><a href="attribute_sets.html#module-regraph.attribute_sets">regraph.attribute_sets (module)</a> </li> <li><a href="exceptions.html#module-regraph.exceptions">regraph.exceptions (module)</a> </li> <li><a href="hierarchy.html#module-regraph.hierarchy">regraph.hierarchy (module)</a> </li> <li><a href="primitives.html#module-regraph.primitives">regraph.primitives (module)</a> </li> <li><a href="rules.html#module-regraph.rules">regraph.rules (module)</a> </li> <li><a href="exceptions.html#regraph.exceptions.ReGraphError">ReGraphError</a> </li> <li><a href="exceptions.html#regraph.exceptions.ReGraphException">ReGraphException</a> </li> <li><a href="exceptions.html#regraph.exceptions.ReGraphWarning">ReGraphWarning</a> </li> <li><a href="primitives.html#regraph.primitives.relabel_node">relabel_node() (in module regraph.primitives)</a> </li> <li><a href="primitives.html#regraph.primitives.relabel_nodes">relabel_nodes() (in module regraph.primitives)</a> </li> <li><a href="hierarchy.html#regraph.hierarchy.Relation">Relation (class in regraph.hierarchy)</a> </li> <li><a href="hierarchy.html#regraph.hierarchy.Hierarchy.relation_dict_factory">relation_dict_factory (regraph.hierarchy.Hierarchy attribute)</a> </li> <li><a href="hierarchy.html#regraph.hierarchy.Hierarchy.relation_to_span">relation_to_span() (regraph.hierarchy.Hierarchy method)</a> </li> <li><a href="hierarchy.html#regraph.hierarchy.Hierarchy.relations">relations() (regraph.hierarchy.Hierarchy method)</a> </li> <li><a href="hierarchy.html#regraph.hierarchy.AttributeContainter.remove_attrs">remove_attrs() (regraph.hierarchy.AttributeContainter method)</a> <ul> <li><a href="hierarchy.html#regraph.hierarchy.Hierarchy.remove_attrs">(regraph.hierarchy.Hierarchy method)</a> </li> </ul></li> <li><a href="primitives.html#regraph.primitives.remove_edge">remove_edge() (in module regraph.primitives)</a> <ul> <li><a href="rules.html#regraph.rules.Rule.remove_edge">(regraph.rules.Rule method)</a> </li> </ul></li> <li><a href="primitives.html#regraph.primitives.remove_edge_attrs">remove_edge_attrs() (in module regraph.primitives)</a> <ul> <li><a href="rules.html#regraph.rules.Rule.remove_edge_attrs">(regraph.rules.Rule method)</a> </li> </ul></li> <li><a href="rules.html#regraph.rules.Rule.remove_edge_p">remove_edge_p() (regraph.rules.Rule method)</a> </li> <li><a href="rules.html#regraph.rules.Rule.remove_edge_rhs">remove_edge_rhs() (regraph.rules.Rule method)</a> </li> <li><a href="hierarchy.html#regraph.hierarchy.Hierarchy.remove_graph">remove_graph() (regraph.hierarchy.Hierarchy method)</a> </li> <li><a href="primitives.html#regraph.primitives.remove_node">remove_node() (in module regraph.primitives)</a> <ul> <li><a href="hierarchy.html#regraph.hierarchy.Hierarchy.remove_node">(regraph.hierarchy.Hierarchy method)</a> </li> <li><a href="rules.html#regraph.rules.Rule.remove_node">(regraph.rules.Rule method)</a> </li> </ul></li> </ul></td> <td style="width: 33%; vertical-align: top;"><ul> <li><a href="primitives.html#regraph.primitives.remove_node_attrs">remove_node_attrs() (in module regraph.primitives)</a> <ul> <li><a href="rules.html#regraph.rules.Rule.remove_node_attrs">(regraph.rules.Rule method)</a> </li> </ul></li> <li><a href="rules.html#regraph.rules.Rule.remove_node_attrs_p">remove_node_attrs_p() (regraph.rules.Rule method)</a> </li> <li><a href="rules.html#regraph.rules.Rule.remove_node_attrs_rhs">remove_node_attrs_rhs() (regraph.rules.Rule method)</a> </li> <li><a href="rules.html#regraph.rules.Rule.remove_node_rhs">remove_node_rhs() (regraph.rules.Rule method)</a> </li> <li><a href="hierarchy.html#regraph.hierarchy.Hierarchy.remove_node_type">remove_node_type() (regraph.hierarchy.Hierarchy method)</a> </li> <li><a href="hierarchy.html#regraph.hierarchy.Hierarchy.remove_relation">remove_relation() (regraph.hierarchy.Hierarchy method)</a> </li> <li><a href="rules.html#regraph.rules.Rule.removed_edge_attrs">removed_edge_attrs() (regraph.rules.Rule method)</a> </li> <li><a href="rules.html#regraph.rules.Rule.removed_edges">removed_edges() (regraph.rules.Rule method)</a> </li> <li><a href="rules.html#regraph.rules.Rule.removed_node_attrs">removed_node_attrs() (regraph.rules.Rule method)</a> </li> <li><a href="rules.html#regraph.rules.Rule.removed_nodes">removed_nodes() (regraph.rules.Rule method)</a> </li> <li><a href="hierarchy.html#regraph.hierarchy.Hierarchy.rename_graph">rename_graph() (regraph.hierarchy.Hierarchy method)</a> </li> <li><a href="hierarchy.html#regraph.hierarchy.Hierarchy.rename_node">rename_node() (regraph.hierarchy.Hierarchy method)</a> </li> <li><a href="hierarchy.html#regraph.hierarchy.RuleTyping.rename_source">rename_source() (regraph.hierarchy.RuleTyping method)</a> <ul> <li><a href="hierarchy.html#regraph.hierarchy.Typing.rename_source">(regraph.hierarchy.Typing method)</a> </li> </ul></li> <li><a href="hierarchy.html#regraph.hierarchy.RuleTyping.rename_target">rename_target() (regraph.hierarchy.RuleTyping method)</a> <ul> <li><a href="hierarchy.html#regraph.hierarchy.Typing.rename_target">(regraph.hierarchy.Typing method)</a> </li> </ul></li> <li><a href="hierarchy.html#regraph.hierarchy.Hierarchy.rewrite">rewrite() (regraph.hierarchy.Hierarchy method)</a> </li> <li><a href="exceptions.html#regraph.exceptions.RewritingError">RewritingError</a> </li> <li><a href="hierarchy.html#regraph.hierarchy.GraphRelation.right_domain">right_domain() (regraph.hierarchy.GraphRelation method)</a> </li> <li><a href="rules.html#regraph.rules.Rule">Rule (class in regraph.rules)</a> </li> <li><a href="hierarchy.html#regraph.hierarchy.Hierarchy.rule_dict_factory">rule_dict_factory (regraph.hierarchy.Hierarchy attribute)</a> </li> <li><a href="hierarchy.html#regraph.hierarchy.Hierarchy.rule_lhs_typing_dict_factory">rule_lhs_typing_dict_factory (regraph.hierarchy.Hierarchy attribute)</a> </li> <li><a href="hierarchy.html#regraph.hierarchy.Hierarchy.rule_rhs_typing_dict_factory">rule_rhs_typing_dict_factory (regraph.hierarchy.Hierarchy attribute)</a> </li> <li><a href="exceptions.html#regraph.exceptions.RuleError">RuleError</a> </li> <li><a href="hierarchy.html#regraph.hierarchy.RuleNode">RuleNode (class in regraph.hierarchy)</a> </li> <li><a href="hierarchy.html#regraph.hierarchy.RuleRelation">RuleRelation (class in regraph.hierarchy)</a> </li> <li><a href="hierarchy.html#regraph.hierarchy.RuleTyping">RuleTyping (class in regraph.hierarchy)</a> </li> </ul></td> </tr></table> <h2 id="S">S</h2> <table style="width: 100%" class="indextable genindextable"><tr> <td style="width: 33%; vertical-align: top;"><ul> <li><a href="primitives.html#regraph.primitives.set_edge">set_edge() (in module regraph.primitives)</a> </li> </ul></td> <td style="width: 33%; vertical-align: top;"><ul> <li><a href="primitives.html#regraph.primitives.subtract">subtract() (in module regraph.primitives)</a> </li> </ul></td> </tr></table> <h2 id="T">T</h2> <table style="width: 100%" class="indextable genindextable"><tr> <td style="width: 33%; vertical-align: top;"><ul> <li><a href="rules.html#regraph.rules.Rule.to_commands">to_commands() (regraph.rules.Rule method)</a> </li> <li><a href="attribute_sets.html#regraph.attribute_sets.EmptySet.to_json">to_json() (regraph.attribute_sets.EmptySet method)</a> <ul> <li><a href="attribute_sets.html#regraph.attribute_sets.FiniteSet.to_json">(regraph.attribute_sets.FiniteSet method)</a> </li> <li><a href="attribute_sets.html#regraph.attribute_sets.IntegerSet.to_json">(regraph.attribute_sets.IntegerSet method)</a> </li> <li><a href="attribute_sets.html#regraph.attribute_sets.RegexSet.to_json">(regraph.attribute_sets.RegexSet method)</a> </li> <li><a href="attribute_sets.html#regraph.attribute_sets.UniversalSet.to_json">(regraph.attribute_sets.UniversalSet method)</a> </li> <li><a href="hierarchy.html#regraph.hierarchy.Hierarchy.to_json">(regraph.hierarchy.Hierarchy method)</a> </li> <li><a href="rules.html#regraph.rules.Rule.to_json">(regraph.rules.Rule method)</a> </li> </ul></li> </ul></td> <td style="width: 33%; vertical-align: top;"><ul> <li><a href="hierarchy.html#regraph.hierarchy.Hierarchy.to_nx_graph">to_nx_graph() (regraph.hierarchy.Hierarchy method)</a> </li> <li><a href="hierarchy.html#regraph.hierarchy.Hierarchy.to_total">to_total() (regraph.hierarchy.Hierarchy method)</a> </li> <li><a href="exceptions.html#regraph.exceptions.TotalityWarning">TotalityWarning</a> </li> <li><a href="hierarchy.html#regraph.hierarchy.Typing">Typing (class in regraph.hierarchy)</a> </li> <li><a href="hierarchy.html#regraph.hierarchy.Hierarchy.typing_dict_factory">typing_dict_factory (regraph.hierarchy.Hierarchy attribute)</a> </li> </ul></td> </tr></table> <h2 id="U">U</h2> <table style="width: 100%" class="indextable genindextable"><tr> <td style="width: 33%; vertical-align: top;"><ul> <li><a href="attribute_sets.html#regraph.attribute_sets.AttributeSet.union">union() (regraph.attribute_sets.AttributeSet method)</a> <ul> <li><a href="attribute_sets.html#regraph.attribute_sets.EmptySet.union">(regraph.attribute_sets.EmptySet method)</a> </li> <li><a href="attribute_sets.html#regraph.attribute_sets.FiniteSet.union">(regraph.attribute_sets.FiniteSet method)</a> </li> <li><a href="attribute_sets.html#regraph.attribute_sets.IntegerSet.union">(regraph.attribute_sets.IntegerSet method)</a> </li> <li><a href="attribute_sets.html#regraph.attribute_sets.RegexSet.union">(regraph.attribute_sets.RegexSet method)</a> </li> <li><a href="attribute_sets.html#regraph.attribute_sets.UniversalSet.union">(regraph.attribute_sets.UniversalSet method)</a> </li> </ul></li> <li><a href="hierarchy.html#regraph.hierarchy.Hierarchy.unique_graph_id">unique_graph_id() (regraph.hierarchy.Hierarchy method)</a> </li> <li><a href="primitives.html#regraph.primitives.unique_node_id">unique_node_id() (in module regraph.primitives)</a> </li> </ul></td> <td style="width: 33%; vertical-align: top;"><ul> <li><a href="attribute_sets.html#regraph.attribute_sets.IntegerSet.universal">universal() (regraph.attribute_sets.IntegerSet class method)</a> <ul> <li><a href="attribute_sets.html#regraph.attribute_sets.RegexSet.universal">(regraph.attribute_sets.RegexSet class method)</a> </li> </ul></li> <li><a href="attribute_sets.html#regraph.attribute_sets.UniversalSet">UniversalSet (class in regraph.attribute_sets)</a> </li> <li><a href="attribute_sets.html#regraph.attribute_sets.FiniteSet.update">update() (regraph.attribute_sets.FiniteSet method)</a> </li> <li><a href="hierarchy.html#regraph.hierarchy.AttributeContainter.update_attrs">update_attrs() (regraph.hierarchy.AttributeContainter method)</a> </li> <li><a href="primitives.html#regraph.primitives.update_edge_attrs">update_edge_attrs() (in module regraph.primitives)</a> <ul> <li><a href="rules.html#regraph.rules.Rule.update_edge_attrs">(regraph.rules.Rule method)</a> </li> </ul></li> <li><a href="primitives.html#regraph.primitives.update_node_attrs">update_node_attrs() (in module regraph.primitives)</a> <ul> <li><a href="rules.html#regraph.rules.Rule.update_node_attrs">(regraph.rules.Rule method)</a> </li> </ul></li> </ul></td> </tr></table> </div> </div> </div> <div class="sphinxsidebar" role="navigation" aria-label="main navigation"> <div class="sphinxsidebarwrapper"> <h1 class="logo"><a href="index.html">ReGraph</a></h1> <h3>Navigation</h3> <div class="relations"> <h3>Related Topics</h3> <ul> <li><a href="index.html">Documentation overview</a><ul> </ul></li> </ul> </div> <div id="searchbox" style="display: none" role="search"> <h3>Quick search</h3> <form class="search" action="search.html" method="get"> <div><input type="text" name="q" /></div> <div><input type="submit" value="Go" /></div> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> </div> <script type="text/javascript">$('#searchbox').show(0);</script> </div> </div> <div class="clearer"></div> </div> <div class="footer"> &copy;2017, Eugenia Oshurko, Yves-Stan Le Cornec. | Powered by <a href="http://sphinx-doc.org/">Sphinx 1.6.5</a> &amp; <a href="https://github.com/bitprophet/alabaster">Alabaster 0.7.10</a> </div> </body> </html>
mit
oscarvegar/yoplannerlp
content/themes/znews/css/skins/custom/custom.css
3391
/* Backgrounds ----------------------------------------------------------*/ .btn-primary, .btn-primary:hover, .flat-mega-menu .drop-down.full-width ul li a.btn, .filter-header input[type="submit"], .ui-widget-header, .ui-state-default:hover, .ui-widget-content .ui-state-default:hover, .ui-widget-header .ui-state-default:hover, .flat-mega-menu .login-form input[type=submit], .flat-mega-menu .search-bar ul input[type=submit], .skin_base, .promotion-box-info .btn, .list-styles li i, .info-gallery .price b, .widget .input-group-addon.btn-search input, .header-v2, .info-head, .nav-tabs li.active a, .nav-tabs li.active a:hover, .nav-tabs li a:hover, .sort-by-container .style-view li:hover, .sort-by-container .style-view li.active, .selector span.custom-select:before, .slider-selection, .filter-widget input[type="submit"], .tabs-detailed .services-lines li:hover, .pagination > .active > a, .pagination .active, .tooltip-inner, .owl-theme .owl-controls .owl-buttons div, #theme-options .layout-style li.active, .thumbs li:hover, p.lead .line, .info-testimonial, .filter-header, .filter-header input[type="button"]{ background: #000 !important; background-color: #000 !important; } .opacy_bg_03, .item-team-01 .info-team, .header-detailed{ background: #000; background: rgba(0, 0, 0, 0.6); } /* Colors ----------------------------------------------------------*/ .item-service-line i, .titles h2 span, .info-boxed h3 span, .price span, .title-footer h2 span, .flat-mega-menu > ul > .title > a > span, .flat-mega-menu > ul > .title i, .icon-big-nav i, .ui-datepicker th, .head-feature, .flat-mega-menu > ul > li:hover > a, .footer-v1 ul li i, .footer-v2 ul li i, .footer-v3 ul li i, .footer-v4 ul li i, .flat-mega-menu > ul > li:hover > a, .flat-mega-menu .login-form:hover, .flat-mega-menu .search-bar:hover, .item-team h4 span, .item-team-01 .social-team li a:hover, .large-number, .info-gallery h3 span, .post-format-icon > i, .post-item .post-title a:hover, .post-meta a:hover, .post-quote-author a, .single-blog h4 i, .single-blog h4 a, .footer-down ul li a:hover, .nav-tabs li i, .container-by-widget-filter h4, .title-results a, blockquote > a, .tweet_time a, .tweet_text a, .acc-trigger a:hover, .acc-trigger.active a, .acc-trigger.active a:hover, .crumbs li a, .page-error h1 i, .sitemap li a:hover, .pagination > li > a, .pagination > li > span, address i, address a{ color: #000 !important; } /* Borders ----------------------------------------------------------*/ .pagination > .active > a, .pagination > .active:hover > a, .filter-header, .flat-mega-menu h2 span, .ui-datepicker, .crumbs ul, .portfolioFilter .current, .portfolioFilter a:hover, .post-format-icon > i, .section-title-03 h1, .title-widget{ border-color: #000 !important; } .crumbs:before{ border-bottom: 20px solid #000; } .tooltip.top .tooltip-arrow { border-top-color: #000; } .flat-mega-menu .drop-down, .flat-mega-menu .social-bar ul { border-bottom-color: #000; } .nav-tabs li.active:after { border: 16px solid #000; border-left-color: transparent; border-right-color: transparent; border-bottom-color: transparent; content: ""; left: 50%; margin-left: -16px; position: absolute; z-index: 101; } .title-widget:after { border-top: 15px solid #000; }
mit
pharring/ApplicationInsights-dotnet
LOGGING/src/NLogTarget/AssemblyInfo.cs
2225
// ----------------------------------------------------------------------- // <copyright file="AssemblyInfo.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. // All rights reserved. 2013 // </copyright> // ----------------------------------------------------------------------- using System; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] [assembly: CLSCompliant(true)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("44abc834-bd19-449f-ad64-f8c83ca078ed")] [assembly: InternalsVisibleTo("Microsoft.ApplicationInsights.NLogTarget.Tests, PublicKey=" + AssemblyInfo.PublicKey)] internal static class AssemblyInfo { #if PUBLIC_RELEASE // Public key; assemblies are delay signed. public const string PublicKey = "0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9"; #else // Internal key; assemblies are public signed. public const string PublicKey = "0024000004800000940000000602000000240000525341310004000001000100319b35b21a993df850846602dae9e86d8fbb0528a0ad488ecd6414db798996534381825f94f90d8b16b72a51c4e7e07cf66ff3293c1046c045fafc354cfcc15fc177c748111e4a8c5a34d3940e7f3789dd58a928add6160d6f9cc219680253dcea88a034e7d472de51d4989c7783e19343839273e0e63a43b99ab338149dd59f"; #endif public const string MoqPublicKey = "0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7"; }
mit
LuaDist/lzmq
src/lzutils.h
2730
#ifndef _LZUTILS_H_ #define _LZUTILS_H_ #include "lua.h" #include "lauxlib.h" #if LUA_VERSION_NUM >= 502 # define luazmq_rawgetp lua_rawgetp # define luazmq_rawsetp lua_rawsetp # define luazmq_setfuncs luaL_setfuncs # define luazmq_absindex lua_absindex #ifndef lua_objlen # define lua_objlen lua_rawlen #endif int luazmq_typerror (lua_State *L, int narg, const char *tname); #else # define luazmq_absindex(L, i) (((i)>0)?(i):((i)<=LUA_REGISTRYINDEX?(i):(lua_gettop(L)+(i)+1))) # define lua_rawlen lua_objlen # define luazmq_typerror luaL_typerror void luazmq_rawgetp (lua_State *L, int index, const void *p); void luazmq_rawsetp (lua_State *L, int index, const void *p); void luazmq_setfuncs (lua_State *L, const luaL_Reg *l, int nup); #endif int luazmq_newmetatablep (lua_State *L, const void *p); void luazmq_getmetatablep (lua_State *L, const void *p); int luazmq_isudatap (lua_State *L, int ud, const void *p); void *luazmq_toudatap (lua_State *L, int ud, const void *p); void *luazmq_checkudatap (lua_State *L, int ud, const void *p); int luazmq_createmeta (lua_State *L, const char *name, const luaL_Reg *methods, int nup); void luazmq_setmeta (lua_State *L, const char *name); void *luazmq_newudata_ (lua_State *L, size_t size, const char *name); #define luazmq_newudata(L, TTYPE, TNAME) (TTYPE *)luazmq_newudata_(L, sizeof(TTYPE), TNAME) #define LUAZMQ_STATIC_ASSERT(A) {(int(*)[(A)?1:0])0;} typedef struct { const char *name; int value; }luazmq_int_const; #define DEFINE_ZMQ_CONST(NAME) {#NAME, ZMQ_##NAME} #define DEFINE_INT_CONST(NAME) {#NAME, NAME} #ifdef LUAZMQ_USE_TEMP_BUFFERS # ifndef LUAZMQ_TEMP_BUFFER_SIZE # define LUAZMQ_TEMP_BUFFER_SIZE 128 # endif # define LUAZMQ_ALLOC_TEMP(BUF, SIZE) (sizeof(BUF) >= SIZE)?(BUF):malloc(SIZE) # define LUAZMQ_FREE_TEMP(BUF, PTR) do{if((PTR) != (BUF))free((void*)PTR);}while(0) # define LUAZMQ_DEFINE_TEMP_BUFFER(NAME) char NAME[LUAZMQ_TEMP_BUFFER_SIZE] #else # define LUAZMQ_ALLOC_TEMP(BUF, SIZE) malloc(SIZE) # define LUAZMQ_FREE_TEMP(BUF, PTR) free((void*)PTR) // MSVC need this to compile easy # define LUAZMQ_DEFINE_TEMP_BUFFER(NAME) static const void *const NAME = NULL #endif void luazmq_register_consts(lua_State *L, const luazmq_int_const *c); void luazmq_register_consts_invers(lua_State *L, const luazmq_int_const *c); int luazmq_pcall_method(lua_State *L, const char *name, int nargs, int nresults, int errfunc); int luazmq_call_method(lua_State *L, const char *name, int nargs, int nresults); int luazmq_new_weak_table(lua_State*L, const char *mode); void luazmq_stack_dump(lua_State *L); #endif
mit
aewing/mason
scripts/build.sh
201
babel packages/core/src/ -d packages/core/lib/ & babel packages/plugin-knex/src/ -d packages/plugin-knex/lib/ & babel packages/plugin-scaffold/src/ -d packages/plugin-scaffold/lib/ & wait echo "Done"
mit
rafaelaznar/sisane-client
public_html/js/zonaimagen/removepop.html
4272
<!-- Copyright (c) 2015 by Rafael Angel Aznar Aparici (rafaaznar at gmail dot com) sisane: The stunning micro-library that helps you to develop easily AJAX web applications by using Angular.js 1.x & sisane-server sisane is distributed under the MIT License (MIT) Sources at https://github.com/rafaelaznar/ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. --> <div class="modal-header"> <div style="font-family:Oswald , serif;" ng-include="'js/system/header.html'"></div> </div> <div class="modal-body"> <div id="wrapper"> <div class="container-fluid"> <div class="row"> <div class="col-lg-12" ng-cloak> <div class="row-fluid" ng-if="status"> <div class="col-xs-12"> <div class="alert alert-danger" role="alert"> <br> <h3 class="bg-danger">{{status}}</h3> <br> <a class="btn btn-default" ng-click="cancel()">Volver</a> </div> </div> </div> <div class="row-fluid" ng-if="!status"> <div class="span6 offset3"> <table class="table table-striped table-condensed"> <thead> <tr> <th>campo</th> <th>valor</th> </tr> </thead> <tbody> <tr ng-repeat="f in fields" class="text-left"> <td>{{f.longname}}</td> <!-- ----------------------------- --> <td ng-if="f.type == 'id'"><b>{{bean[f.name]}}</b></td> <td ng-if="f.type == 'text'">{{bean[f.name]}}</td> <!-- ----------------------------- --> <td ng-if="f.name == 'obj_zona'">{{bean[f.name].id}}</td> <td ng-if="f.name == 'obj_imagen'">{{bean[f.name].id}}</td> </tr> </tbody> </table> <div class="text-right"> <div>¿Está seguro de que desea borrar el registro?</div> <a class="btn btn-danger" ng-click="remove()">Si</a> <a class="btn btn-default" ng-click="cancel()">No</a> </div> </div> </div> </div> </div> </div> </div> </div> <div class="modal-footer"> <button class="btn btn-warning" type="button" ng-click="cancel()">Cancel</button> <div style="font-family: Questrial, serif;" ng-include="'js/system/footer.html'"></div> </div>
mit
ndeloof/git-plugin
src/test/java/hudson/plugins/git/GitChangeSetUtil.java
6820
package hudson.plugins.git; import org.jenkinsci.plugins.gitclient.Git; import org.jenkinsci.plugins.gitclient.GitClient; import hudson.EnvVars; import hudson.FilePath; import hudson.model.TaskListener; import hudson.scm.EditType; import hudson.util.StreamTaskListener; import org.eclipse.jgit.lib.ObjectId; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import junit.framework.TestCase; /** Utility class to support GitChangeSet testing. */ public class GitChangeSetUtil { static final String ID = "123abc456def"; static final String PARENT = "345mno678pqr"; static final String AUTHOR_NAME = "John Author"; static final String AUTHOR_DATE = "1234568 -0600"; static final String AUTHOR_DATE_FORMATTED = "1970-01-15T06:56:08-0600"; static final String COMMITTER_NAME = "John Committer"; static final String COMMITTER_DATE = "1234566 -0600"; static final String COMMITTER_DATE_FORMATTED = "1970-01-15T06:56:06-0600"; static final String COMMIT_TITLE = "Commit title."; static final String COMMENT = COMMIT_TITLE + "\n"; static GitChangeSet genChangeSet(boolean authorOrCommitter, boolean useLegacyFormat) { return genChangeSet(authorOrCommitter, useLegacyFormat, true); } public static GitChangeSet genChangeSet(boolean authorOrCommitter, boolean useLegacyFormat, boolean hasParent) { ArrayList<String> lines = new ArrayList<String>(); lines.add("Some header junk we should ignore..."); lines.add("header line 2"); lines.add("commit " + ID); lines.add("tree 789ghi012jkl"); if (hasParent) { lines.add("parent " + PARENT); } else { lines.add("parent "); } lines.add("author " + AUTHOR_NAME + " <[email protected]> " + AUTHOR_DATE); lines.add("committer " + COMMITTER_NAME + " <[email protected]> " + COMMITTER_DATE); lines.add(""); lines.add(" " + COMMIT_TITLE); lines.add(" Commit extended description."); lines.add(""); if (useLegacyFormat) { lines.add("123abc456def"); lines.add(" create mode 100644 some/file1"); lines.add(" delete mode 100644 other/file2"); } lines.add(":000000 123456 0000000000000000000000000000000000000000 123abc456def789abc012def345abc678def901a A\tsrc/test/add.file"); lines.add(":123456 000000 123abc456def789abc012def345abc678def901a 0000000000000000000000000000000000000000 D\tsrc/test/deleted.file"); lines.add(":123456 789012 123abc456def789abc012def345abc678def901a bc234def567abc890def123abc456def789abc01 M\tsrc/test/modified.file"); lines.add(":123456 789012 123abc456def789abc012def345abc678def901a bc234def567abc890def123abc456def789abc01 R012\tsrc/test/renamedFrom.file\tsrc/test/renamedTo.file"); lines.add(":000000 123456 bc234def567abc890def123abc456def789abc01 123abc456def789abc012def345abc678def901a C100\tsrc/test/original.file\tsrc/test/copyOf.file"); return new GitChangeSet(lines, authorOrCommitter); } static void assertChangeSet(GitChangeSet changeSet) { TestCase.assertEquals("123abc456def", changeSet.getId()); TestCase.assertEquals("Commit title.", changeSet.getMsg()); TestCase.assertEquals("Commit title.\nCommit extended description.\n", changeSet.getComment()); TestCase.assertEquals("Commit title.\nCommit extended description.\n".replace("\n", "<br>"), changeSet.getCommentAnnotated()); HashSet<String> expectedAffectedPaths = new HashSet<String>(7); expectedAffectedPaths.add("src/test/add.file"); expectedAffectedPaths.add("src/test/deleted.file"); expectedAffectedPaths.add("src/test/modified.file"); expectedAffectedPaths.add("src/test/renamedFrom.file"); expectedAffectedPaths.add("src/test/renamedTo.file"); expectedAffectedPaths.add("src/test/copyOf.file"); TestCase.assertEquals(expectedAffectedPaths, changeSet.getAffectedPaths()); Collection<GitChangeSet.Path> actualPaths = changeSet.getPaths(); TestCase.assertEquals(6, actualPaths.size()); for (GitChangeSet.Path path : actualPaths) { if ("src/test/add.file".equals(path.getPath())) { TestCase.assertEquals(EditType.ADD, path.getEditType()); TestCase.assertNull(path.getSrc()); TestCase.assertEquals("123abc456def789abc012def345abc678def901a", path.getDst()); } else if ("src/test/deleted.file".equals(path.getPath())) { TestCase.assertEquals(EditType.DELETE, path.getEditType()); TestCase.assertEquals("123abc456def789abc012def345abc678def901a", path.getSrc()); TestCase.assertNull(path.getDst()); } else if ("src/test/modified.file".equals(path.getPath())) { TestCase.assertEquals(EditType.EDIT, path.getEditType()); TestCase.assertEquals("123abc456def789abc012def345abc678def901a", path.getSrc()); TestCase.assertEquals("bc234def567abc890def123abc456def789abc01", path.getDst()); } else if ("src/test/renamedFrom.file".equals(path.getPath())) { TestCase.assertEquals(EditType.DELETE, path.getEditType()); TestCase.assertEquals("123abc456def789abc012def345abc678def901a", path.getSrc()); TestCase.assertEquals("bc234def567abc890def123abc456def789abc01", path.getDst()); } else if ("src/test/renamedTo.file".equals(path.getPath())) { TestCase.assertEquals(EditType.ADD, path.getEditType()); TestCase.assertEquals("123abc456def789abc012def345abc678def901a", path.getSrc()); TestCase.assertEquals("bc234def567abc890def123abc456def789abc01", path.getDst()); } else if ("src/test/copyOf.file".equals(path.getPath())) { TestCase.assertEquals(EditType.ADD, path.getEditType()); TestCase.assertEquals("bc234def567abc890def123abc456def789abc01", path.getSrc()); TestCase.assertEquals("123abc456def789abc012def345abc678def901a", path.getDst()); } else { TestCase.fail("Unrecognized path."); } } } public static GitChangeSet genChangeSet(ObjectId sha1, String gitImplementation, boolean authorOrCommitter) throws IOException, InterruptedException { EnvVars envVars = new EnvVars(); TaskListener listener = StreamTaskListener.fromStdout(); GitClient git = Git.with(listener, envVars).in(new FilePath(new File("."))).using(gitImplementation).getClient(); return new GitChangeSet(git.showRevision(sha1), authorOrCommitter); } }
mit
amishyn/auto_html
lib/auto_html/filters/image.rb
156
AutoHtml.add_filter(:image) do |text| text.gsub(/https?:\/\/.+\.(jpg|jpeg|bmp|gif|png)(\?\S+)?/i) do |match| %|<img src="#{match}" alt=""/>| end end
mit
RamIndani/takes
README.md
24514
<img src="http://www.takes.org/clapper.jpg" width="96px" height="96px"/> [![Made By Teamed.io](http://img.teamed.io/btn.svg)](http://www.teamed.io) [![DevOps By Rultor.com](http://www.rultor.com/b/yegor256/takes)](http://www.rultor.com/p/yegor256/takes) [![Build Status](https://img.shields.io/travis/yegor256/takes/master.svg)](https://travis-ci.org/yegor256/takes) [![Build status](https://img.shields.io/appveyor/ci/yegor256/takes/master.svg)](https://ci.appveyor.com/project/yegor256/takes/branch/master) [![Maven Central](https://img.shields.io/maven-central/v/org.takes/takes.svg)](https://maven-badges.herokuapp.com/maven-central/org.takes/takes) [![JavaDoc](https://img.shields.io/badge/javadoc-html-blue.svg)](http://www.javadoc.io/doc/org.takes/takes) [![Coverage Status](https://coveralls.io/repos/yegor256/takes/badge.svg?branch=master&service=github)](https://coveralls.io/github/yegor256/takes?branch=master) [![License](https://img.shields.io/badge/license-MIT-green.svg)](https://github.com/yegor256/takes/blob/master/LICENSE.txt) **Takes** is a [true object-oriented](http://www.yegor256.com/2014/11/20/seven-virtues-of-good-object.html) and [immutable](http://www.yegor256.com/2014/06/09/objects-should-be-immutable.html) Java6 web development framework. Its key benefits, comparing to all others, include these four fundamental principles: 1. not a single `null` ([why NULL is bad?](http://www.yegor256.com/2014/05/13/why-null-is-bad.html)) 2. not a single `public` `static` method ([why they are bad?](http://www.yegor256.com/2014/05/05/oop-alternative-to-utility-classes.html)) 3. not a single mutable class ([why they are bad?](http://www.yegor256.com/2014/06/09/objects-should-be-immutable.html)) 4. not a single `instanceof` keyword, type casting, or reflection ([why?](http://www.yegor256.com/2015/04/02/class-casting-is-anti-pattern.html)) Of course, there are no configuration files. Besides that, these are more traditional features, out of the box: * hit-refresh debugging * [XML+XSLT](http://www.yegor256.com/2014/06/25/xml-and-xslt-in-browser.html) * [JSON](http://en.wikipedia.org/wiki/JSON) * [RESTful](http://en.wikipedia.org/wiki/Representational_state_transfer) * Templates, incl. [Apache Velocity](http://velocity.apache.org/) This is what is not supported and won't be supported: * [WebSockets](http://en.wikipedia.org/wiki/WebSocket) These [blog posts](http://www.yegor256.com/tag/takes.org.html) may help you too. ## Quick Start Create this `App.java` file: ```java import org.takes.http.Exit; import org.takes.http.FtBasic; import org.takes.facets.fork.FkRegex; import org.takes.facets.fork.TkFork; public final class App { public static void main(final String... args) throws Exception { new FtBasic( new TkFork(new FkRegex("/", "hello, world!")), 8080 ).start(Exit.NEVER); } } ``` Then, download [`takes.jar`](http://repo1.maven.org/maven2/org/takes/takes/) and compile your Java code: ``` $ javac -cp takes.jar App.java ``` Now, run it like this: ```bash $ java -Dfile.encoding=UTF-8 -cp takes.jar:. App ``` Should work :) This code starts a new HTTP server on port 8080 and renders a plain-text page on all requests at the root URI. **Important**: Pay attention that UTF-8 encoding is set on the command line. The entire framework relies on your default Java encoding, which is not necessarily UTF-8 by default. To be sure, always set it on the command line with `file.encoding` Java argument. We decided not to hard-code "UTF-8" in our code mostly because this would be against the entire idea of Java localization, according to which a user always should have a choice of encoding and language selection. We're using `Charset.defaultCharset()` everywhere in the code. ## Build and Run With Maven If you're using Maven, this is how your `pom.xml` should look like: ```xml <project> <dependencies> <dependency> <groupId>org.takes</groupId> <artifactId>takes</artifactId> </dependency> </dependencies> <profiles> <profile> <id>hit-refresh</id> <build> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>exec-maven-plugin</artifactId> <version>1.3</version> <executions> <execution> <id>start-server</id> <phase>pre-integration-test</phase> <goals> <goal>java</goal> </goals> <configuration> <mainClass>foo.App</mainClass> <!-- your main class --> <cleanupDaemonThreads>false</cleanupDaemonThreads> <arguments> <argument>--port=${port}</argument> </arguments> </configuration> </execution> </executions> </plugin> </plugins> </build> </profile> </profiles> </project> ``` With this configutation you can run it from command line: ``` $ mvn clean integration-test -Phit-refresh -Dport=8080 ``` Maven will start the server and you can see it at `http://localhost:8080`. ## Unit Testing This is how you can unit test the app, using JUnit 4.x and [Hamcrest](http://hamcrest.org): ```java public final class AppTest { @Test public void returnsHttpResponse() throws Exception { MatcherAssert.assertThat( new RsPrint( new App().act(new RqFake("GET", "/")) ).printBody(), Matchers.equalsTo("hello, world!") ); } } ``` You can create a fake request with form parameters like this: ```java new RqForm.Fake( new RqFake(), "foo", "value-1", "bar", "value-2" ) ``` ## Integration Testing Here is how you can test the entire server via HTTP, using JUnit and [jcabi-http](http://http.jcabi.com) for making HTTP requests: ```java public final class AppITCase { @Test public void returnsTextPageOnHttpRequest() throws Exception { new FtRemote(new App()).exec( new FtRemote.Script() { @Override public void exec(final URI home) throws IOException { new JdkRequest(home) .fetch() .as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_OK) .assertBody(Matchers.equalTo("hello, world!")); } } ); } } ``` More complex integration testing examples you can find in one of the open source projects that are using Take, for example: [rultor.com](https://github.com/yegor256/rultor/tree/master/src/test/java/com/rultor/web). ## A Bigger Example Let's make it a bit more sophisticated: ```java public final class App { public static void main(final String... args) { new FtBasic( new TkFork( new FkRegex("/robots\\.txt", ""), new FkRegex("/", new TkIndex()) ), 8080 ).start(Exit.NEVER); } } ``` The `FtBasic` is accepting new incoming sockets on port 8080, parses them according to HTTP 1.1 specification and creates instances of class `Request`. Then, it gives requests to the instance of `TkFork` (`tk` stands for "take") and expects it to return an instance of `Take` back. As you probably understood already, the first regular expression that matches returns a take. `TkIndex` is our custom class (`tk` stands for "take"), let's see how it looks: ```java public final class TkIndex implements Take { @Override public Response act(final Request req) { return new RsHTML("<html>Hello, world!</html>"); } } ``` It is immutable and must implement a single method `act()`, which is returning an instance of `Response`. So far so good, but this class doesn't have an access to an HTTP request. Here is how we solve this: ```java new TkFork( new FkRegex( "/file/(?<path>[^/]+)", new TkRegex() { @Override public Response act(final RqRegex request) throws IOException { final File file = new File( request.matcher().group("path") ); return new RsHTML( FileUtils.readFileToString(file, Charsets.UTF_8) ); } } ) ) ``` We're using `TkRegex` instead of `Take`, in order to deal with `RqRegex` instead of a more generic `Request`. `RqRegex` gives an instance of `Matcher` used by `FkRegex` for pattern matching. Here is a more complex and verbose example: ```java public final class App { public static void main(final String... args) { new FtBasic( new TkFork( new FkRegex("/robots.txt", ""), new FkRegex("/", new TkIndex()), new FkRegex( "/xsl/.*", new TkWithType(new TkClasspath(), "text/xsl") ), new FkRegex("/account", new TkAccount(users)), new FkRegex("/balance/(?<user>[a-z]+)", new TkBalance()) ) ).start(Exit.NEVER); } } ``` ## Templates Now let's see how we can render something more complex than an plain text. First, XML+XSLT is a recommended mechanism of HTML rendering. Even though it may too complex, give it a try, you won't regret. Here is how we render a simple XML page that is transformed to HTML5 on-fly (more about `RsXembly` read below): ```java public final class TkAccount implements Take { private final Users users; public TkAccount(final Users users) { this.users = users; } @Override public Response act(final Request req) { final User user = this.users.find(new RqCookies(req).get("user")); return new RsLogin( new RsXSLT( new RsXembly( new XeStylesheet("/xsl/account.xsl"), new XeAppend("page", user) ) ), user ); } } ``` This is how that `User` class may look like: ```java public final class User implements XeSource { private final String name; private final int balance; @Override public Iterable<Directive> toXembly() { return new Directives().add("user") .add("name").set(this.name).up() .add("balance").set(Integer.toString(this.balance)); } } ``` Here is how `RsLogin` may look like: ```java public final class RsLogin extends RsWrap { public RsLogin(final Response response, final User user) { super( new RsWithCookie( response, "user", user.toString() ) ); } } ``` ## Velocity Templates Let's say, you want to use [Velocity](http://velocity.apache.org/): ```java public final class TkHelloWorld implements Take { @Override public Response act(final Request req) { return new RsVelocity( "hi, ${user.name}! You've got ${user.balance}", new RsVelocity.Pair("user", new User()) ); } } ``` You will need this extra dependency in classpath: ```xml <dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity-engine-core</artifactId> <scope>runtime</scope> </dependency> ``` ## Static Resources Very often you need to serve static resources to your web users, like CSS stylesheets, images, JavaScript files, etc. There are a few supplementary classes for that: ```java new TkFork( new FkRegex("/css/.+", new TkWithType(new TkClasspath(), "text/css")), new FkRegex("/data/.+", new TkFiles(new File("/usr/local/data")) ) ``` Class `TkClasspath` take static part of the request URI and finds a resource with this name in classpath. `TkFiles` just looks by file name in the directory configured. `TkWithType` sets content type of all responses coming out of the decorated take. ## Hit Refresh Debugging It is a very convenient feature. Once you start the app you want to be able to modify its static resources (CSS, JS, XSL, etc), refresh the page in a browser and immediately see the result. You don't want to re-compile the entire project and restart it. Here is what you need to do to your sources in order to enable that feature: ```java new TkFork( new FkRegex( "/css/.+", new TkWithType( new TkFork( new FkHitRefresh( "./src/main/resources/foo/scss/**", // what sources to watch "mvn sass:compile", // what to run when sources are modified new TkFiles("./target/css") ) new FkFixed(new TkClasspath()) ), "text/css" ) ) ) ``` This `FkHitRefresh` fork is a decorator of take. Once it sees `X-Take-Refresh` header in the request, it realizes that the server is running in "hit-refresh" mode and passes the request to the encapsulated take. Before it passes the request it tries to understand whether any of the resources are older than compiled files. If they are older, it tries to run compilation tool to build them again. ## Request Methods (POST, PUT, HEAD, etc.) Here is an example: ```java new TkFork( new FkRegex( "/user", new TkFork( new FkMethods("GET", new TkGetUser()), new FkMethods("POST,PUT", new TkPostUser()), new FkMethods("DELETE", new TkDeleteUser()) ) ) ) ``` ## Request Parsing Here is how you can parse an instance of `Request`: ```java Href href = new RqHref.Base(request).href(); URI uri = href.uri(); Iterable<String> values = href.param("key"); ``` For a more complex parsing try to use Apache Http Client or something similar. ## Form Processing Here is an example: ```java public final class TkSavePhoto implements Take { @Override public Response act(final Request req) { final String name = new RqForm(req).param("name"); return new RsWithStatus(HttpURLConnection.HTTP_NO_CONTENT); } } ``` ## Exception Handling By default, `TkFork` lets all exceptions bubble up. If one of your take crashes, a user will see a default error page. Here is how you can configure this behavior: ```java public final class App { public static void main(final String... args) { new FtBasic( new TkFallback( new TkFork( new FkRegex("/robots\\.txt", ""), new FkRegex("/", new TkIndex()) ), new FbChain( new FbStatus(404, new RsText("sorry, page is absent")), new FbStatus(405, new RsText("this method is not allowed here")), new Fallback() { @Override public Iterator<Response> route(final RqFallback req) { return Collections.<Response>singleton( new RsHTML("oops, something went terribly wrong!") ).iterator(); } } ) ), 8080 ).start(Exit.NEVER); } } ``` `TkFallback` decorates an instance of Take and catches all exceptions any of its take may throw. Once it's thrown, an instance of `FbChain` will find the most suitable fallback and will fetch a response from there. ## Redirects Sometimes it's very useful to return a redirect response (`30x` status code), either by a normal `return` or by throwing an exception. This example illustrates both methods: ```java public final class TkPostMessage implements Take { @Override public Response act(final Request req) { final String body = new RqPring(req).printBody(); if (body.isEmpty()) { throw new RsFlash( new RsForward(), "message can't be empty" ); } // save the message to the database return new RsFlash( new RsForward("/"), "thanks, the message was posted" ); } } ``` Then, you should decorate the entire `TkFork` with this `TkForward` and `TkFlash`: ```java public final class App { public static void main(final String... args) { new FtBasic( new TkFlash( new TkForward( new TkFork(new FkRegex("/", new TkPostMessage()) ) ), 8080 ).start(Exit.NEVER); } } ``` ## RsJSON Here is how we can deal with JSON: ```java public final class TkBalance extends TkFixed { @Override public Response act(final RqRegex request) { return new RsJSON( new User(request.matcher().group("user"))) ); } } ``` This is the method to add to `User`: ```java public final class User implements XeSource, RsJSON.Source { @Override public JsonObject toJSON() { return Json.createObjectBuilder() .add("balance", this.balance) .build(); } } ``` ## RsXembly Here is how you generate an XML page using [Xembly](http://www.takes.org): ```java Response response = new RsXembly( new XeAppend("page"), new XeDirectives("XPATH '/page'", this.user) ) ``` This is a complete example, with all possible options: ```java Response response = new RsXembly( new XeStylesheet("/xsl/account.xsl"), // add processing instruction new XeAppend( "page", // create a DOM document with "page" root element new XeMillis(false), // add "millis" attribute to the root, with current time user, // add user to the root element new XeSource() { @Override public Iterable<Directive> toXembly() { return new Directives().add("status").set("alive"); } }, new XeMillis(true), // replace "millis" attribute with take building time ), ) ``` This is the output that will be produced: ```xml <?xml version='1.0'?> <?xsl-stylesheet href='/xsl/account.xsl'?> <page> <millis>5648</millis> <user> <name>Jeff Lebowski</name> <balance>123</balance> </user> <status>alive</status> </page> ``` To avoid duplication of all this scaffolding in every page, you can create your own class, which will be used in every page, for example: ```java Response response = new RsXembly( new XeFoo(user) ) ``` This is how this `XeFoo` class would look like: ```java public final class XeFoo extends XeWrap { public XeFoo(final String stylesheet, final XeSource... sources) { super( new XeAppend( "page", new XeMillis(false), new XeStylesheet(stylesheet), new XeChain(sources), new XeSource() { @Override public Iterable<Directive> toXembly() { return new Directives().add("status").set("alive"); } }, new XeMillis(true) ) ); } } ``` You will need this extra dependency in classpath: ```xml <dependency> <groupId>com.jcabi.incubator</groupId> <artifactId>xembly</artifactId> </dependency> ``` More about this mechanism in this blog post: [XML Data and XSL Views in Takes Framework](http://www.yegor256.com/2015/06/25/xml-data-xsl-views-takes-framework.html). ## Cookies Here is how we drop a cookie to the user: ```java public final class TkIndex implements Take { @Override public Response act(final Request req) { return new RsWithCookie("auth", "John Doe"); } } ``` An HTTP response will contain this header, which will place a `auth` cookie into the user's browser: ``` HTTP/1.1 200 OK Set-Cookie: auth="John Doe" ``` This is how you read cookies from a request: ```java public final class TkIndex implements Take { @Override public Response act(final Request req) { // the list may be empty final Iterable<String> cookies = new RqCookies(req).cookie("my-cookie"); } } ``` ## GZIP Compression If you want to compress all your responses with GZIP, wrap your take in `TkGzip`: ```java new TkGzip(take) ``` Now, each request that contains `Accept-Encoding` request header with `gzip` compression method inside will receive a GZIP-compressed response. Also, you can compress an individual response, using `RsGzip` decorator. ## Content Negotiation Say, you want to return different content based on `Accept` header of the request (a.k.a. [content negotation](http://en.wikipedia.org/wiki/Content_negotiation)): ```java public final class TkIndex implements Take { @Override public Response act(final Request req) { return new RsFork( req, new FkTypes("text/*", new RsText("it's a text")) new FkTypes("application/json", new RsJSON("{\"a\":1}")) new FkTypes("image/png", /* something else */) ); } } ``` ## Authentication Here is an example of login via [Facebook](https://developers.facebook.com/docs/reference/dialogs/oauth/): ```java new TkAuth( new TkFork( new FkRegex("/", new TkHTML("hello, check <a href='/acc'>account</a>")), new FkRegex("/acc", new TkSecure(new TkAccount())) ), new PsChain( new PsCookie( new CcSafe(new CcHex(new CcXOR(new CcCompact(), "secret-code"))) ), new PsByFlag( new PsByFlag.Pair( PsFacebook.class.getSimpleName(), new PsFacebook("facebook-app-id", "facebook-secret") ), new PsByFlag.Pair( PsLogout.class.getSimpleName(), new PsLogout() ) ) ) ) ``` Then, you need to show a login link to the user, which he or she can click and get to the Facebook OAuth authentication page. Here is how you do this with XeResponse: ```java new RsXembly( new XeStylesheet("/xsl/index.xsl"), new XeAppend( "page", new XeFacebookLink(req, "facebook-app-id"), // ... other xembly sources ) ) ``` The link will be add to the XML page like this: ```xml <page> <links> <link rel="take:facebook" href="https://www.facebook.com/dialog/oauth..."/> </links> </page> ``` Similar mechanism can be used for `PsGithub`, `PsGoogle`, `PsLinkedin`, `PsTwitter`, etc. This is how you get currently logged in user: ```java public final class TkAccount implements Take { @Override public Response act(final Request req) { final Identity identity = new RqAuth(req).identity(); if (this.identity.equals(Identity.ANONYMOUS)) { // returns "urn:facebook:1234567" for a user logged in via Facebook this.identity().urn(); } } } ``` More about it in this blog post: [How Cookie-Based Authentication Works in the Takes Framework](http://www.yegor256.com/2015/05/18/cookie-based-authentication.html) ## Command Line Arguments There is a convenient class `FtCLI` that parses command line arguments and starts the necessary `Front` accordingly. There are a few command line arguments that should be passed to `FtCLI` constructor: ``` --port=1234 Tells the server to listen to TCP port 1234 --lifetime=5000 The server will die in five seconds (useful for integration testing) --refresh Run the server in hit-refresh mode --daemon Runs the server in Java daemon thread (for integration testing) --threads=30 Processes incoming HTTP requests in 30 parallel threads --max-latency=5000 Maximum latency in milliseconds per each request (longer requests will be interrupted) ``` For example: ```java public final class App { public static void main(final String... args) { new FtCLI( new TkFork(new FkRegex("/", "hello, world!")), args ).start(Exit.NEVER); } } ``` Then, run it like this: ``` $ java -cp take.jar App.class --port=8080 --refresh ``` You should see "hello, world!" at `http://localhost:8080`. Parameter `--port` also accepts file name, instead of a number. If the file exists, `FtCLI` will try to read its content and use it as port number. If the file is absent, `FtCLI` will allocate a new random port number, use it to start a server, and save it to the file. ## Logging The framework sends all logs to SLF4J logging facility. If you want to see them, configure one of [SLF4J bindings](http://www.slf4j.org/manual.html). ## Directory Layout You are free to use any build tool, but we recommend Maven. This is how your project directory layout may/should look like: ``` /src /main /java /foo App.java /scss /coffeescript /resources /xsl /js /css robot.txt log4j.properties /test /java /foo AppTest.java /resources log4j.properties pom.xml LICENSE.txt ``` ## How to contribute Fork repository, make changes, send us a pull request. We will review your changes and apply them to the `master` branch shortly, provided they don't violate our quality standards. To avoid frustration, before sending us your pull request please run full Maven build: ``` $ mvn clean install -Pqulice ``` If your default encoding is not UTF-8, some of unit tests will break. This is an intentional behavior. To fix that, set this environment variable in console (in Windows, for example): ``` SET JAVA_TOOL_OPTIONS=-Dfile.encoding=UTF-8 ``` To avoid build errors use maven 3.2+. Pay attention that our `pom.xml` inherits a lot of configuration from [jcabi-parent](http://parent.jcabi.com). [This article](http://www.yegor256.com/2015/02/05/jcabi-parent-maven-pom.html) explains why it's done this way. ## Got questions? If you have questions or general suggestions, don't hesitate to submit a new [Github issue](https://github.com/yegor256/takes/issues/new).
mit
ncave/FSharp.Compiler.Service
docs/reference/fsharp-compiler-ast-blockseparator.html
4675
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>BlockSeparator - F# Compiler Services</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content=""> <meta name="author" content="Microsoft Corporation, Dave Thomas, Anh-Dung Phan, Tomas Petricek"> <script src="https://code.jquery.com/jquery-1.8.0.js"></script> <script src="https://code.jquery.com/ui/1.8.23/jquery-ui.js"></script> <script src="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.2.1/js/bootstrap.min.js"></script> <link href="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.2.1/css/bootstrap-combined.min.css" rel="stylesheet"> <link type="text/css" rel="stylesheet" href="./content/style.css" /> <link type="text/css" rel="stylesheet" href="./content/fcs.css" /> <script type="text/javascript" src="./content/tips.js"></script> <!-- HTML5 shim, for IE6-8 support of HTML5 elements --> <!--[if lt IE 9]> <script src="https://html5shim.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="masthead"> <ul class="nav nav-pills pull-right"> <li><a href="http://fsharp.org">fsharp.org</a></li> <li><a href="http://github.com/fsharp/FSharp.Compiler.Service">github page</a></li> </ul> <h3 class="muted">F# Compiler Services</h3> </div> <hr /> <div class="row"> <div class="span9" id="main"> <h1>BlockSeparator</h1> <p> <span>Namespace: FSharp.Compiler</span><br /> <span>Parent Module: <a href="fsharp-compiler-ast.html">Ast</a></span> </p> <div class="xmldoc"> <p>denotes location of the separator block + optional position of the semicolon (used for tooling support)</p> </div> </div> <div class="span3"> <a href="https://nuget.org/packages/FSharp.Compiler.Service"> <img src="./images/logo.png" style="width:140px;height:140px;margin:10px 0px 0px 35px;border-style:none;" /> </a> <ul class="nav nav-list" id="menu"> <li class="nav-header"> <a href="./ja/index.html" class="nflag"><img src="./images/ja.png" /></a> <a href="./index.html" class="nflag nflag2"><img src="./images/en.png" /></a> F# Compiler Services </li> <li><a href="./index.html">Home page</a></li> <li class="divider"></li> <li><a href="https://www.nuget.org/packages/FSharp.Compiler.Service">Get Library via NuGet</a></li> <li><a href="http://github.com/fsharp/FSharp.Compiler.Service">Source Code on GitHub</a></li> <li><a href="http://github.com/fsharp/FSharp.Compiler.Service/blob/master/LICENSE">License</a></li> <li><a href="http://github.com/fsharp/FSharp.Compiler.Service/blob/master/RELEASE_NOTES.md">Release Notes</a></li> <li class="nav-header">Getting started</li> <li><a href="./index.html">Home page</a></li> <li><a href="./devnotes.html">Developer notes</a></li> <li><a href="./fsharp-readme.html">F# compiler readme</a></li> <li class="nav-header">Available services</li> <li><a href="./tokenizer.html">F# Language tokenizer</a></li> <li><a href="./untypedtree.html">Processing untyped AST</a></li> <li><a href="./editor.html">Using editor (IDE) services</a></li> <li><a href="./symbols.html">Using resolved symbols</a></li> <li><a href="./typedtree.html">Using resolved expressions</a></li> <li><a href="./project.html">Whole-project analysis</a></li> <li><a href="./interactive.html">Embedding F# interactive</a></li> <li><a href="./compiler.html">Embedding F# compiler</a></li> <li><a href="./filesystem.html">Virtualized file system</a></li> <li class="nav-header">Design Notes</li> <li><a href="./queue.html">The FSharpChecker operations queue</a></li> <li><a href="./caches.html">The FSharpChecker caches</a></li> <li><a href="./corelib.html">Notes on FSharp.Core.dll</a></li> <li class="nav-header">Documentation</li> <li><a href="./reference/index.html">API Reference</a> </li> </ul> </div> </div> </div> <a href="http://github.com/fsharp/FSharp.Compiler.Service"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://s3.amazonaws.com/github/ribbons/forkme_right_gray_6d6d6d.png" alt="Fork me on GitHub"></a> </body> </html>
mit
darenr/MOMA-Art
kadist/wup.py
1480
from nltk.corpus import wordnet import json import codecs import sys import time major_weight = 1.0 minor_weight = 0.8 similarity_threshold = 0.65 def fn(ss1, ss2, weight): similarity = ss1.wup_similarity(ss2) return (ss1, ss2, weight * similarity if similarity else 0 ) def isSynsetForm(s): return '.n.' in s or '.s.' in s or '.v.' in s if len(sys.argv) != 3: print 'usage <seed synset> <kadist.json>' sys.exit(-1) else: candidates = [] source = wordnet.synset(sys.argv[1]) tagged_works = 0 with codecs.open(sys.argv[2], 'rb', 'utf-8') as f: kadist = json.loads(f.read()) for m in kadist: if m['major_tags']: tagged_works += 1 candidates += [(wordnet.synset(tag), major_weight) for tag in m['major_tags'] if isSynsetForm(tag)] if m['minor_tags']: candidates += [(wordnet.synset(tag), minor_weight) for tag in m['minor_tags'] if isSynsetForm(tag) ] start = time.time() print 'starting similarity calculations on', tagged_works, 'tagged works' similarities = (fn(source, candidate[0], candidate[1]) for candidate in set([c for c in candidates if c[0] != source])) for result in (sorted( (sim for sim in similarities if sim[2] >= similarity_threshold), key=lambda x: x[2])): print result[0].name(), result[1].name(), result[2] print source.name(), 'occurs as a tag', len([c for c in candidates if c[0] == source]),'times' print 'number lookups', len(candidates), 'duration', time.time()-start
mit
ohinder/Everest
test/test_linear_system_solvers.jl
1834
using Base.Test using FactCheck # test linear system solvers function test_linear_solver(solver::abstract_linear_system_solver, sym::Symbol) start_advanced_timer() n = 40; mat = speye(n) mat = mat + mat' mat[1,1] = -100; mat[2,2] = -100; initialize!(solver, mat, sym); test_linear_solver_inertia(solver, sym, mat, 1, 38, 2) rhs = 1.0*rand(n, 2); A = rand(n,n) mat[:,:] = A + A' test_linear_solver_accuracy(solver, sym, mat, rhs, 38, 2) finalize!(solver) pause_advanced_timer() end function test_linear_solver_inertia(solver::abstract_linear_system_solver, sym::Symbol, mat::SparseMatrixCSC{Float64,Int64}, correct_inertia::Int64, n::Int64, m::Int64) @test solver._SparseMatrix == mat inertia = ls_factor!(solver, n, m) @fact inertia --> correct_inertia end function test_linear_solver_accuracy(solver::abstract_linear_system_solver, sym::Symbol, mat::SparseMatrixCSC{Float64,Int64}, rhs::AbstractArray, n::Int64, m::Int64) ls_factor!(solver, n, m) sol = ls_solve(solver,rhs); #sol = ls_solve(solver,rhs); err = norm(mat*sol - rhs,1)/norm(sol,1) @fact err --> less_than(1e-6) end facts("Linear solvers") do # test mumps solver context("MUMPS") do ls_solver_mumps = linear_solver_MUMPS(); test_linear_solver( ls_solver_mumps, :symmetric ) #MPI.Finalize() end # test julia solver context("julia") do # test julia lu factor ls_solver_julia = linear_solver_JULIA(); test_linear_solver( ls_solver_julia , :unsymmetric ) # test julia cholesky factor ls_solver_julia = linear_solver_JULIA(); test_linear_solver( ls_solver_julia, :definite ) end end # test matlab ldl solver #context("matlab") do # ls_solver_matlab = linear_solver_MATLAB(); # test_linear_solver( ls_solver_matlab, :symmetric ) #end
mit
etsy/phan
tests/files/src/0920_flatten.php
648
<?php /** @throws RuntimeException */ function maybeThrow920() { if ( rand() ) { throw new \RuntimeException; } return true; } function check920(int $flag) { try { maybeThrow920(); } catch ( \RuntimeException $e ) { $flag = false; $excep = $e; } catch (Error $e) { $flag = 'error'; } if (rand()) { '@phan-debug-var $excep, $flag'; return [$flag, $excep ?? null]; // PhanCoalescingNeverUndefined Using $excep ?? null seems unnecessary - the expression appears to always be defined } else { '@phan-debug-var $e'; return $e ?? null; } } check920();
mit
klavs/db-lv
docs/vaditaji/d1cc27bd-905d-1c39-c2f3-f53ef603808a.html
4364
<!doctype html> <html lang="lv"> <head prefix="og: http://ogp.me/ns# fb: http://ogp.me/ns/fb# profile: http://ogp.me/ns/profile#" itemscope itemtype="http://schema.org/WebSite" > <meta charset="utf-8"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <!-- Google Tag Manager --> <script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0], j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src= 'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f); })(window,document,'script','dataLayer','GTM-KSXCLLZ');</script> <!-- End Google Tag Manager --> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta property="fb:app_id" content="1236171016488428" /> <meta property="og:type" content="profile" /> <meta property="og:url" content="https://lvdb.lv/vaditaji/d1cc27bd-905d-1c39-c2f3-f53ef603808a" /> <meta property="og:title" content="Gražina Afanasjeva" /> <meta name="twitter:card" content="summary" /> <meta name="twitter:site" content="@lvdb_lv" /> <meta name="msvalidate.01" content="CD405DAD5EA4CF65237EAB3E933C6C74" /> <title>Gražina Afanasjeva</title> <meta itemprop='name' content="lvdb.lv"> <link rel="canonical" href="https://lvdb.lv" itemprop="url"> <link rel="alternate" hreflang="lv-LV" href="https://lvdb.lv"> <meta name="theme-color" content="#f4c671"> <link href="https://fonts.googleapis.com/css?family=Roboto:300,400,700&amp;subset=latin-ext" rel="stylesheet"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/7.0.0/normalize.min.css" /> <link rel="stylesheet" href="/static/style.css" /> <link rel="icon" href="images/favicon.png"> </head> <body> <!-- Google Tag Manager (noscript) --> <noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-KSXCLLZ" height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript> <!-- End Google Tag Manager (noscript) --> <script> window.fbAsyncInit = function() { FB.init({ appId : '1236171016488428', cookie : true, xfbml : true, version : 'v2.8' }); FB.AppEvents.logPageView(); }; (function(d, s, id){ var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) {return;} js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/sdk.js"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); </script> <div class="background"> <div class="header-background"></div> </div> <div class="main-section" itemscope itemtype="http://schema.org/Person"> <!-- <header> <div class="header__hero"></div> <div class="header__main-info-holder"> <div class="header__main-info"> <div class="image"></div> <span class="name-row"> <h1 class="group-name" itemprop="name">Gražina Afanasjeva</h1> </span> </div> </div> --> </header> <main> <h1 itemprop="name">Gražina Afanasjeva</h1> <section> <h2>Kolektīvi</h2> <ul class="property-list"> <li class="property" itemprop="affiliation brand memberOf worksFor" itemscope itemtype="http://schema.org/DanceGroup"> <a href="/kolektivi/Lindale" itemprop="url sameAs mainEntityOfPage" title="Durbes novada domes vidējās paaudzes deju kolektīvs &quot;Lindale&quot;"> <span itemprop="name">Lindale</span> </a> </li> </ul> </section> </main> </div> </body> </html>
mit
VirusFree/SharpDX
Source/Toolkit/SharpDX.Toolkit/Graphics/ModelData.Material.cs
3138
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System.Collections.Generic; using SharpDX.Serialization; namespace SharpDX.Toolkit.Graphics { public partial class ModelData { /// <summary> /// Class Mesh /// </summary> public sealed class Material : CommonData, IDataSerializable { public Material() { Textures = new Dictionary<string, List<MaterialTexture>>(); Properties = new PropertyCollection(); } /// <summary> /// The textures /// </summary> public Dictionary<string, List<MaterialTexture>> Textures; /// <summary> /// Gets attributes attached to this material. /// </summary> public PropertyCollection Properties; void IDataSerializable.Serialize(BinarySerializer serializer) { if (serializer.Mode == SerializerMode.Write) { serializer.Writer.Write(Textures.Count); foreach (var texture in Textures) { var name = texture.Key; var list = texture.Value; serializer.Serialize(ref name); serializer.Serialize(ref list); } } else { var count = serializer.Reader.ReadInt32(); Textures = new Dictionary<string, List<MaterialTexture>>(count); for(int i = 0; i < count; i++) { string name = null; List<MaterialTexture> list = null; serializer.Serialize(ref name); serializer.Serialize(ref list); Textures.Add(name, list); } } serializer.Serialize(ref Properties); } } } }
mit
SolarCactus/ARKCraft-Code
src/main/java/com/arkcraft/module/items/common/entity/EntityDodoEgg.java
2029
package com.arkcraft.module.items.common.entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.projectile.EntityThrowable; import net.minecraft.item.Item; import net.minecraft.util.DamageSource; import net.minecraft.util.EnumParticleTypes; import net.minecraft.util.MovingObjectPosition; import net.minecraft.world.World; import com.arkcraft.module.creature.common.entity.passive.EntityDodo; import com.arkcraft.module.items.ARKCraftItems; public class EntityDodoEgg extends EntityThrowable { public EntityDodoEgg(World w) { super(w); } public EntityDodoEgg(World w, EntityLivingBase base) { super(w, base); } public EntityDodoEgg(World w, double x, double y, double z) { super(w, x, y, z); } /** * Called when this EntityThrowable hits a block or entity. */ protected void onImpact(MovingObjectPosition pos) { if (pos.entityHit != null) { pos.entityHit.attackEntityFrom(DamageSource.causeThrownDamage(this, this.getThrower()), 0.0F); } if (!this.worldObj.isRemote && this.rand.nextInt(8) == 0) { byte b0 = 1; if (this.rand.nextInt(32) == 0) { b0 = 4; } for (int i = 0; i < b0; ++i) { EntityDodo entitydodo = new EntityDodo(this.worldObj); entitydodo.setGrowingAge(-24000); entitydodo.setLocationAndAngles(this.posX, this.posY, this.posZ, this.rotationYaw, 0.0F); this.worldObj.spawnEntityInWorld(entitydodo); } } @SuppressWarnings("unused") double d0 = 0.08D; for (int j = 0; j < 8; ++j) { // worldObj.spawnParticle(EnumParticleTypes.SNOWBALL, this.posX, // this.posY, this.posZ, 0.0D, 0.0D, 0.0D); this.worldObj.spawnParticle(EnumParticleTypes.ITEM_CRACK, this.posX, this.posY, this.posZ, ((double) this.rand.nextFloat() - 0.5D) * 0.08D, ((double) this.rand.nextFloat() - 0.5D) * 0.08D, ((double) this.rand.nextFloat() - 0.5D) * 0.08D, new int[] { Item.getIdFromItem(ARKCraftItems.dodo_egg) }); } if (!this.worldObj.isRemote) { this.setDead(); } } }
mit
GridProtectionAlliance/gsf
Source/Libraries/GSF.Security/RestrictAccessAttribute.cs
3748
//****************************************************************************************************** // RestrictAccessAttribute.cs - Gbtc // // Copyright © 2012, Grid Protection Alliance. All Rights Reserved. // // Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See // the NOTICE file distributed with this work for additional information regarding copyright ownership. // The GPA licenses this file to you under the MIT License (MIT), 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.opensource.org/licenses/MIT // // Unless agreed to in writing, the subject software distributed under the License is distributed on an // "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the // License for the specific language governing permissions and limitations. // // Code Modification History: // ---------------------------------------------------------------------------------------------------- // 01/06/2011 - Pinal C. Patel // Generated original version of source code. // 12/20/2012 - Starlynn Danyelle Gilliam // Modified Header. // //****************************************************************************************************** using System; using System.Threading; namespace GSF.Security { /// <summary> /// Represents an <see cref="Attribute"/> that can be used restrict access to a class when using role-based security. /// </summary> [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] public class RestrictAccessAttribute : Attribute { #region [ Members ] // Fields private string[] m_roles; #endregion #region [ Constructors ] /// <summary> /// Initializes a new instance of the <see cref="RestrictAccessAttribute"/> class. /// </summary> public RestrictAccessAttribute() : this(null) { } /// <summary> /// Initializes a new instance of the <see cref="RestrictAccessAttribute"/> class. /// </summary> /// <param name="roles">List of either roles the current thread principal must have in order to have access.</param> public RestrictAccessAttribute(params string[] roles) { m_roles = roles; } #endregion #region [ Properties ] /// <summary> /// Gets or sets the list of either roles the current thread principal must have in order to have access. /// </summary> public string[] Roles { get { return m_roles; } set { m_roles = value; } } #endregion #region [ Methods ] /// <summary> /// Checks if the current thread principal has at least one of the <see cref="Roles"/> in order to have access. /// </summary> /// <returns>true if the current thread principal has access, otherwise false.</returns> public bool CheckAccess() { if (m_roles != null) { // One or more roles have been specified. foreach (string role in m_roles) { // Check role against principal's role membership. if (Thread.CurrentPrincipal.IsInRole(role)) // Principal has membership to the role so allow access. return true; } } return false; } #endregion } }
mit
rgbkrk/hydrogen
lib/existing-kernel-picker.js
2362
/* @flow */ import SelectListView from "atom-select-list"; import store from "./store"; import _ from "lodash"; import tildify from "tildify"; import WSKernel from "./ws-kernel"; import { kernelSpecProvidesGrammar } from "./utils"; import type Kernel from "./kernel"; function getName(kernel: Kernel) { const prefix = kernel instanceof WSKernel ? `${kernel.gatewayName}: ` : ""; return ( prefix + kernel.displayName + " - " + store .getFilesForKernel(kernel) .map(tildify) .join(", ") ); } export default class ExistingKernelPicker { kernelSpecs: Array<Kernelspec>; selectListView: SelectListView; panel: ?atom$Panel; previouslyFocusedElement: ?HTMLElement; constructor() { this.selectListView = new SelectListView({ itemsClassList: ["mark-active"], items: [], filterKeyForItem: kernel => getName(kernel), elementForItem: kernel => { const element = document.createElement("li"); element.textContent = getName(kernel); return element; }, didConfirmSelection: kernel => { const { filePath, editor, grammar } = store; if (!filePath || !editor || !grammar) return this.cancel(); store.newKernel(kernel, filePath, editor, grammar); this.cancel(); }, didCancelSelection: () => this.cancel(), emptyMessage: "No running kernels for this language." }); } destroy() { this.cancel(); return this.selectListView.destroy(); } cancel() { if (this.panel != null) { this.panel.destroy(); } this.panel = null; if (this.previouslyFocusedElement) { this.previouslyFocusedElement.focus(); this.previouslyFocusedElement = null; } } attach() { this.previouslyFocusedElement = document.activeElement; if (this.panel == null) this.panel = atom.workspace.addModalPanel({ item: this.selectListView }); this.selectListView.focus(); this.selectListView.reset(); } async toggle() { if (this.panel != null) { this.cancel(); } else if (store.filePath && store.grammar) { await this.selectListView.update({ items: store.runningKernels.filter(kernel => kernelSpecProvidesGrammar(kernel.kernelSpec, store.grammar) ) }); store.markers.clear(); this.attach(); } } }
mit
mperdeck/jsnlog
jsnlog/PublicFacing/Configuration/JsnlogConfiguration/ICanCreateJsonFields.cs
977
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace JSNLog { /// <summary> /// Classes (loggers, etc.) that implement this interface can generate /// JSON name-value fields based on their properties. These fields are used in the /// JSON object passed to setOptions. /// </summary> public interface ICanCreateJsonFields { /// <summary> /// Creates JSON fields for a JSON object that will be passed to setOptions /// for the element (logger, etc.) that implementes this interface. /// </summary> /// <param name="jsonFields"> /// The JSON fields are added to this. /// </param> /// <param name="appenderNames"></param> /// <param name="virtualToAbsoluteFunc"></param> void AddJsonFields(IList<string> jsonFields, Dictionary<string, string> appenderNames, Func<string, string> virtualToAbsoluteFunc); } }
mit
vrenkens/Nabu-asr
nabu/neuralnetworks/decoders/alignment_decoder.py
3558
'''@file alignment_decoder.py contains the AlignmentDecoder''' import os import struct import numpy as np import tensorflow as tf import decoder class AlignmentDecoder(decoder.Decoder): '''gets the HMM state posteriors''' def __call__(self, inputs, input_seq_length): '''decode a batch of data Args: inputs: the inputs as a dictionary of [batch_size x time x ...] tensors input_seq_length: the input sequence lengths as a dictionary of [batch_size] vectors Returns: - the decoded sequences as a dictionary of outputs ''' with tf.name_scope('alignment_decoder'): #create the decoding graph logits, logits_seq_length = self.model( inputs, input_seq_length, targets=[], target_seq_length=[], is_training=False) #compute the log probabilities logprobs = tf.log(tf.nn.softmax(logits.values()[0])) #read the prior if it exists, otherwise use uniform prior if os.path.exists(self.conf['prior']): prior = np.load(self.conf['prior']) else: print( 'WARNING could not find prior in file %s using uniform' ' prior' % self.conf['prior']) output_dim = self.model.output_dims.values()[0] prior = np.ones([output_dim])/output_dim #compute posterior to pseudo likelihood loglikes = logprobs - np.log(prior) outputs = {o:(loglikes, logits_seq_length[o]) for o in logits} return outputs def write(self, outputs, directory, names): '''write the output of the decoder to disk args: outputs: the outputs of the decoder directory: the directory where the results should be written names: the names of the utterances in outputs ''' for o in outputs: if not os.path.isdir(os.path.join(directory, o)): os.makedirs(os.path.join(directory, o)) batch_size = outputs[o][0].shape[0] scp_file = os.path.join(directory, o, 'feats.scp') ark_file = os.path.join(directory, o, 'loglikes.ark') for i in range(batch_size): output = outputs[o][0][i, :outputs[o][1][i]] arkwrite(scp_file, ark_file, names[i], output) def update_evaluation_loss(self, loss, outputs, references, reference_seq_length): '''update the evaluation loss args: loss: the current evaluation loss outputs: the outputs of the decoder as a dictionary references: the references as a dictionary reference_seq_length: the sequence lengths of the references Returns: an op to update the evalution loss ''' raise Exception('AlignmentDecoder can not be used to validate') def arkwrite(scp_file, ark_file, name, array): '''write the array to the arkfile''' scp_fid = open(scp_file, 'a') ark_fid = open(ark_file, 'ab') rows, cols = array.shape ark_fid.write(struct.pack('<%ds'%(len(name)), name)) pos = ark_fid.tell() ark_fid.write(struct.pack('<xcccc', 'B', 'F', 'M', ' ')) ark_fid.write(struct.pack('<bi', 4, rows)) ark_fid.write(struct.pack('<bi', 4, cols)) ark_fid.write(array) scp_fid.write('%s %s:%s\n' % (name, ark_file, pos)) scp_fid.close() ark_fid.close()
mit
AlexanderL/grunt-torn-asset-cachebuster
test/fixtures/images.css
297
h1 { background-image: url(hello.png); } h2 { background-image: url('//cdn.1.test.com/hello.png'); } h3 { background-image: url("//cdn.2.test.com/hello.png"); } h4 { background-image: url(data:image/png;base64,TEST==); } h5 { background-image: url('data:image/png;base64,TEST=='); }
mit
ThePletch/pact_broker
lib/pact_broker/logging.rb
645
require 'logger' require 'pathname' module PactBroker module Logging # Need to make this configurable based on the calling app! LOG_DIR = Pathname.new(File.join(File.dirname(__FILE__), '..', '..', 'log')).cleanpath LOG_FILE_NAME = "#{ENV['RACK_ENV'] || 'development'}.log" def self.included(base) base.extend(self) end def logger= logger @@logger = logger end def logger @@logger ||= begin FileUtils.mkdir_p(LOG_DIR) logger = Logger.new(File.join(LOG_DIR, LOG_FILE_NAME)) logger.level = Logger::DEBUG logger end end end include Logging end
mit
keesdewit82/LasVegasCoin
src/lasvegascoind.cpp
6106
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The Las Vegas Coin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "clientversion.h" #include "init.h" #include "main.h" #include "masternodeconfig.h" #include "noui.h" #include "rpcserver.h" #include "ui_interface.h" #include "util.h" #include <boost/algorithm/string/predicate.hpp> #include <boost/filesystem.hpp> #include <boost/thread.hpp> /* Introduction text for doxygen: */ /*! \mainpage Developer documentation * * \section intro_sec Introduction * * This is the developer documentation of the reference client for an experimental new digital currency called Las Vegas Coin (http://www.lasvegascoin.org), * which enables instant payments to anyone, anywhere in the world. Las Vegas Coin uses peer-to-peer technology to operate * with no central authority: managing transactions and issuing money are carried out collectively by the network. * * The software is a community-driven open source project, released under the MIT license. * * \section Navigation * Use the buttons <code>Namespaces</code>, <code>Classes</code> or <code>Files</code> at the top of the page to start navigating the code. */ static bool fDaemon; void DetectShutdownThread(boost::thread_group* threadGroup) { bool fShutdown = ShutdownRequested(); // Tell the main threads to shutdown. while (!fShutdown) { MilliSleep(200); fShutdown = ShutdownRequested(); } if (threadGroup) { threadGroup->interrupt_all(); threadGroup->join_all(); } } ////////////////////////////////////////////////////////////////////////////// // // Start // bool AppInit(int argc, char* argv[]) { boost::thread_group threadGroup; boost::thread* detectShutdownThread = NULL; bool fRet = false; // // Parameters // // If Qt is used, parameters/lasvegascoin.conf are parsed in qt/lasvegascoin.cpp's main() ParseParameters(argc, argv); // Process help and version before taking care about datadir if (mapArgs.count("-?") || mapArgs.count("-help") || mapArgs.count("-version")) { std::string strUsage = _("LasVegasCoin Core Daemon") + " " + _("version") + " " + FormatFullVersion() + "\n"; if (mapArgs.count("-version")) { strUsage += LicenseInfo(); } else { strUsage += "\n" + _("Usage:") + "\n" + " lasvegascoind [options] " + _("Start LasVegasCoin Core Daemon") + "\n"; strUsage += "\n" + HelpMessage(HMM_BITCOIND); } fprintf(stdout, "%s", strUsage.c_str()); return false; } try { if (!boost::filesystem::is_directory(GetDataDir(false))) { fprintf(stderr, "Error: Specified data directory \"%s\" does not exist.\n", mapArgs["-datadir"].c_str()); return false; } try { ReadConfigFile(mapArgs, mapMultiArgs); } catch (std::exception& e) { fprintf(stderr, "Error reading configuration file: %s\n", e.what()); return false; } // Check for -testnet or -regtest parameter (Params() calls are only valid after this clause) if (!SelectParamsFromCommandLine()) { fprintf(stderr, "Error: Invalid combination of -regtest and -testnet.\n"); return false; } // parse masternode.conf std::string strErr; if (!masternodeConfig.read(strErr)) { fprintf(stderr, "Error reading masternode configuration file: %s\n", strErr.c_str()); return false; } // Command-line RPC bool fCommandLine = false; for (int i = 1; i < argc; i++) if (!IsSwitchChar(argv[i][0]) && !boost::algorithm::istarts_with(argv[i], "lasvegascoin:")) fCommandLine = true; if (fCommandLine) { fprintf(stderr, "Error: There is no RPC client functionality in lasvegascoind anymore. Use the lasvegascoin-cli utility instead.\n"); exit(1); } #ifndef WIN32 fDaemon = GetBoolArg("-daemon", false); if (fDaemon) { fprintf(stdout, "Las Vegas Coin server starting\n"); // Daemonize pid_t pid = fork(); if (pid < 0) { fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno); return false; } if (pid > 0) // Parent process, pid is child process id { return true; } // Child process falls through to rest of initialization pid_t sid = setsid(); if (sid < 0) fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno); } #endif SoftSetBoolArg("-server", true); detectShutdownThread = new boost::thread(boost::bind(&DetectShutdownThread, &threadGroup)); fRet = AppInit2(threadGroup); } catch (std::exception& e) { PrintExceptionContinue(&e, "AppInit()"); } catch (...) { PrintExceptionContinue(NULL, "AppInit()"); } if (!fRet) { if (detectShutdownThread) detectShutdownThread->interrupt(); threadGroup.interrupt_all(); // threadGroup.join_all(); was left out intentionally here, because we didn't re-test all of // the startup-failure cases to make sure they don't result in a hang due to some // thread-blocking-waiting-for-another-thread-during-startup case } if (detectShutdownThread) { detectShutdownThread->join(); delete detectShutdownThread; detectShutdownThread = NULL; } Shutdown(); return fRet; } int main(int argc, char* argv[]) { SetupEnvironment(); // Connect lasvegascoind signal handlers noui_connect(); return (AppInit(argc, argv) ? 0 : 1); }
mit
hatchery/Genepool2
genes/apt/test_get.py
1570
from unittest import TestCase from unittest.mock import patch from genes.apt.get import APTGet class APTGetInstallTestCase(TestCase): def test_apt_get_install_no_items_fails(self): with patch('genes.process.process.Popen') as mock_popen: apt_get = APTGet() with self.assertRaises(ValueError): apt_get.install() mock_popen.assert_not_called() def test_apt_get_install_single_item_calls_popen(self): with patch('genes.process.process.Popen') as mock_popen: apt_get = APTGet() apt_get.install('test') mock_popen.assert_called_with(('apt-get', '-y', 'install', 'test')) def test_apt_get_install_multiple_items_calls_popen(self): with patch('genes.process.process.Popen') as mock_popen: apt_get = APTGet() apt_get.install('test1', 'test2') mock_popen.assert_called_once_with(('apt-get', '-y', 'install', 'test1', 'test2')) class TestAPTGetUpdate(TestCase): def test_apt_get_update_calls_popen(self): with patch('genes.process.process.Popen') as mock_popen: apt_get = APTGet() apt_get.update() mock_popen.assert_called_once_with(('apt-get', '-y', 'update')) class TestAPTGetUpgrade(TestCase): def test_apt_get_upgrade_with_no_items_calls_popen(self): with patch('genes.process.process.Popen') as mock_popen: apt_get = APTGet() apt_get.upgrade() mock_popen.assert_called_once_with(('apt-get', '-y', 'upgrade'))
mit
syberia/director
docs/reference/get_helpers.html
5005
<!-- Generated by pkgdown: do not edit by hand --> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Get all helper files associated with an idempotent resource directory. — get_helpers • director</title> <!-- jquery --> <script src="https://code.jquery.com/jquery-3.1.0.min.js" integrity="sha384-nrOSfDHtoPMzJHjVTdCopGqIqeYETSXhZDFyniQ8ZHcVy08QesyHcnOUpMpqnmWq" crossorigin="anonymous"></script> <!-- Bootstrap --> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> <!-- Font Awesome icons --> <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-T8Gy5hrqNKT+hzMclPo118YTQO6cYprQmhrYwIiQ/3axmI1hQomh7Ud2hPOy8SP1" crossorigin="anonymous"> <!-- pkgdown --> <link href="../pkgdown.css" rel="stylesheet"> <script src="../jquery.sticky-kit.min.js"></script> <script src="../pkgdown.js"></script> <!-- mathjax --> <script src='https://mathjax.rstudio.com/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML'></script> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container template-reference-topic"> <header> <div class="navbar navbar-default navbar-fixed-top" role="navigation"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="../index.html">director</a> </div> <div id="navbar" class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li> <a href="../reference/index.html">Reference</a> </li> <li> <a href="../articles/index.html">Articles</a> </li> </ul> <ul class="nav navbar-nav navbar-right"> </ul> </div><!--/.nav-collapse --> </div><!--/.container --> </div><!--/.navbar --> </header> <div class="row"> <div class="col-md-9 contents"> <div class="page-header"> <h1>Get all helper files associated with an idempotent resource directory.</h1> </div> <p>Get all helper files associated with an idempotent resource directory.</p> <pre class="usage"><span class='fu'>get_helpers</span>(<span class='no'>path</span>, <span class='no'>...</span>, <span class='kw'>leave_idempotent</span> <span class='kw'>=</span> <span class='fl'>FALSE</span>)</pre> <h2 class="hasAnchor" id="arguments"><a class="anchor" href="#arguments"></a> Arguments</h2> <table class="ref-arguments"> <colgroup><col class="name" /><col class="desc" /></colgroup> <tr> <th>path</th> <td><p>character. The *absolute* path of the idempotent resource.</p></td> </tr> <tr> <th>...</th> <td><p>additional parameters to pass to <code>list.files</code>.</p></td> </tr> <tr> <th>leave_idempotent</th> <td><p>logical. Whether or not to leave the idempotent file (non-helper). By default <code>FALSE</code>.</p></td> </tr> </table> <h2 class="hasAnchor" id="value"><a class="anchor" href="#value"></a>Value</h2> <p>a character list of relative helper paths.</p> <h2 class="hasAnchor" id="examples"><a class="anchor" href="#examples"></a>Examples</h2> <pre class="examples"><div class='input'><span class='fu'>not_run</span>({ <span class='co'># If we have a directory structure given by \code{"model/model.R"},</span> <span class='co'># \code{"model/constants.R"}, \code{"model/functions.R"}, then the</span> <span class='co'># below will return \code{c("constants.R", "functions.R")}.</span> <span class='fu'>get_helpers</span>(<span class='st'>"model"</span>) })</div></pre> </div> <div class="col-md-3 hidden-xs hidden-sm" id="sidebar"> <h2>Contents</h2> <ul class="nav nav-pills nav-stacked"> <li><a href="#arguments">Arguments</a></li> <li><a href="#value">Value</a></li> <li><a href="#examples">Examples</a></li> </ul> </div> </div> <footer> <div class="copyright"> <p>Developed by Robert Krzyzanowski.</p> </div> <div class="pkgdown"> <p>Site built with <a href="http://hadley.github.io/pkgdown/">pkgdown</a>.</p> </div> </footer> </div> </body> </html>
mit
netlify/staticgen
content/projects/tclssg.md
1503
--- title: Tclssg repo: tclssg/tclssg homepage: https://github.com/tclssg/tclssg language: - Tcl license: - MIT templates: - Custom description: A static site generator that uses Tcl for both code and templates. --- Tclssg is a static site generator written in Tcl that uses Markdown for content markup, Bootstrap for layout (with Bootstrap theme support) and Tcl code embedded in HTML for templating. ### Features - Markdown, Bootstrap themes, Tcl templates; - Distinguishes between plain old pages and blog posts; - RSS feeds; - SEO and usability features: sitemaps, canonical and previous/next links, `noindex` where appropriate. - Valid HTML5 and CSS level 3 output; - Deployment over FTP; - Deployment over SCP and other protocols with a custom deployment command; - Support for external comment engines; - Relative links in the HTML output that make it suitable for viewing over _file://_; - Reasonably fast (can process 500 input pages into 650 HTML files in about 35 seconds on a laptop with an SSD); - Few dependencies. - Can be used as a library from Tcl. ### Page example ```markdown { title {Test page} blogPost 1 tags {test {a long tag with spaces}} date 2014-01-02 hideDate 1 } **Lorem ipsum** reprehenderit _ullamco deserunt sit eiusmod_ ut minim in id voluptate proident enim eu aliqua sit. <!-- more --> Mollit ex cillum pariatur anim [exemplum](http://example.com) tempor exercitation sed eu Excepteur dolore deserunt cupidatat aliquip irure in fugiat eu laborum est. ```
mit
materik/unitility
ObjC/Weight/Ounce.h
155
// // Ounce.h // Pods // // Created by materik on 17/02/16. // // #import "Unit.h" #import "WeightProtocol.h" @interface Ounce : Unit <Weight> @end
mit
johanlantz/headsetpresenter
HeadsetPresenter_Bluetools/HeadsetPresenter/Bluetools/BlueTools SDK v1.21/dotNetCF200/C#/ObexPushClient/Properties/AssemblyInfo.cs
1262
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("ObjectPushSample200CF")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Franson")] [assembly: AssemblyProduct("ObjectPushSample200CF")] [assembly: AssemblyCopyright("Copyright © Franson 2006")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("db5a4510-da02-424b-ab1a-6a8cbe3656f7")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // [assembly: AssemblyVersion("1.0.0.0")]
mit
antmat/blackhole
src/benchmark/logger/logger.cpp
3474
#include <epicmeter/benchmark.hpp> #include <blackhole/formatter/string.hpp> #include <blackhole/logger.hpp> #include <blackhole/macro.hpp> #include <blackhole/sink/null.hpp> #include <blackhole/sink/stream.hpp> #include "../util.hpp" #define BH_BASE_LOG(__log__, ...) \ if (auto record = (__log__).open_record()) \ if (blackhole::aux::syntax_check(__VA_ARGS__)) \ blackhole::aux::logger::make_pusher((__log__), record, __VA_ARGS__) #define BENCHMARK_BASELINE_X(...) void TT_CONCATENATE(f, __LINE__)() #define BENCHMARK_RELATIVE_X(...) void TT_CONCATENATE(f, __LINE__)() namespace { enum level_t { debug, info }; } #define MESSAGE_LONG "Something bad is going on but I can handle it" static const std::string FORMAT_BASE = "[%(timestamp)s]: %(message)s"; static const std::string FORMAT_VERBOSE = "[%(timestamp)s] [%(severity)s]: %(message)s"; BENCHMARK(LogStringToNull, Baseline) { static auto log = initialize< blackhole::verbose_logger_t<level_t>, blackhole::formatter::string_t, blackhole::sink::null_t >().formatter(FORMAT_VERBOSE).sink().log(level_t::debug).get(); BH_LOG(log, level_t::info, MESSAGE_LONG)( "id", 42, "info", "le string" ); } BENCHMARK_BASELINE(Logger, Base) { static auto log = initialize< blackhole::logger_base_t, blackhole::formatter::string_t, blackhole::sink::null_t >().formatter(FORMAT_BASE).sink().log().get(); BH_BASE_LOG(log, MESSAGE_LONG)( "id", 42, "info", "le string" ); } BENCHMARK(Logger, Verbose) { static auto log = initialize< blackhole::verbose_logger_t<level_t>, blackhole::formatter::string_t, blackhole::sink::null_t >().formatter(FORMAT_VERBOSE).sink().log(level_t::debug).get(); BH_LOG(log, level_t::info, MESSAGE_LONG)( "id", 42, "info", "le string" ); } BENCHMARK_BASELINE_X(Limits, Practical) { static const char MESSAGE[] = "[1412592701.561182] [0]: Something bad is going on but I can handle it"; std::cout << MESSAGE << std::endl; } BENCHMARK_RELATIVE_X(Limits, Experimental) { static auto log = initialize< blackhole::verbose_logger_t<level_t>, blackhole::formatter::string_t, blackhole::sink::stream_t >() .formatter(FORMAT_VERBOSE) .sink(blackhole::sink::stream_t::output_t::stdout) .log(level_t::debug) .get(); BH_LOG(log, level_t::info, MESSAGE_LONG); } BENCHMARK_BASELINE(Filtering, Rejected) { static auto log = initialize< blackhole::verbose_logger_t<level_t>, blackhole::formatter::string_t, blackhole::sink::null_t >() .formatter(FORMAT_BASE) .sink() .log(level_t::debug) .mod(std::bind(&filter_by::verbosity<level_t>, std::placeholders::_1, level_t::info)) .get(); BH_LOG(log, level_t::debug, MESSAGE_LONG)( "id", 42, "info", "le string" ); } BENCHMARK(Filtering, Accepted) { static auto log = initialize< blackhole::verbose_logger_t<level_t>, blackhole::formatter::string_t, blackhole::sink::null_t >() .formatter(FORMAT_BASE) .sink() .log(level_t::debug) .mod(std::bind(&filter_by::verbosity<level_t>, std::placeholders::_1, level_t::info)) .get(); BH_LOG(log, level_t::info, MESSAGE_LONG)( "id", 42, "info", "le string" ); }
mit
joansmith/ontrack
ontrack-extension-api/src/main/java/net/ontrack/extension/api/Extension.java
1030
package net.ontrack.extension.api; import net.ontrack.extension.api.action.ActionExtension; import net.ontrack.extension.api.action.EntityActionExtension; import net.ontrack.extension.api.action.TopActionExtension; import net.ontrack.extension.api.configuration.ConfigurationExtension; import net.ontrack.extension.api.decorator.EntityDecorator; import net.ontrack.extension.api.property.PropertyExtensionDescriptor; import java.util.Collection; import java.util.List; public interface Extension { String getName(); Collection<String> getDependencies(); List<? extends PropertyExtensionDescriptor> getPropertyExtensionDescriptors(); List<? extends ConfigurationExtension> getConfigurationExtensions(); Collection<? extends TopActionExtension> getTopLevelActions(); Collection<? extends ActionExtension> getDiffActions(); Collection<? extends EntityActionExtension> getEntityActions(); Collection<? extends EntityDecorator> getDecorators(); String getExtensionStyle(String scope); }
mit
lashus/ivory-google-map
tests/Helper/Functional/Overlay/MarkerClustererFunctionalTest.php
1901
<?php /* * This file is part of the Ivory Google Map package. * * (c) Eric GELOEN <[email protected]> * * For the full copyright and license information, please read the LICENSE * file that was distributed with this source code. */ namespace Ivory\Tests\GoogleMap\Helper\Functional\Overlay; use Ivory\GoogleMap\Base\Coordinate; use Ivory\GoogleMap\Map; use Ivory\GoogleMap\Overlay\Marker; use Ivory\GoogleMap\Overlay\MarkerClusterType; use Ivory\Tests\GoogleMap\Helper\Functional\AbstractMapFunctionalTest; /** * @author GeLo <[email protected]> * * @group functional */ class MarkerClustererFunctionalTest extends AbstractMapFunctionalTest { public function testRender() { $map = new Map(); $map->getOverlayManager()->getMarkerCluster()->setType(MarkerClusterType::MARKER_CLUSTERER); $map->getOverlayManager()->addMarker($this->createMarker()); $map->getOverlayManager()->addMarker($this->createMarker(new Coordinate(1, 1))); $map->getOverlayManager()->addMarker($this->createMarker(new Coordinate(2, 2))); $this->renderMap($map); $this->assertMap($map); } public function testRenderWithAutoZoom() { $map = new Map(); $map->setAutoZoom(true); $map->getOverlayManager()->getMarkerCluster()->setType(MarkerClusterType::MARKER_CLUSTERER); $map->getOverlayManager()->addMarker($this->createMarker()); $map->getOverlayManager()->addMarker($this->createMarker(new Coordinate(1, 1))); $map->getOverlayManager()->addMarker($this->createMarker(new Coordinate(2, 2))); $this->renderMap($map); $this->assertMap($map); } /** * @param Coordinate|null $position * * @return Marker */ private function createMarker(Coordinate $position = null) { return new Marker($position ?: new Coordinate()); } }
mit
Anoncoin/anoncoin
src/zerocoin/ParamGeneration.h
2865
/// \file ParamGeneration.h /// /// \brief Parameter generation routines for Zerocoin. /// /// \author Ian Miers, Christina Garman and Matthew Green /// \date June 2013 /// /// \copyright Copyright 2013 Ian Miers, Christina Garman and Matthew Green /// \license This project is released under the MIT license. #ifndef PARAMGENERATION_H_ #define PARAMGENERATION_H_ namespace libzerocoin { void CalculateParams(Params &params, Bignum N, std::string aux, uint32_t securityLevel); void calculateGroupParamLengths(uint32_t maxPLen, uint32_t securityLevel, uint32_t *pLen, uint32_t *qLen); // Constants #define STRING_COMMIT_GROUP "COIN_COMMITMENT_GROUP" #define STRING_AVC_GROUP "ACCUMULATED_VALUE_COMMITMENT_GROUP" #define STRING_AVC_ORDER "ACCUMULATED_VALUE_COMMITMENT_ORDER" #define STRING_AIC_GROUP "ACCUMULATOR_INTERNAL_COMMITMENT_GROUP" #define STRING_QRNCOMMIT_GROUPG "ACCUMULATOR_QRN_COMMITMENT_GROUPG" #define STRING_QRNCOMMIT_GROUPH "ACCUMULATOR_QRN_COMMITMENT_GROUPH" #define ACCUMULATOR_BASE_CONSTANT 31 #define MAX_PRIMEGEN_ATTEMPTS 10000 #define MAX_ACCUMGEN_ATTEMPTS 10000 #define MAX_GENERATOR_ATTEMPTS 10000 #define NUM_SCHNORRGEN_ATTEMPTS 10000 // Prototypes bool primalityTestByTrialDivision(uint32_t candidate); uint256 calculateSeed(Bignum modulus, std::string auxString, uint32_t securityLevel, std::string groupName); uint256 calculateGeneratorSeed(uint256 seed, uint256 pSeed, uint256 qSeed, std::string label, uint32_t index, uint32_t count); uint256 calculateHash(uint256 input); IntegerGroupParams deriveIntegerGroupParams(uint256 seed, uint32_t pLen, uint32_t qLen); IntegerGroupParams deriveIntegerGroupFromOrder(Bignum &groupOrder); void calculateGroupModulusAndOrder(uint256 seed, uint32_t pLen, uint32_t qLen, Bignum *resultModulus, Bignum *resultGroupOrder, uint256 *resultPseed, uint256 *resultQseed); void deriveGeneratorsFromSerialNumber(Bignum serialNumber, Bignum modulus, Bignum groupOrder, Bignum& g_out, Bignum& h_out); // throws ZerocoinException Bignum calculateGroupGenerator(Bignum serialNumber, uint256 seed, uint256 pSeed, uint256 qSeed, Bignum modulus, Bignum groupOrder, uint32_t index); Bignum generateRandomPrime(uint32_t primeBitLen, uint256 in_seed, uint256 *out_seed, uint32_t *prime_gen_counter); Bignum generateIntegerFromSeed(uint32_t numBits, uint256 seed, uint32_t *numIterations); bool primalityTestByTrialDivision(uint32_t candidate); Bignum calculateRawUFO(uint32_t ufoIndex, uint32_t numBits); }/* namespace libzerocoin */ #endif /* PARAMGENERATION_H_ */
mit
Gigoteur/PX8
unicorn-android/sdl/src/SDL/src/render/opengl/SDL_render_gl.c
54667
/* Simple DirectMedia Layer Copyright (C) 1997-2017 Sam Lantinga <[email protected]> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "../../SDL_internal.h" #if SDL_VIDEO_RENDER_OGL && !SDL_RENDER_DISABLED #include "SDL_hints.h" #include "SDL_log.h" #include "SDL_assert.h" #include "SDL_opengl.h" #include "../SDL_sysrender.h" #include "SDL_shaders_gl.h" #ifdef __MACOSX__ #include <OpenGL/OpenGL.h> #endif /* To prevent unnecessary window recreation, * these should match the defaults selected in SDL_GL_ResetAttributes */ #define RENDERER_CONTEXT_MAJOR 2 #define RENDERER_CONTEXT_MINOR 1 /* OpenGL renderer implementation */ /* Details on optimizing the texture path on Mac OS X: http://developer.apple.com/library/mac/#documentation/GraphicsImaging/Conceptual/OpenGL-MacProgGuide/opengl_texturedata/opengl_texturedata.html */ /* Used to re-create the window with OpenGL capability */ extern int SDL_RecreateWindow(SDL_Window * window, Uint32 flags); static const float inv255f = 1.0f / 255.0f; static SDL_Renderer *GL_CreateRenderer(SDL_Window * window, Uint32 flags); static void GL_WindowEvent(SDL_Renderer * renderer, const SDL_WindowEvent *event); static int GL_GetOutputSize(SDL_Renderer * renderer, int *w, int *h); static int GL_CreateTexture(SDL_Renderer * renderer, SDL_Texture * texture); static int GL_UpdateTexture(SDL_Renderer * renderer, SDL_Texture * texture, const SDL_Rect * rect, const void *pixels, int pitch); static int GL_UpdateTextureYUV(SDL_Renderer * renderer, SDL_Texture * texture, const SDL_Rect * rect, const Uint8 *Yplane, int Ypitch, const Uint8 *Uplane, int Upitch, const Uint8 *Vplane, int Vpitch); static int GL_LockTexture(SDL_Renderer * renderer, SDL_Texture * texture, const SDL_Rect * rect, void **pixels, int *pitch); static void GL_UnlockTexture(SDL_Renderer * renderer, SDL_Texture * texture); static int GL_SetRenderTarget(SDL_Renderer * renderer, SDL_Texture * texture); static int GL_UpdateViewport(SDL_Renderer * renderer); static int GL_UpdateClipRect(SDL_Renderer * renderer); static int GL_RenderClear(SDL_Renderer * renderer); static int GL_RenderDrawPoints(SDL_Renderer * renderer, const SDL_FPoint * points, int count); static int GL_RenderDrawLines(SDL_Renderer * renderer, const SDL_FPoint * points, int count); static int GL_RenderFillRects(SDL_Renderer * renderer, const SDL_FRect * rects, int count); static int GL_RenderCopy(SDL_Renderer * renderer, SDL_Texture * texture, const SDL_Rect * srcrect, const SDL_FRect * dstrect); static int GL_RenderCopyEx(SDL_Renderer * renderer, SDL_Texture * texture, const SDL_Rect * srcrect, const SDL_FRect * dstrect, const double angle, const SDL_FPoint *center, const SDL_RendererFlip flip); static int GL_RenderReadPixels(SDL_Renderer * renderer, const SDL_Rect * rect, Uint32 pixel_format, void * pixels, int pitch); static void GL_RenderPresent(SDL_Renderer * renderer); static void GL_DestroyTexture(SDL_Renderer * renderer, SDL_Texture * texture); static void GL_DestroyRenderer(SDL_Renderer * renderer); static int GL_BindTexture (SDL_Renderer * renderer, SDL_Texture *texture, float *texw, float *texh); static int GL_UnbindTexture (SDL_Renderer * renderer, SDL_Texture *texture); SDL_RenderDriver GL_RenderDriver = { GL_CreateRenderer, { "opengl", (SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC | SDL_RENDERER_TARGETTEXTURE), 1, {SDL_PIXELFORMAT_ARGB8888}, 0, 0} }; typedef struct GL_FBOList GL_FBOList; struct GL_FBOList { Uint32 w, h; GLuint FBO; GL_FBOList *next; }; typedef struct { SDL_GLContext context; SDL_bool debug_enabled; SDL_bool GL_ARB_debug_output_supported; int errors; char **error_messages; GLDEBUGPROCARB next_error_callback; GLvoid *next_error_userparam; SDL_bool GL_ARB_texture_non_power_of_two_supported; SDL_bool GL_ARB_texture_rectangle_supported; struct { GL_Shader shader; Uint32 color; int blendMode; } current; SDL_bool GL_EXT_framebuffer_object_supported; GL_FBOList *framebuffers; /* OpenGL functions */ #define SDL_PROC(ret,func,params) ret (APIENTRY *func) params; #include "SDL_glfuncs.h" #undef SDL_PROC /* Multitexture support */ SDL_bool GL_ARB_multitexture_supported; PFNGLACTIVETEXTUREARBPROC glActiveTextureARB; GLint num_texture_units; PFNGLGENFRAMEBUFFERSEXTPROC glGenFramebuffersEXT; PFNGLDELETEFRAMEBUFFERSEXTPROC glDeleteFramebuffersEXT; PFNGLFRAMEBUFFERTEXTURE2DEXTPROC glFramebufferTexture2DEXT; PFNGLBINDFRAMEBUFFEREXTPROC glBindFramebufferEXT; PFNGLCHECKFRAMEBUFFERSTATUSEXTPROC glCheckFramebufferStatusEXT; /* Shader support */ GL_ShaderContext *shaders; } GL_RenderData; typedef struct { GLuint texture; GLenum type; GLfloat texw; GLfloat texh; GLenum format; GLenum formattype; void *pixels; int pitch; SDL_Rect locked_rect; /* YUV texture support */ SDL_bool yuv; SDL_bool nv12; GLuint utexture; GLuint vtexture; GL_FBOList *fbo; } GL_TextureData; SDL_FORCE_INLINE const char* GL_TranslateError (GLenum error) { #define GL_ERROR_TRANSLATE(e) case e: return #e; switch (error) { GL_ERROR_TRANSLATE(GL_INVALID_ENUM) GL_ERROR_TRANSLATE(GL_INVALID_VALUE) GL_ERROR_TRANSLATE(GL_INVALID_OPERATION) GL_ERROR_TRANSLATE(GL_OUT_OF_MEMORY) GL_ERROR_TRANSLATE(GL_NO_ERROR) GL_ERROR_TRANSLATE(GL_STACK_OVERFLOW) GL_ERROR_TRANSLATE(GL_STACK_UNDERFLOW) GL_ERROR_TRANSLATE(GL_TABLE_TOO_LARGE) default: return "UNKNOWN"; } #undef GL_ERROR_TRANSLATE } SDL_FORCE_INLINE void GL_ClearErrors(SDL_Renderer *renderer) { GL_RenderData *data = (GL_RenderData *) renderer->driverdata; if (!data->debug_enabled) { return; } if (data->GL_ARB_debug_output_supported) { if (data->errors) { int i; for (i = 0; i < data->errors; ++i) { SDL_free(data->error_messages[i]); } SDL_free(data->error_messages); data->errors = 0; data->error_messages = NULL; } } else { while (data->glGetError() != GL_NO_ERROR) { continue; } } } SDL_FORCE_INLINE int GL_CheckAllErrors (const char *prefix, SDL_Renderer *renderer, const char *file, int line, const char *function) { GL_RenderData *data = (GL_RenderData *) renderer->driverdata; int ret = 0; if (!data->debug_enabled) { return 0; } if (data->GL_ARB_debug_output_supported) { if (data->errors) { int i; for (i = 0; i < data->errors; ++i) { SDL_SetError("%s: %s (%d): %s %s", prefix, file, line, function, data->error_messages[i]); ret = -1; } GL_ClearErrors(renderer); } } else { /* check gl errors (can return multiple errors) */ for (;;) { GLenum error = data->glGetError(); if (error != GL_NO_ERROR) { if (prefix == NULL || prefix[0] == '\0') { prefix = "generic"; } SDL_SetError("%s: %s (%d): %s %s (0x%X)", prefix, file, line, function, GL_TranslateError(error), error); ret = -1; } else { break; } } } return ret; } #if 0 #define GL_CheckError(prefix, renderer) #elif defined(_MSC_VER) #define GL_CheckError(prefix, renderer) GL_CheckAllErrors(prefix, renderer, __FILE__, __LINE__, __FUNCTION__) #else #define GL_CheckError(prefix, renderer) GL_CheckAllErrors(prefix, renderer, __FILE__, __LINE__, __PRETTY_FUNCTION__) #endif static int GL_LoadFunctions(GL_RenderData * data) { #ifdef __SDL_NOGETPROCADDR__ #define SDL_PROC(ret,func,params) data->func=func; #else #define SDL_PROC(ret,func,params) \ do { \ data->func = SDL_GL_GetProcAddress(#func); \ if ( ! data->func ) { \ return SDL_SetError("Couldn't load GL function %s: %s", #func, SDL_GetError()); \ } \ } while ( 0 ); #endif /* __SDL_NOGETPROCADDR__ */ #include "SDL_glfuncs.h" #undef SDL_PROC return 0; } static SDL_GLContext SDL_CurrentContext = NULL; static int GL_ActivateRenderer(SDL_Renderer * renderer) { GL_RenderData *data = (GL_RenderData *) renderer->driverdata; if (SDL_CurrentContext != data->context || SDL_GL_GetCurrentContext() != data->context) { if (SDL_GL_MakeCurrent(renderer->window, data->context) < 0) { return -1; } SDL_CurrentContext = data->context; GL_UpdateViewport(renderer); } GL_ClearErrors(renderer); return 0; } /* This is called if we need to invalidate all of the SDL OpenGL state */ static void GL_ResetState(SDL_Renderer *renderer) { GL_RenderData *data = (GL_RenderData *) renderer->driverdata; if (SDL_GL_GetCurrentContext() == data->context) { GL_UpdateViewport(renderer); } else { GL_ActivateRenderer(renderer); } data->current.shader = SHADER_NONE; data->current.color = 0; data->current.blendMode = -1; data->glDisable(GL_DEPTH_TEST); data->glDisable(GL_CULL_FACE); /* This ended up causing video discrepancies between OpenGL and Direct3D */ /* data->glEnable(GL_LINE_SMOOTH); */ data->glMatrixMode(GL_MODELVIEW); data->glLoadIdentity(); GL_CheckError("", renderer); } static void APIENTRY GL_HandleDebugMessage(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const char *message, const void *userParam) { SDL_Renderer *renderer = (SDL_Renderer *) userParam; GL_RenderData *data = (GL_RenderData *) renderer->driverdata; if (type == GL_DEBUG_TYPE_ERROR_ARB) { /* Record this error */ int errors = data->errors + 1; char **error_messages = SDL_realloc(data->error_messages, errors * sizeof(*data->error_messages)); if (error_messages) { data->errors = errors; data->error_messages = error_messages; data->error_messages[data->errors-1] = SDL_strdup(message); } } /* If there's another error callback, pass it along, otherwise log it */ if (data->next_error_callback) { data->next_error_callback(source, type, id, severity, length, message, data->next_error_userparam); } else { if (type == GL_DEBUG_TYPE_ERROR_ARB) { SDL_LogError(SDL_LOG_CATEGORY_RENDER, "%s", message); } else { SDL_LogDebug(SDL_LOG_CATEGORY_RENDER, "%s", message); } } } static GL_FBOList * GL_GetFBO(GL_RenderData *data, Uint32 w, Uint32 h) { GL_FBOList *result = data->framebuffers; while (result && ((result->w != w) || (result->h != h))) { result = result->next; } if (!result) { result = SDL_malloc(sizeof(GL_FBOList)); if (result) { result->w = w; result->h = h; data->glGenFramebuffersEXT(1, &result->FBO); result->next = data->framebuffers; data->framebuffers = result; } } return result; } SDL_Renderer * GL_CreateRenderer(SDL_Window * window, Uint32 flags) { SDL_Renderer *renderer; GL_RenderData *data; GLint value; Uint32 window_flags; int profile_mask = 0, major = 0, minor = 0; SDL_bool changed_window = SDL_FALSE; SDL_GL_GetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, &profile_mask); SDL_GL_GetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, &major); SDL_GL_GetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, &minor); window_flags = SDL_GetWindowFlags(window); if (!(window_flags & SDL_WINDOW_OPENGL) || profile_mask == SDL_GL_CONTEXT_PROFILE_ES || major != RENDERER_CONTEXT_MAJOR || minor != RENDERER_CONTEXT_MINOR) { changed_window = SDL_TRUE; SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, 0); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, RENDERER_CONTEXT_MAJOR); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, RENDERER_CONTEXT_MINOR); if (SDL_RecreateWindow(window, window_flags | SDL_WINDOW_OPENGL) < 0) { goto error; } } renderer = (SDL_Renderer *) SDL_calloc(1, sizeof(*renderer)); if (!renderer) { SDL_OutOfMemory(); goto error; } data = (GL_RenderData *) SDL_calloc(1, sizeof(*data)); if (!data) { GL_DestroyRenderer(renderer); SDL_OutOfMemory(); goto error; } renderer->WindowEvent = GL_WindowEvent; renderer->GetOutputSize = GL_GetOutputSize; renderer->CreateTexture = GL_CreateTexture; renderer->UpdateTexture = GL_UpdateTexture; renderer->UpdateTextureYUV = GL_UpdateTextureYUV; renderer->LockTexture = GL_LockTexture; renderer->UnlockTexture = GL_UnlockTexture; renderer->SetRenderTarget = GL_SetRenderTarget; renderer->UpdateViewport = GL_UpdateViewport; renderer->UpdateClipRect = GL_UpdateClipRect; renderer->RenderClear = GL_RenderClear; renderer->RenderDrawPoints = GL_RenderDrawPoints; renderer->RenderDrawLines = GL_RenderDrawLines; renderer->RenderFillRects = GL_RenderFillRects; renderer->RenderCopy = GL_RenderCopy; renderer->RenderCopyEx = GL_RenderCopyEx; renderer->RenderReadPixels = GL_RenderReadPixels; renderer->RenderPresent = GL_RenderPresent; renderer->DestroyTexture = GL_DestroyTexture; renderer->DestroyRenderer = GL_DestroyRenderer; renderer->GL_BindTexture = GL_BindTexture; renderer->GL_UnbindTexture = GL_UnbindTexture; renderer->info = GL_RenderDriver.info; renderer->info.flags = SDL_RENDERER_ACCELERATED; renderer->driverdata = data; renderer->window = window; data->context = SDL_GL_CreateContext(window); if (!data->context) { GL_DestroyRenderer(renderer); goto error; } if (SDL_GL_MakeCurrent(window, data->context) < 0) { GL_DestroyRenderer(renderer); goto error; } if (GL_LoadFunctions(data) < 0) { GL_DestroyRenderer(renderer); goto error; } #ifdef __MACOSX__ /* Enable multi-threaded rendering */ /* Disabled until Ryan finishes his VBO/PBO code... CGLEnable(CGLGetCurrentContext(), kCGLCEMPEngine); */ #endif if (flags & SDL_RENDERER_PRESENTVSYNC) { SDL_GL_SetSwapInterval(1); } else { SDL_GL_SetSwapInterval(0); } if (SDL_GL_GetSwapInterval() > 0) { renderer->info.flags |= SDL_RENDERER_PRESENTVSYNC; } /* Check for debug output support */ if (SDL_GL_GetAttribute(SDL_GL_CONTEXT_FLAGS, &value) == 0 && (value & SDL_GL_CONTEXT_DEBUG_FLAG)) { data->debug_enabled = SDL_TRUE; } if (data->debug_enabled && SDL_GL_ExtensionSupported("GL_ARB_debug_output")) { PFNGLDEBUGMESSAGECALLBACKARBPROC glDebugMessageCallbackARBFunc = (PFNGLDEBUGMESSAGECALLBACKARBPROC) SDL_GL_GetProcAddress("glDebugMessageCallbackARB"); data->GL_ARB_debug_output_supported = SDL_TRUE; data->glGetPointerv(GL_DEBUG_CALLBACK_FUNCTION_ARB, (GLvoid **)(char *)&data->next_error_callback); data->glGetPointerv(GL_DEBUG_CALLBACK_USER_PARAM_ARB, &data->next_error_userparam); glDebugMessageCallbackARBFunc(GL_HandleDebugMessage, renderer); /* Make sure our callback is called when errors actually happen */ data->glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB); } if (SDL_GL_ExtensionSupported("GL_ARB_texture_non_power_of_two")) { data->GL_ARB_texture_non_power_of_two_supported = SDL_TRUE; } else if (SDL_GL_ExtensionSupported("GL_ARB_texture_rectangle") || SDL_GL_ExtensionSupported("GL_EXT_texture_rectangle")) { data->GL_ARB_texture_rectangle_supported = SDL_TRUE; } if (data->GL_ARB_texture_rectangle_supported) { data->glGetIntegerv(GL_MAX_RECTANGLE_TEXTURE_SIZE_ARB, &value); renderer->info.max_texture_width = value; renderer->info.max_texture_height = value; } else { data->glGetIntegerv(GL_MAX_TEXTURE_SIZE, &value); renderer->info.max_texture_width = value; renderer->info.max_texture_height = value; } /* Check for multitexture support */ if (SDL_GL_ExtensionSupported("GL_ARB_multitexture")) { data->glActiveTextureARB = (PFNGLACTIVETEXTUREARBPROC) SDL_GL_GetProcAddress("glActiveTextureARB"); if (data->glActiveTextureARB) { data->GL_ARB_multitexture_supported = SDL_TRUE; data->glGetIntegerv(GL_MAX_TEXTURE_UNITS_ARB, &data->num_texture_units); } } /* Check for shader support */ if (SDL_GetHintBoolean(SDL_HINT_RENDER_OPENGL_SHADERS, SDL_TRUE)) { data->shaders = GL_CreateShaderContext(); } SDL_LogInfo(SDL_LOG_CATEGORY_RENDER, "OpenGL shaders: %s", data->shaders ? "ENABLED" : "DISABLED"); /* We support YV12 textures using 3 textures and a shader */ if (data->shaders && data->num_texture_units >= 3) { renderer->info.texture_formats[renderer->info.num_texture_formats++] = SDL_PIXELFORMAT_YV12; renderer->info.texture_formats[renderer->info.num_texture_formats++] = SDL_PIXELFORMAT_IYUV; renderer->info.texture_formats[renderer->info.num_texture_formats++] = SDL_PIXELFORMAT_NV12; renderer->info.texture_formats[renderer->info.num_texture_formats++] = SDL_PIXELFORMAT_NV21; } #ifdef __MACOSX__ renderer->info.texture_formats[renderer->info.num_texture_formats++] = SDL_PIXELFORMAT_UYVY; #endif if (SDL_GL_ExtensionSupported("GL_EXT_framebuffer_object")) { data->GL_EXT_framebuffer_object_supported = SDL_TRUE; data->glGenFramebuffersEXT = (PFNGLGENFRAMEBUFFERSEXTPROC) SDL_GL_GetProcAddress("glGenFramebuffersEXT"); data->glDeleteFramebuffersEXT = (PFNGLDELETEFRAMEBUFFERSEXTPROC) SDL_GL_GetProcAddress("glDeleteFramebuffersEXT"); data->glFramebufferTexture2DEXT = (PFNGLFRAMEBUFFERTEXTURE2DEXTPROC) SDL_GL_GetProcAddress("glFramebufferTexture2DEXT"); data->glBindFramebufferEXT = (PFNGLBINDFRAMEBUFFEREXTPROC) SDL_GL_GetProcAddress("glBindFramebufferEXT"); data->glCheckFramebufferStatusEXT = (PFNGLCHECKFRAMEBUFFERSTATUSEXTPROC) SDL_GL_GetProcAddress("glCheckFramebufferStatusEXT"); renderer->info.flags |= SDL_RENDERER_TARGETTEXTURE; } data->framebuffers = NULL; /* Set up parameters for rendering */ GL_ResetState(renderer); return renderer; error: if (changed_window) { /* Uh oh, better try to put it back... */ SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, profile_mask); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, major); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, minor); SDL_RecreateWindow(window, window_flags); } return NULL; } static void GL_WindowEvent(SDL_Renderer * renderer, const SDL_WindowEvent *event) { if (event->event == SDL_WINDOWEVENT_SIZE_CHANGED || event->event == SDL_WINDOWEVENT_SHOWN || event->event == SDL_WINDOWEVENT_HIDDEN) { /* Rebind the context to the window area and update matrices */ SDL_CurrentContext = NULL; } } static int GL_GetOutputSize(SDL_Renderer * renderer, int *w, int *h) { SDL_GL_GetDrawableSize(renderer->window, w, h); return 0; } SDL_FORCE_INLINE int power_of_2(int input) { int value = 1; while (value < input) { value <<= 1; } return value; } SDL_FORCE_INLINE SDL_bool convert_format(GL_RenderData *renderdata, Uint32 pixel_format, GLint* internalFormat, GLenum* format, GLenum* type) { switch (pixel_format) { case SDL_PIXELFORMAT_ARGB8888: *internalFormat = GL_RGBA8; *format = GL_BGRA; *type = GL_UNSIGNED_INT_8_8_8_8_REV; break; case SDL_PIXELFORMAT_YV12: case SDL_PIXELFORMAT_IYUV: case SDL_PIXELFORMAT_NV12: case SDL_PIXELFORMAT_NV21: *internalFormat = GL_LUMINANCE; *format = GL_LUMINANCE; *type = GL_UNSIGNED_BYTE; break; #ifdef __MACOSX__ case SDL_PIXELFORMAT_UYVY: *internalFormat = GL_RGB8; *format = GL_YCBCR_422_APPLE; *type = GL_UNSIGNED_SHORT_8_8_APPLE; break; #endif default: return SDL_FALSE; } return SDL_TRUE; } static GLenum GetScaleQuality(void) { const char *hint = SDL_GetHint(SDL_HINT_RENDER_SCALE_QUALITY); if (!hint || *hint == '0' || SDL_strcasecmp(hint, "nearest") == 0) { return GL_NEAREST; } else { return GL_LINEAR; } } static int GL_CreateTexture(SDL_Renderer * renderer, SDL_Texture * texture) { GL_RenderData *renderdata = (GL_RenderData *) renderer->driverdata; GL_TextureData *data; GLint internalFormat; GLenum format, type; int texture_w, texture_h; GLenum scaleMode; GL_ActivateRenderer(renderer); if (texture->access == SDL_TEXTUREACCESS_TARGET && !renderdata->GL_EXT_framebuffer_object_supported) { return SDL_SetError("Render targets not supported by OpenGL"); } if (!convert_format(renderdata, texture->format, &internalFormat, &format, &type)) { return SDL_SetError("Texture format %s not supported by OpenGL", SDL_GetPixelFormatName(texture->format)); } data = (GL_TextureData *) SDL_calloc(1, sizeof(*data)); if (!data) { return SDL_OutOfMemory(); } if (texture->access == SDL_TEXTUREACCESS_STREAMING) { size_t size; data->pitch = texture->w * SDL_BYTESPERPIXEL(texture->format); size = texture->h * data->pitch; if (texture->format == SDL_PIXELFORMAT_YV12 || texture->format == SDL_PIXELFORMAT_IYUV) { /* Need to add size for the U and V planes */ size += (2 * (texture->h * data->pitch) / 4); } if (texture->format == SDL_PIXELFORMAT_NV12 || texture->format == SDL_PIXELFORMAT_NV21) { /* Need to add size for the U/V plane */ size += ((texture->h * data->pitch) / 2); } data->pixels = SDL_calloc(1, size); if (!data->pixels) { SDL_free(data); return SDL_OutOfMemory(); } } if (texture->access == SDL_TEXTUREACCESS_TARGET) { data->fbo = GL_GetFBO(renderdata, texture->w, texture->h); } else { data->fbo = NULL; } GL_CheckError("", renderer); renderdata->glGenTextures(1, &data->texture); if (GL_CheckError("glGenTextures()", renderer) < 0) { if (data->pixels) { SDL_free(data->pixels); } SDL_free(data); return -1; } texture->driverdata = data; if (renderdata->GL_ARB_texture_non_power_of_two_supported) { data->type = GL_TEXTURE_2D; texture_w = texture->w; texture_h = texture->h; data->texw = 1.0f; data->texh = 1.0f; } else if (renderdata->GL_ARB_texture_rectangle_supported) { data->type = GL_TEXTURE_RECTANGLE_ARB; texture_w = texture->w; texture_h = texture->h; data->texw = (GLfloat) texture_w; data->texh = (GLfloat) texture_h; } else { data->type = GL_TEXTURE_2D; texture_w = power_of_2(texture->w); texture_h = power_of_2(texture->h); data->texw = (GLfloat) (texture->w) / texture_w; data->texh = (GLfloat) texture->h / texture_h; } data->format = format; data->formattype = type; scaleMode = GetScaleQuality(); renderdata->glEnable(data->type); renderdata->glBindTexture(data->type, data->texture); renderdata->glTexParameteri(data->type, GL_TEXTURE_MIN_FILTER, scaleMode); renderdata->glTexParameteri(data->type, GL_TEXTURE_MAG_FILTER, scaleMode); /* According to the spec, CLAMP_TO_EDGE is the default for TEXTURE_RECTANGLE and setting it causes an INVALID_ENUM error in the latest NVidia drivers. */ if (data->type != GL_TEXTURE_RECTANGLE_ARB) { renderdata->glTexParameteri(data->type, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); renderdata->glTexParameteri(data->type, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); } #ifdef __MACOSX__ #ifndef GL_TEXTURE_STORAGE_HINT_APPLE #define GL_TEXTURE_STORAGE_HINT_APPLE 0x85BC #endif #ifndef STORAGE_CACHED_APPLE #define STORAGE_CACHED_APPLE 0x85BE #endif #ifndef STORAGE_SHARED_APPLE #define STORAGE_SHARED_APPLE 0x85BF #endif if (texture->access == SDL_TEXTUREACCESS_STREAMING) { renderdata->glTexParameteri(data->type, GL_TEXTURE_STORAGE_HINT_APPLE, GL_STORAGE_SHARED_APPLE); } else { renderdata->glTexParameteri(data->type, GL_TEXTURE_STORAGE_HINT_APPLE, GL_STORAGE_CACHED_APPLE); } if (texture->access == SDL_TEXTUREACCESS_STREAMING && texture->format == SDL_PIXELFORMAT_ARGB8888 && (texture->w % 8) == 0) { renderdata->glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE); renderdata->glPixelStorei(GL_UNPACK_ALIGNMENT, 1); renderdata->glPixelStorei(GL_UNPACK_ROW_LENGTH, (data->pitch / SDL_BYTESPERPIXEL(texture->format))); renderdata->glTexImage2D(data->type, 0, internalFormat, texture_w, texture_h, 0, format, type, data->pixels); renderdata->glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_FALSE); } else #endif { renderdata->glTexImage2D(data->type, 0, internalFormat, texture_w, texture_h, 0, format, type, NULL); } renderdata->glDisable(data->type); if (GL_CheckError("glTexImage2D()", renderer) < 0) { return -1; } if (texture->format == SDL_PIXELFORMAT_YV12 || texture->format == SDL_PIXELFORMAT_IYUV) { data->yuv = SDL_TRUE; renderdata->glGenTextures(1, &data->utexture); renderdata->glGenTextures(1, &data->vtexture); renderdata->glEnable(data->type); renderdata->glBindTexture(data->type, data->utexture); renderdata->glTexParameteri(data->type, GL_TEXTURE_MIN_FILTER, scaleMode); renderdata->glTexParameteri(data->type, GL_TEXTURE_MAG_FILTER, scaleMode); renderdata->glTexParameteri(data->type, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); renderdata->glTexParameteri(data->type, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); renderdata->glTexImage2D(data->type, 0, internalFormat, texture_w/2, texture_h/2, 0, format, type, NULL); renderdata->glBindTexture(data->type, data->vtexture); renderdata->glTexParameteri(data->type, GL_TEXTURE_MIN_FILTER, scaleMode); renderdata->glTexParameteri(data->type, GL_TEXTURE_MAG_FILTER, scaleMode); renderdata->glTexParameteri(data->type, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); renderdata->glTexParameteri(data->type, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); renderdata->glTexImage2D(data->type, 0, internalFormat, texture_w/2, texture_h/2, 0, format, type, NULL); renderdata->glDisable(data->type); } if (texture->format == SDL_PIXELFORMAT_NV12 || texture->format == SDL_PIXELFORMAT_NV21) { data->nv12 = SDL_TRUE; renderdata->glGenTextures(1, &data->utexture); renderdata->glEnable(data->type); renderdata->glBindTexture(data->type, data->utexture); renderdata->glTexParameteri(data->type, GL_TEXTURE_MIN_FILTER, scaleMode); renderdata->glTexParameteri(data->type, GL_TEXTURE_MAG_FILTER, scaleMode); renderdata->glTexParameteri(data->type, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); renderdata->glTexParameteri(data->type, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); renderdata->glTexImage2D(data->type, 0, GL_LUMINANCE_ALPHA, texture_w/2, texture_h/2, 0, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, NULL); renderdata->glDisable(data->type); } return GL_CheckError("", renderer); } static int GL_UpdateTexture(SDL_Renderer * renderer, SDL_Texture * texture, const SDL_Rect * rect, const void *pixels, int pitch) { GL_RenderData *renderdata = (GL_RenderData *) renderer->driverdata; GL_TextureData *data = (GL_TextureData *) texture->driverdata; const int texturebpp = SDL_BYTESPERPIXEL(texture->format); SDL_assert(texturebpp != 0); /* otherwise, division by zero later. */ GL_ActivateRenderer(renderer); renderdata->glEnable(data->type); renderdata->glBindTexture(data->type, data->texture); renderdata->glPixelStorei(GL_UNPACK_ALIGNMENT, 1); renderdata->glPixelStorei(GL_UNPACK_ROW_LENGTH, (pitch / texturebpp)); renderdata->glTexSubImage2D(data->type, 0, rect->x, rect->y, rect->w, rect->h, data->format, data->formattype, pixels); if (data->yuv) { renderdata->glPixelStorei(GL_UNPACK_ROW_LENGTH, (pitch / 2)); /* Skip to the correct offset into the next texture */ pixels = (const void*)((const Uint8*)pixels + rect->h * pitch); if (texture->format == SDL_PIXELFORMAT_YV12) { renderdata->glBindTexture(data->type, data->vtexture); } else { renderdata->glBindTexture(data->type, data->utexture); } renderdata->glTexSubImage2D(data->type, 0, rect->x/2, rect->y/2, rect->w/2, rect->h/2, data->format, data->formattype, pixels); /* Skip to the correct offset into the next texture */ pixels = (const void*)((const Uint8*)pixels + (rect->h * pitch)/4); if (texture->format == SDL_PIXELFORMAT_YV12) { renderdata->glBindTexture(data->type, data->utexture); } else { renderdata->glBindTexture(data->type, data->vtexture); } renderdata->glTexSubImage2D(data->type, 0, rect->x/2, rect->y/2, rect->w/2, rect->h/2, data->format, data->formattype, pixels); } if (data->nv12) { renderdata->glPixelStorei(GL_UNPACK_ROW_LENGTH, (pitch / 2)); /* Skip to the correct offset into the next texture */ pixels = (const void*)((const Uint8*)pixels + rect->h * pitch); renderdata->glBindTexture(data->type, data->utexture); renderdata->glTexSubImage2D(data->type, 0, rect->x/2, rect->y/2, rect->w/2, rect->h/2, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, pixels); } renderdata->glDisable(data->type); return GL_CheckError("glTexSubImage2D()", renderer); } static int GL_UpdateTextureYUV(SDL_Renderer * renderer, SDL_Texture * texture, const SDL_Rect * rect, const Uint8 *Yplane, int Ypitch, const Uint8 *Uplane, int Upitch, const Uint8 *Vplane, int Vpitch) { GL_RenderData *renderdata = (GL_RenderData *) renderer->driverdata; GL_TextureData *data = (GL_TextureData *) texture->driverdata; GL_ActivateRenderer(renderer); renderdata->glEnable(data->type); renderdata->glBindTexture(data->type, data->texture); renderdata->glPixelStorei(GL_UNPACK_ALIGNMENT, 1); renderdata->glPixelStorei(GL_UNPACK_ROW_LENGTH, Ypitch); renderdata->glTexSubImage2D(data->type, 0, rect->x, rect->y, rect->w, rect->h, data->format, data->formattype, Yplane); renderdata->glPixelStorei(GL_UNPACK_ROW_LENGTH, Upitch); renderdata->glBindTexture(data->type, data->utexture); renderdata->glTexSubImage2D(data->type, 0, rect->x/2, rect->y/2, rect->w/2, rect->h/2, data->format, data->formattype, Uplane); renderdata->glPixelStorei(GL_UNPACK_ROW_LENGTH, Vpitch); renderdata->glBindTexture(data->type, data->vtexture); renderdata->glTexSubImage2D(data->type, 0, rect->x/2, rect->y/2, rect->w/2, rect->h/2, data->format, data->formattype, Vplane); renderdata->glDisable(data->type); return GL_CheckError("glTexSubImage2D()", renderer); } static int GL_LockTexture(SDL_Renderer * renderer, SDL_Texture * texture, const SDL_Rect * rect, void **pixels, int *pitch) { GL_TextureData *data = (GL_TextureData *) texture->driverdata; data->locked_rect = *rect; *pixels = (void *) ((Uint8 *) data->pixels + rect->y * data->pitch + rect->x * SDL_BYTESPERPIXEL(texture->format)); *pitch = data->pitch; return 0; } static void GL_UnlockTexture(SDL_Renderer * renderer, SDL_Texture * texture) { GL_TextureData *data = (GL_TextureData *) texture->driverdata; const SDL_Rect *rect; void *pixels; rect = &data->locked_rect; pixels = (void *) ((Uint8 *) data->pixels + rect->y * data->pitch + rect->x * SDL_BYTESPERPIXEL(texture->format)); GL_UpdateTexture(renderer, texture, rect, pixels, data->pitch); } static int GL_SetRenderTarget(SDL_Renderer * renderer, SDL_Texture * texture) { GL_RenderData *data = (GL_RenderData *) renderer->driverdata; GL_TextureData *texturedata; GLenum status; GL_ActivateRenderer(renderer); if (!data->GL_EXT_framebuffer_object_supported) { return SDL_SetError("Render targets not supported by OpenGL"); } if (texture == NULL) { data->glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); return 0; } texturedata = (GL_TextureData *) texture->driverdata; data->glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, texturedata->fbo->FBO); /* TODO: check if texture pixel format allows this operation */ data->glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, texturedata->type, texturedata->texture, 0); /* Check FBO status */ status = data->glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT); if (status != GL_FRAMEBUFFER_COMPLETE_EXT) { return SDL_SetError("glFramebufferTexture2DEXT() failed"); } return 0; } static int GL_UpdateViewport(SDL_Renderer * renderer) { GL_RenderData *data = (GL_RenderData *) renderer->driverdata; if (SDL_CurrentContext != data->context) { /* We'll update the viewport after we rebind the context */ return 0; } if (renderer->target) { data->glViewport(renderer->viewport.x, renderer->viewport.y, renderer->viewport.w, renderer->viewport.h); } else { int w, h; SDL_GL_GetDrawableSize(renderer->window, &w, &h); data->glViewport(renderer->viewport.x, (h - renderer->viewport.y - renderer->viewport.h), renderer->viewport.w, renderer->viewport.h); } data->glMatrixMode(GL_PROJECTION); data->glLoadIdentity(); if (renderer->viewport.w && renderer->viewport.h) { if (renderer->target) { data->glOrtho((GLdouble) 0, (GLdouble) renderer->viewport.w, (GLdouble) 0, (GLdouble) renderer->viewport.h, 0.0, 1.0); } else { data->glOrtho((GLdouble) 0, (GLdouble) renderer->viewport.w, (GLdouble) renderer->viewport.h, (GLdouble) 0, 0.0, 1.0); } } data->glMatrixMode(GL_MODELVIEW); return GL_CheckError("", renderer); } static int GL_UpdateClipRect(SDL_Renderer * renderer) { GL_RenderData *data = (GL_RenderData *) renderer->driverdata; if (renderer->clipping_enabled) { const SDL_Rect *rect = &renderer->clip_rect; data->glEnable(GL_SCISSOR_TEST); if (renderer->target) { data->glScissor(renderer->viewport.x + rect->x, renderer->viewport.y + rect->y, rect->w, rect->h); } else { int w, h; SDL_GL_GetDrawableSize(renderer->window, &w, &h); data->glScissor(renderer->viewport.x + rect->x, h - renderer->viewport.y - rect->y - rect->h, rect->w, rect->h); } } else { data->glDisable(GL_SCISSOR_TEST); } return 0; } static void GL_SetShader(GL_RenderData * data, GL_Shader shader) { if (data->shaders && shader != data->current.shader) { GL_SelectShader(data->shaders, shader); data->current.shader = shader; } } static void GL_SetColor(GL_RenderData * data, Uint8 r, Uint8 g, Uint8 b, Uint8 a) { Uint32 color = ((a << 24) | (r << 16) | (g << 8) | b); if (color != data->current.color) { data->glColor4f((GLfloat) r * inv255f, (GLfloat) g * inv255f, (GLfloat) b * inv255f, (GLfloat) a * inv255f); data->current.color = color; } } static void GL_SetBlendMode(GL_RenderData * data, int blendMode) { if (blendMode != data->current.blendMode) { switch (blendMode) { case SDL_BLENDMODE_NONE: data->glDisable(GL_BLEND); break; case SDL_BLENDMODE_BLEND: data->glEnable(GL_BLEND); data->glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA); break; case SDL_BLENDMODE_ADD: data->glEnable(GL_BLEND); data->glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE, GL_ZERO, GL_ONE); break; case SDL_BLENDMODE_MOD: data->glEnable(GL_BLEND); data->glBlendFuncSeparate(GL_ZERO, GL_SRC_COLOR, GL_ZERO, GL_ONE); break; } data->current.blendMode = blendMode; } } static void GL_SetDrawingState(SDL_Renderer * renderer) { GL_RenderData *data = (GL_RenderData *) renderer->driverdata; GL_ActivateRenderer(renderer); GL_SetColor(data, renderer->r, renderer->g, renderer->b, renderer->a); GL_SetBlendMode(data, renderer->blendMode); GL_SetShader(data, SHADER_SOLID); } static int GL_RenderClear(SDL_Renderer * renderer) { GL_RenderData *data = (GL_RenderData *) renderer->driverdata; GL_ActivateRenderer(renderer); data->glClearColor((GLfloat) renderer->r * inv255f, (GLfloat) renderer->g * inv255f, (GLfloat) renderer->b * inv255f, (GLfloat) renderer->a * inv255f); if (renderer->clipping_enabled) { data->glDisable(GL_SCISSOR_TEST); } data->glClear(GL_COLOR_BUFFER_BIT); if (renderer->clipping_enabled) { data->glEnable(GL_SCISSOR_TEST); } return 0; } static int GL_RenderDrawPoints(SDL_Renderer * renderer, const SDL_FPoint * points, int count) { GL_RenderData *data = (GL_RenderData *) renderer->driverdata; int i; GL_SetDrawingState(renderer); data->glBegin(GL_POINTS); for (i = 0; i < count; ++i) { data->glVertex2f(0.5f + points[i].x, 0.5f + points[i].y); } data->glEnd(); return 0; } static int GL_RenderDrawLines(SDL_Renderer * renderer, const SDL_FPoint * points, int count) { GL_RenderData *data = (GL_RenderData *) renderer->driverdata; int i; GL_SetDrawingState(renderer); if (count > 2 && points[0].x == points[count-1].x && points[0].y == points[count-1].y) { data->glBegin(GL_LINE_LOOP); /* GL_LINE_LOOP takes care of the final segment */ --count; for (i = 0; i < count; ++i) { data->glVertex2f(0.5f + points[i].x, 0.5f + points[i].y); } data->glEnd(); } else { #if defined(__MACOSX__) || defined(__WIN32__) #else int x1, y1, x2, y2; #endif data->glBegin(GL_LINE_STRIP); for (i = 0; i < count; ++i) { data->glVertex2f(0.5f + points[i].x, 0.5f + points[i].y); } data->glEnd(); /* The line is half open, so we need one more point to complete it. * http://www.opengl.org/documentation/specs/version1.1/glspec1.1/node47.html * If we have to, we can use vertical line and horizontal line textures * for vertical and horizontal lines, and then create custom textures * for diagonal lines and software render those. It's terrible, but at * least it would be pixel perfect. */ data->glBegin(GL_POINTS); #if defined(__MACOSX__) || defined(__WIN32__) /* Mac OS X and Windows seem to always leave the last point open */ data->glVertex2f(0.5f + points[count-1].x, 0.5f + points[count-1].y); #else /* Linux seems to leave the right-most or bottom-most point open */ x1 = points[0].x; y1 = points[0].y; x2 = points[count-1].x; y2 = points[count-1].y; if (x1 > x2) { data->glVertex2f(0.5f + x1, 0.5f + y1); } else if (x2 > x1) { data->glVertex2f(0.5f + x2, 0.5f + y2); } if (y1 > y2) { data->glVertex2f(0.5f + x1, 0.5f + y1); } else if (y2 > y1) { data->glVertex2f(0.5f + x2, 0.5f + y2); } #endif data->glEnd(); } return GL_CheckError("", renderer); } static int GL_RenderFillRects(SDL_Renderer * renderer, const SDL_FRect * rects, int count) { GL_RenderData *data = (GL_RenderData *) renderer->driverdata; int i; GL_SetDrawingState(renderer); for (i = 0; i < count; ++i) { const SDL_FRect *rect = &rects[i]; data->glRectf(rect->x, rect->y, rect->x + rect->w, rect->y + rect->h); } return GL_CheckError("", renderer); } static int GL_SetupCopy(SDL_Renderer * renderer, SDL_Texture * texture) { GL_RenderData *data = (GL_RenderData *) renderer->driverdata; GL_TextureData *texturedata = (GL_TextureData *) texture->driverdata; data->glEnable(texturedata->type); if (texturedata->yuv) { data->glActiveTextureARB(GL_TEXTURE2_ARB); data->glBindTexture(texturedata->type, texturedata->vtexture); data->glActiveTextureARB(GL_TEXTURE1_ARB); data->glBindTexture(texturedata->type, texturedata->utexture); data->glActiveTextureARB(GL_TEXTURE0_ARB); } if (texturedata->nv12) { data->glActiveTextureARB(GL_TEXTURE1_ARB); data->glBindTexture(texturedata->type, texturedata->utexture); data->glActiveTextureARB(GL_TEXTURE0_ARB); } data->glBindTexture(texturedata->type, texturedata->texture); if (texture->modMode) { GL_SetColor(data, texture->r, texture->g, texture->b, texture->a); } else { GL_SetColor(data, 255, 255, 255, 255); } GL_SetBlendMode(data, texture->blendMode); if (texturedata->yuv) { GL_SetShader(data, SHADER_YUV); } else if (texturedata->nv12) { if (texture->format == SDL_PIXELFORMAT_NV12) { GL_SetShader(data, SHADER_NV12); } else { GL_SetShader(data, SHADER_NV21); } } else { GL_SetShader(data, SHADER_RGB); } return 0; } static int GL_RenderCopy(SDL_Renderer * renderer, SDL_Texture * texture, const SDL_Rect * srcrect, const SDL_FRect * dstrect) { GL_RenderData *data = (GL_RenderData *) renderer->driverdata; GL_TextureData *texturedata = (GL_TextureData *) texture->driverdata; GLfloat minx, miny, maxx, maxy; GLfloat minu, maxu, minv, maxv; GL_ActivateRenderer(renderer); if (GL_SetupCopy(renderer, texture) < 0) { return -1; } minx = dstrect->x; miny = dstrect->y; maxx = dstrect->x + dstrect->w; maxy = dstrect->y + dstrect->h; minu = (GLfloat) srcrect->x / texture->w; minu *= texturedata->texw; maxu = (GLfloat) (srcrect->x + srcrect->w) / texture->w; maxu *= texturedata->texw; minv = (GLfloat) srcrect->y / texture->h; minv *= texturedata->texh; maxv = (GLfloat) (srcrect->y + srcrect->h) / texture->h; maxv *= texturedata->texh; data->glBegin(GL_TRIANGLE_STRIP); data->glTexCoord2f(minu, minv); data->glVertex2f(minx, miny); data->glTexCoord2f(maxu, minv); data->glVertex2f(maxx, miny); data->glTexCoord2f(minu, maxv); data->glVertex2f(minx, maxy); data->glTexCoord2f(maxu, maxv); data->glVertex2f(maxx, maxy); data->glEnd(); data->glDisable(texturedata->type); return GL_CheckError("", renderer); } static int GL_RenderCopyEx(SDL_Renderer * renderer, SDL_Texture * texture, const SDL_Rect * srcrect, const SDL_FRect * dstrect, const double angle, const SDL_FPoint *center, const SDL_RendererFlip flip) { GL_RenderData *data = (GL_RenderData *) renderer->driverdata; GL_TextureData *texturedata = (GL_TextureData *) texture->driverdata; GLfloat minx, miny, maxx, maxy; GLfloat centerx, centery; GLfloat minu, maxu, minv, maxv; GL_ActivateRenderer(renderer); if (GL_SetupCopy(renderer, texture) < 0) { return -1; } centerx = center->x; centery = center->y; if (flip & SDL_FLIP_HORIZONTAL) { minx = dstrect->w - centerx; maxx = -centerx; } else { minx = -centerx; maxx = dstrect->w - centerx; } if (flip & SDL_FLIP_VERTICAL) { miny = dstrect->h - centery; maxy = -centery; } else { miny = -centery; maxy = dstrect->h - centery; } minu = (GLfloat) srcrect->x / texture->w; minu *= texturedata->texw; maxu = (GLfloat) (srcrect->x + srcrect->w) / texture->w; maxu *= texturedata->texw; minv = (GLfloat) srcrect->y / texture->h; minv *= texturedata->texh; maxv = (GLfloat) (srcrect->y + srcrect->h) / texture->h; maxv *= texturedata->texh; /* Translate to flip, rotate, translate to position */ data->glPushMatrix(); data->glTranslatef((GLfloat)dstrect->x + centerx, (GLfloat)dstrect->y + centery, (GLfloat)0.0); data->glRotated(angle, (GLdouble)0.0, (GLdouble)0.0, (GLdouble)1.0); data->glBegin(GL_TRIANGLE_STRIP); data->glTexCoord2f(minu, minv); data->glVertex2f(minx, miny); data->glTexCoord2f(maxu, minv); data->glVertex2f(maxx, miny); data->glTexCoord2f(minu, maxv); data->glVertex2f(minx, maxy); data->glTexCoord2f(maxu, maxv); data->glVertex2f(maxx, maxy); data->glEnd(); data->glPopMatrix(); data->glDisable(texturedata->type); return GL_CheckError("", renderer); } static int GL_RenderReadPixels(SDL_Renderer * renderer, const SDL_Rect * rect, Uint32 pixel_format, void * pixels, int pitch) { GL_RenderData *data = (GL_RenderData *) renderer->driverdata; Uint32 temp_format = renderer->target ? renderer->target->format : SDL_PIXELFORMAT_ARGB8888; void *temp_pixels; int temp_pitch; GLint internalFormat; GLenum format, type; Uint8 *src, *dst, *tmp; int w, h, length, rows; int status; GL_ActivateRenderer(renderer); if (!convert_format(data, temp_format, &internalFormat, &format, &type)) { return SDL_SetError("Texture format %s not supported by OpenGL", SDL_GetPixelFormatName(temp_format)); } if (!rect->w || !rect->h) { return 0; /* nothing to do. */ } temp_pitch = rect->w * SDL_BYTESPERPIXEL(temp_format); temp_pixels = SDL_malloc(rect->h * temp_pitch); if (!temp_pixels) { return SDL_OutOfMemory(); } SDL_GetRendererOutputSize(renderer, &w, &h); data->glPixelStorei(GL_PACK_ALIGNMENT, 1); data->glPixelStorei(GL_PACK_ROW_LENGTH, (temp_pitch / SDL_BYTESPERPIXEL(temp_format))); data->glReadPixels(rect->x, renderer->target ? rect->y : (h-rect->y)-rect->h, rect->w, rect->h, format, type, temp_pixels); if (GL_CheckError("glReadPixels()", renderer) < 0) { SDL_free(temp_pixels); return -1; } /* Flip the rows to be top-down if necessary */ if (!renderer->target) { length = rect->w * SDL_BYTESPERPIXEL(temp_format); src = (Uint8*)temp_pixels + (rect->h-1)*temp_pitch; dst = (Uint8*)temp_pixels; tmp = SDL_stack_alloc(Uint8, length); rows = rect->h / 2; while (rows--) { SDL_memcpy(tmp, dst, length); SDL_memcpy(dst, src, length); SDL_memcpy(src, tmp, length); dst += temp_pitch; src -= temp_pitch; } SDL_stack_free(tmp); } status = SDL_ConvertPixels(rect->w, rect->h, temp_format, temp_pixels, temp_pitch, pixel_format, pixels, pitch); SDL_free(temp_pixels); return status; } static void GL_RenderPresent(SDL_Renderer * renderer) { GL_ActivateRenderer(renderer); SDL_GL_SwapWindow(renderer->window); } static void GL_DestroyTexture(SDL_Renderer * renderer, SDL_Texture * texture) { GL_RenderData *renderdata = (GL_RenderData *) renderer->driverdata; GL_TextureData *data = (GL_TextureData *) texture->driverdata; GL_ActivateRenderer(renderer); if (!data) { return; } if (data->texture) { renderdata->glDeleteTextures(1, &data->texture); } if (data->yuv) { renderdata->glDeleteTextures(1, &data->utexture); renderdata->glDeleteTextures(1, &data->vtexture); } SDL_free(data->pixels); SDL_free(data); texture->driverdata = NULL; } static void GL_DestroyRenderer(SDL_Renderer * renderer) { GL_RenderData *data = (GL_RenderData *) renderer->driverdata; if (data) { if (data->context != NULL) { /* make sure we delete the right resources! */ GL_ActivateRenderer(renderer); } GL_ClearErrors(renderer); if (data->GL_ARB_debug_output_supported) { PFNGLDEBUGMESSAGECALLBACKARBPROC glDebugMessageCallbackARBFunc = (PFNGLDEBUGMESSAGECALLBACKARBPROC) SDL_GL_GetProcAddress("glDebugMessageCallbackARB"); /* Uh oh, we don't have a safe way of removing ourselves from the callback chain, if it changed after we set our callback. */ /* For now, just always replace the callback with the original one */ glDebugMessageCallbackARBFunc(data->next_error_callback, data->next_error_userparam); } if (data->shaders) { GL_DestroyShaderContext(data->shaders); } if (data->context) { while (data->framebuffers) { GL_FBOList *nextnode = data->framebuffers->next; /* delete the framebuffer object */ data->glDeleteFramebuffersEXT(1, &data->framebuffers->FBO); GL_CheckError("", renderer); SDL_free(data->framebuffers); data->framebuffers = nextnode; } SDL_GL_DeleteContext(data->context); } SDL_free(data); } SDL_free(renderer); } static int GL_BindTexture (SDL_Renderer * renderer, SDL_Texture *texture, float *texw, float *texh) { GL_RenderData *data = (GL_RenderData *) renderer->driverdata; GL_TextureData *texturedata = (GL_TextureData *) texture->driverdata; GL_ActivateRenderer(renderer); data->glEnable(texturedata->type); if (texturedata->yuv) { data->glActiveTextureARB(GL_TEXTURE2_ARB); data->glBindTexture(texturedata->type, texturedata->vtexture); data->glActiveTextureARB(GL_TEXTURE1_ARB); data->glBindTexture(texturedata->type, texturedata->utexture); data->glActiveTextureARB(GL_TEXTURE0_ARB); } data->glBindTexture(texturedata->type, texturedata->texture); if(texw) *texw = (float)texturedata->texw; if(texh) *texh = (float)texturedata->texh; return 0; } static int GL_UnbindTexture (SDL_Renderer * renderer, SDL_Texture *texture) { GL_RenderData *data = (GL_RenderData *) renderer->driverdata; GL_TextureData *texturedata = (GL_TextureData *) texture->driverdata; GL_ActivateRenderer(renderer); if (texturedata->yuv) { data->glActiveTextureARB(GL_TEXTURE2_ARB); data->glDisable(texturedata->type); data->glActiveTextureARB(GL_TEXTURE1_ARB); data->glDisable(texturedata->type); data->glActiveTextureARB(GL_TEXTURE0_ARB); } data->glDisable(texturedata->type); return 0; } #endif /* SDL_VIDEO_RENDER_OGL && !SDL_RENDER_DISABLED */ /* vi: set ts=4 sw=4 expandtab: */
mit
researchlab/golearning
news_spider/news_spider_list.go
4627
package main import ( "database/sql" "fmt" "github.com/PuerkitoBio/goquery" _ "github.com/go-sql-driver/mysql" "sync" "time" ) type NewsSpider struct { TargetUrl string TargetSource string MysqlDSN string InsertStmt string QueryStmt string Duration int } type Paper struct { Title string ImgAddr string Desc string Content string Author string Time string } var ( NewsSpiderList = []*NewsSpider{ &NewsSpider{ TargetUrl: "https://news.jin10.com", TargetSource: "金十数据", MysqlDSN: "root:123456@tcp(localhost:3306)/phdb?charset=utf8", InsertStmt: "INSERT INTO consult_info( consult_title, pic_addr, consult_desc, consult_content, consult_source, consult_author, create_date ) VALUES( ?, ?, ?, ?, ?, ?, ? )", QueryStmt: "SELECT IF(COUNT(*),'true','false') FROM consult_info WHERE consult_title = ?", Duration: 30, }, &NewsSpider{ TargetUrl: "https://news.jin10.com", TargetSource: "金十数据", MysqlDSN: "root:123456@tcp(localhost:3306)/phdb?charset=utf8", InsertStmt: "INSERT INTO consult_info( consult_title, pic_addr, consult_desc, consult_content, consult_source, consult_author, create_date ) VALUES( ?, ?, ?, ?, ?, ?, ? )", QueryStmt: "SELECT IF(COUNT(*),'true','false') FROM consult_info WHERE consult_title = ?", Duration: 5, }, } ) func main() { var wg sync.WaitGroup wg.Add(len(NewsSpiderList)) for _, ns := range NewsSpiderList { go ns.Run(&wg) } wg.Wait() } func (ns *NewsSpider) Run(wg *sync.WaitGroup) { defer wg.Done() ticker := time.NewTicker(time.Duration(ns.Duration) * time.Minute) ns.newsSpider() for range ticker.C { ns.newsSpider() } } // 新闻爬虫 func (ns *NewsSpider) newsSpider() { // mysql 初始化 db, err := sql.Open("mysql", ns.MysqlDSN) if nil != err { time.Sleep(time.Duration(1) * time.Minute) if db, err = sql.Open("mysql", ns.MysqlDSN); nil != err { panic(err.Error()) } } defer db.Close() doc, err := goquery.NewDocument(ns.TargetUrl) if nil != err { return } paper := Paper{} // 遍历类节点 doc.Find(".jin-newsList__item").Each(func(i int, s *goquery.Selection) { // 文章封面 a_img := s.Find(".J_lazyImg").Eq(0) if nil == a_img { return } img, _ := a_img.Attr("data-original") // 文章链接 a_href := s.Find("a").Eq(0) if nil == a_href { return } // 抓取详情 article_id, _ := a_href.Attr("href") article_href := fmt.Sprintf("%s%s", ns.TargetUrl, article_id) // 获取详情的dom dom, err := goquery.NewDocument(article_href) if nil != err { return } // 设定来源 //source := "金十数据" // 观看次数 // hit := dom.Find(".jin-meta p").Eq(0).Text() // 评论数 // msg := dom.Find(".jin-meta p").Eq(1).Text() // paper := Paper{ // Title: dom.Find(".jin-news-article_title").Text(), // 新闻标题 // ImgAddr: img, // Desc: dom.Find(".jin-news-article_description").Text(), // 文章描述 // Content: dom.Find(".jin-news-article_content").Text(), // 文章内容 // Author: dom.Find(".jin-meta p").Eq(3).Text(), // Time: dom.Find(".jin-meta p").Eq(2).Text() + " " + s.Find(".jin-newsList__time").Text(), // 发布日期 // } paper.Title = dom.Find(".jin-news-article_title").Text() // 新闻标题 paper.ImgAddr = img paper.Desc = dom.Find(".jin-news-article_description").Text() // 文章描述 paper.Content = dom.Find(".jin-news-article_content").Text() // 文章内容 paper.Author = dom.Find(".jin-meta p").Eq(3).Text() paper.Time = dom.Find(".jin-meta p").Eq(2).Text() + " " + s.Find(".jin-newsList__time").Text() // 发布日期 // mysql 查询 if isExist, err := ns.fetchRow(db, paper.Title); nil == err && !isExist { ns.insert(db, paper.Title, paper.ImgAddr, paper.Desc, paper.Content, ns.TargetSource, paper.Author, paper.Time) } }) } //插入 func (ns *NewsSpider) insert(db *sql.DB, args ...interface{}) (int64, error) { stmtIns, err := db.Prepare(ns.InsertStmt) if err != nil { return 0, err } defer stmtIns.Close() result, err := stmtIns.Exec(args...) if err != nil { return 0, err } return result.LastInsertId() } //取一行数据, func (ns *NewsSpider) fetchRow(db *sql.DB, args ...interface{}) (isExist bool, err error) { stmtOut, err := db.Prepare(ns.QueryStmt) if err != nil { return } defer stmtOut.Close() err = stmtOut.QueryRow(args...).Scan(&isExist) return }
mit
Tuxity/loopback-connector-mongodb
example/model.js
2094
// Copyright IBM Corp. 2013,2016. All Rights Reserved. // Node module: loopback-connector-mongodb // This file is licensed under the MIT License. // License text available at https://opensource.org/licenses/MIT var g = require('strong-globalize')(); var DataSource = require('loopback-datasource-juggler').DataSource; var config = require('rc')('loopback', { dev: { mongodb: {}}}).dev.mongodb; var ds = new DataSource(require('../'), config); var Customer = ds.createModel('customer', { seq: { type: Number, id: true }, name: String, emails: [ { label: String, email: String }, ], age: Number }); Customer.destroyAll(function(err) { Customer.create({ seq: 1, name: 'John1', emails: [ { label: 'work', email: '[email protected]' }, { label: 'home', email: '[email protected]' }, ], age: 30, }, function(err, customer1) { console.log(customer1.toObject()); Customer.create({ seq: 2, name: 'John2', emails: [ { label: 'work', email: '[email protected]' }, { label: 'home', email: '[email protected]' }, ], age: 35, }, function(err, customer2) { Customer.find({ where: { 'emails.email': '[email protected]' }}, function(err, customers) { g.log('{{Customers}} matched by {{emails.email}} %s', customers); }); Customer.find({ where: { 'emails.0.label': 'work' }}, function(err, customers) { g.log('{{Customers}} matched by {{emails.0.label}} %s', customers); }); /* customer1.updateAttributes({name: 'John'}, function(err, result) { console.log(err, result); }); customer1.delete(function(err, result) { customer1.updateAttributes({name: 'JohnX'}, function(err, result) { console.log(err, result); }); }); */ Customer.findById(customer1.seq, function(err, customer1) { console.log(customer1.toObject()); customer1.name = 'John'; customer1.save(function(err, customer1) { console.log(customer1.toObject()); ds.disconnect(); }); }); }); }); });
mit
g0v/laweasyread-data
rawdata/lawstat/version2/90089/9008932113000.html
12588
<html> <META HTTP-EQUIV=Content-Type Content="text/html; charset=big5"> <!-- Mirrored from lis.ly.gov.tw/lghtml/lawstat/version2/90089/9008932113000.htm by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 24 Mar 2013 09:27:42 GMT --> <head><title>ªk½s¸¹:90089 ª©¥»:032113000</title> <link rel="stylesheet" type="text/css" href="../../version.css" > </HEAD> <body><left> <table><tr><td><FONT COLOR=blue SIZE=5>¥D­p¤H­û¥ô¥Î±ø¨Ò(90089)</font> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td> <table><tr><td>&nbsp;&nbsp;&nbsp;</td> <tr><td align=left valign=top> <a href=9008925100200.html target=law90089><nobr><font size=2>¤¤µØ¥Á°ê 25 ¦~ 10 ¤ë 2 ¤é</font></nobr></a> </td> <td valign=top><font size=2>¨î©w20±ø</font></td> <tr><td align=left valign=top><nobr><font size=2>¤¤µØ¥Á°ê 25 ¦~ 10 ¤ë 30 ¤é¤½¥¬</font></nobr></td> <tr><td align=left valign=top> <a href=9008926022600.html target=law90089><nobr><font size=2>¤¤µØ¥Á°ê 26 ¦~ 2 ¤ë 26 ¤é</font></nobr></a> </td> <td valign=top><font size=2>­×¥¿²Ä5±ø</font></td> <tr><td align=left valign=top><nobr><font size=2>¤¤µØ¥Á°ê 26 ¦~ 3 ¤ë 9 ¤é¤½¥¬</font></nobr></td> <tr><td align=left valign=top> <a href=9008928042100.html target=law90089><nobr><font size=2>¤¤µØ¥Á°ê 28 ¦~ 4 ¤ë 21 ¤é</font></nobr></a> </td> <td valign=top><font size=2>­×¥¿¥þ¤å20±ø</font></td> <tr><td align=left valign=top><nobr><font size=2>¤¤µØ¥Á°ê 28 ¦~ 5 ¤ë 3 ¤é¤½¥¬</font></nobr></td> <tr><td align=left valign=top> <a href=9008929083000.html target=law90089><nobr><font size=2>¤¤µØ¥Á°ê 29 ¦~ 8 ¤ë 30 ¤é</font></nobr></a> </td> <td valign=top><font size=2>­×¥¿²Ä6, 7±ø</font></td> <tr><td align=left valign=top><nobr><font size=2>¤¤µØ¥Á°ê 29 ¦~ 9 ¤ë 19 ¤é¤½¥¬</font></nobr></td> <tr><td align=left valign=top> <a href=9008932113000.html target=law90089><nobr><font size=2>¤¤µØ¥Á°ê 32 ¦~ 11 ¤ë 30 ¤é</font></nobr></a> </td> <td valign=top><font size=2>­×¥¿¥þ¤å20±ø</font></td> <tr><td align=left valign=top><nobr><font size=2>¤¤µØ¥Á°ê 32 ¦~ 12 ¤ë 22 ¤é¤½¥¬</font></nobr></td> <tr><td align=left valign=top> <nobr><font size=2>¤¤µØ¥Á°ê 70 ¦~ 12 ¤ë 15 ¤é</font></nobr> </td> <td valign=top><font size=2>¼o¤î20±ø</font></td> <tr><td align=left valign=top><nobr><font size=2>¤¤µØ¥Á°ê 70 ¦~ 12 ¤ë 28 ¤é¤½¥¬</font></nobr></td> </table></table></table></table> <p><table><tr><td><font color=blue size=4>¥Á°ê32¦~11¤ë30¤é(«D²{¦æ±ø¤å)</font></td> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>²Ä¤@±ø</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td> ¡@¡@¥D­p¤H­û¤§¥ô¥Î°£ªk«ß¥t¦³³W©w¥~¡A¨Ì¥»±ø¨Ò¦æ¤§¡C<br> </td> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>²Ä¤G±ø</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td> ¡@¡@¥»±ø¨Ò©ÒºÙ¥D­p¤H­û¡A¿×¿ì²z·³­p·|­p©Î²Î­p¤§¥D­p©x¡B·|­p¤H­û¤Î²Î­p¤H­û¡C<br> </td> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>²Ä¤T±ø</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td> ¡@¡@¥D­p©x¡B·|­pªø¡B²Î­pªø¡B·|­p¥D¥ô¡B²Î­p¥D¥ô¡B·|­p­û¡B²Î­p­û¡A¬°¥D¿ì¤H­û¡C¾l¬°·³­p·|­p©Î²Î­p¦õ²z¤H­û¡C<br> </td> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>²Ä¥|±ø</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td> ¡@¡@¥D­p©xÀ³´N¨ã¦³¥ª¦C¦U´Ú¸ê®æ¤§¤@ªÌ¡A¦U«ö¨äÃö©ó·³­p·|­p²Î­p¤§¾Ç¾ú¸g¾ú¤À§O¥ô¥Î¤§¡G<br> ¡@¡@¤@¡B²{¥ô©Î´¿¥ô¥D­p©x¡A¸g»Í±Ô¦X®æªÌ¡C<br> ¡@¡@¤G¡B²{¥ô©Î´¿¥ô·|­pªø©Î²Î­pªø¤@¦~¥H¤W¡A¸g»Í±Ô¦X®æªÌ¡C<br> ¡@¡@¤T¡B¦b±Ð¨|³¡»{¥i¤§°ê¤º¥~¤j¾Ç©Î¿W¥ß¾Ç°|±M­×¥D­p¾Ç¬ì²¦·~¡A¨Ã¦b¦U©x¸p´¿¥ô»P²¥ô¾¬Û·í¤§·³­p·|­p©Î²Î­p¾°È¤­¦~¥H¤W¡AµÛ¦³¦¨ÁZªÌ¡C<br> ¡@¡@¥|¡B¦b±Ð¨|³¡»{¥i¤§°ê¤º¥~¤j¾Ç©Î¿W¥ß¾Ç°|±M­×¥D­p¾Ç¬ì²¦·~¡A¨Ã¦b¤½Àç¨Æ·~¾÷Ãö¥D¿ì»P²¥ô¾¬Û·í¤§·³­p·|­p©Î²Î­p¾°È¤­¦~¥H¤W¡AµÛ¦³¦¨ÁZªÌ¡C<br> ¡@¡@¤­¡B¦b±Ð¨|³¡»{¥i¤§°ê¤º¥~¤j¾Ç©Î¿W¥ß¾Ç°|¥R¥ô±M¥ô±Ð±ÂÁ¿±Â¥D­p¾Ç¬ì¤­¦~¥H¤W¡A¨Ã©ó¥D­p¾Ç³N¦³¯S®í¤§µÛ§@¸g¼f¬d¦X®æªÌ¡C<br> </td> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>²Ä¤­±ø</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td> ¡@¡@·|­pªø©Î²Î­pªøÀ³´N¨ã¦³¥ª¦C¦U´Ú¸ê®æ¤§¤@ªÌ¡A¦U«ö¨äÃö©ó·³­p·|­p²Î­p¤§¾Ç¾ú¸g¾ú¤À§O¥ô¥Î¤§¡G<br> ¡@¡@¤@¡B²{¥ô©Î´¿¥ô·|­pªø©Î²Î­pªø¸g»Í±Ô¦X®æªÌ¡C<br> ¡@¡@¤G¡B²{¥ô©Î´¿¥ô²¥ô¾¤§·³­p·|­p©Î²Î­p¾°È¤@¦~¥H¤W¡A¸g»Í±Ô¦X®æªÌ¡C<br> ¡@¡@¤T¡B²{¥ô©Î´¿¥ô³Ì°ª¯ÅÂË¥ô¾¤§·³­p·|­p©Î²Î­p¾°È¤T¦~¥H¤W¡A¸g»Í±Ô¦X®æªÌ¡C<br> ¡@¡@¥|¡B¦b±Ð¨|³¡»{¥i¤§°ê¤º¥~¤j¾Ç©Î¿W¥ß¾Ç°|±M­×¥D­p¾Ç¬ì²¦·~¨Ã¦b¦U©x¸p´¿¥ô»P²¥ô¾¬Û·í¤§·³­p·|­p©Î²Î­p¾°È¥|¦~¥H¤W¡AµÛ¦³¦¨ÁZªÌ¡C<br> ¡@¡@¤­¡B¦b±Ð¨|³¡»{¥i¤§°ê¤º¥~¤j¾Ç©Î¿W¥ß¾Ç°|±M­×¥D­p¾Ç¬ì²¦·~¡A¨Ã¦b¤½Àç¨Æ·~¾÷Ãö¥D¿ì»P²¥ô¾¬Û·í¤§·³­p·|­p©Î²Î­p¾°È¥|¦~¥H¤W¡AµÛ¦³¦¨ÁZªÌ¡C<br> ¡@¡@¤»¡B¦b±Ð¨|³¡»{¥i¤§°ê¤º¥~¤j¾Ç©Î¿W¥ß¾Ç°|¥R¥ô±M¥ô±Ð±ÂÁ¿±Â¥D­p¾Ç¬ì¥|¦~¥H¤W¡A¨Ã©ó¥D­p¾Ç³N¦³±MªùµÛ§@¡A¸g¼f¬d¦X®æªÌ¡C<br> </td> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>²Ä¤»±ø</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td> ¡@¡@ÂË¥ô¾·|­p¥D¥ô©Î²Î­p¥D¥ôÀ³´N¨ã¦³¥ª¦C¦U´Ú¸ê®æ¤§¤@ªÌ¡A¦U«ö¨äÃö©ó·³­p·|­p²Î­p¤§¾Ç¾ú¸g¾ú¤À§O¥ô¥Î¤§¡G<br> ¡@¡@¤@¡B¸g°ªµ¥¦Ò¸Õ·|­p²Î­p¼f­p©Î°]°È¦æ¬F¤H­û¦Ò¸Õ¤Î®æ¡A©Î»P°ªµ¥¦Ò¸Õ¬Û·í¤§¯SºØ¦Ò¸Õ·|­p²Î­p¼f­p©Î°]°È¦æ¬F¤H­û¦Ò¸Õ¤Î®æ¡A¨Ã¿ì²z©Î¹ê²ß·³­p·|­p©Î²Î­p¨Æ°È¤@¦~¥H¤W¦¨ÁZÀu¨}ªÌ¡C<br> ¡@¡@¤G¡B²{¥ô©Î´¿¥ôÂË¥ô¾¤§·|­p¥D¥ô©Î²Î­p¥D¥ô¸g»Í±Ô¦X®æªÌ¡C<br> ¡@¡@¤T¡B²{¥ô©Î´¿¥ôÂË¥ô¾¤§·³­p·|­p©Î²Î­p¾°È¤@¦~¥H¤W¸g»Í±Ô¦X®æªÌ¡C<br> ¡@¡@¥|¡B²{¥ô©Î´¿¥ô³Ì°ª¯Å©e¥ô¾¤§·³­p·|­p©Î²Î­p¾°È¤T¦~¥H¤W¡A¸g»Í±Ô¦X®æªÌ¡C<br> ¡@¡@¤­¡B¦b±Ð¨|³¡»{¥i¤§°ê¤º¥~±M¬ì¥H¤W¾Ç®Õ±M­×¥D­p¾Ç¬ì²¦·~¡A¨Ã¦b¦U©x¸p´¿¥ô»PÂË¥ô¾¬Û·í¤§·³­p·|­p©Î²Î­p¾°È¤T¦~¥H¤W¡AµÛ¦³¦¨ÁZªÌ¡C<br> ¡@¡@¤»¡B¦b±Ð¨|³¡»{¥i¤§°ê¤º¥~±M¬ì¥H¤W¾Ç®Õ±M­×¥D­p¾Ç¬ì²¦·~¡A¨Ã¦b¤½Àç¨Æ·~¾÷Ãö´¿¥ô»PÂË¥ô¾¬Û·í¤§·³­p·|­p©Î²Î­p¾°È¤T¦~¥H¤W¡AµÛ¦³¦¨ÁZªÌ¡C<br> ¡@¡@¤C¡B¦b±Ð¨|³¡»{¥i¤§°ê¤º¥~±M¬ì¥H¤W¾Ç®Õ±Ð±Â¥D­p¾Ç¬ì¤T¦~¥H¤W¡A¨Ã©ó¥D­p¾Ç³N¦³±MªùµÛ§@¸g¼f¬d¦X®æªÌ¡C<br> ¡@¡@¤K¡B»â¦³·|­p®vÃҮѨÃÄ~Äò°õ¦æ·|­p®v·~°È¤@¦~¥H¤W¡A¦¨ÁZÀu¨}¡A¸g¼f¬d¦X®æªÌ¡C<br> ¡@¡@ÂË¥ô¾·|­p²Î­p¦õ²z¤H­û¤§¥ô¥Î¸ê®æ¡A¾A¥Î«e¶µ¤§³W©w¡C<br> </td> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>²Ä¤C±ø</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td> ¡@¡@©e¥ô¾·|­p¥D¥ô²Î­p¥D¥ô©Î·|­p­û²Î­p­û¡AÀ³´N¨ã¦³¥ª¦C¦U´Ú¸ê®æ¤§¤@ªÌ¡A¦U«ö¨äÃö©ó·³­p·|­p²Î­p¤§¾Ç¾ú¸g¾ú¡A¤À§O¥ô¥Î¤§¡G<br> ¡@¡@¤@¡B¸g´¶³q¦Ò¸Õ·|­p²Î­p¼f­p©Î°]°È¦æ¬F¤H­û¦Ò¸Õ¤Î®æ¡A©Î»P´¶³q¦Ò¸Õ¬Û·í¤§¯SºØ¦Ò¸Õ·|­p²Î­p¼f­p©Î°]°È¦æ¬F¤H­û¦Ò¸Õ¤Î®æ¡A¨Ã¿ì²z©Î¹ê²ß·³­p·|­p©Î²Î­p¨Æ°È¤@¦~¥H¤WªÌ¡C<br> ¡@¡@¤G¡B²{¥ô©Î´¿¥ô©e¥ô¾·|­p¥D¥ô²Î­p¥D¥ô©Î·|­p­û²Î­p­û¡A¸g»Í±Ô¦X®æªÌ¡C<br> ¡@¡@¤T¡B²{¥ô©Î´¿¥ô©e¥ô¾¤§·³­p·|­p©Î²Î­p¾°È¤@¦~¥H¤W¡A¸g»Í±Ô¦X®æªÌ¡C<br> ¡@¡@¥|¡B¦b±Ð¨|³¡»{¥i¤§°ê¤º¥~±M¬ì¥H¤W¾Ç®Õ²¦·~¡A´¿­×¥D­p¾Ç¬ì¤§¤@ºØ¡A¨Ã¦b¦U©x¸p©Î¤½Àç¨Æ·~¾÷Ãö´¿¥ô»P©e¥ô¾¬Û·í¤§·³­p·|­p©Î²Î­p¾°È¤G¦~¥H¤WªÌ¡C<br> ¡@¡@¤­¡B¦b±Ð¨|³¡»{¥i¤§°ê¤º¥~±M¬ì¥H¤W¾Ç®Õ²¦·~¡A¸g¤¤¥¡©Î¬Ù¥«¬F©²¥D­p¾÷Ãö°V½m¦X®æ¡A¨Ã´¿¥ô·³­p·|­p©Î²Î­p¾°È¤G¦~¥H¤WªÌ¡C<br> ¡@¡@¤»¡B¦b±Ð¨|³¡»{¥i¤§°ê¤º¥~±M¬ì¥H¤W¾Ç®Õ±M­×·|­p©Î²Î­p²¦·~¡A¨Ã´¿¥ô©e¥ô¾¤§·³­p·|­p©Î²Î­p¾°È¤@¦~¥H¤WªÌ¡C<br> ¡@¡@¤C¡B¸g»Í±Ô¦X®æ¤§©e¥ô¾¤½°È­û¡A¸g­ìªA°È¾÷Ãö«O°e¦Ü¤¤¥¡©Î¬Ù¥«¬F©²¥D­p¾÷Ãö°V½m¦X®æªÌ¡C<br> ¡@¡@¤K¡B¦b¥DºÞ±Ð¨|¾÷Ãö»{¥i¤§°ª¯Å¾·~¾Ç®Õ°Ó¬ì²¦·~©Î°ª¯Å¤¤¾Ç²¦·~´¿­×¥D­p¾Ç¬ì¤G¦~¥H¤W¡A¨Ã¦b©x¸p©Î¤½Àç¨Æ·~¾÷Ãö¿ì²z·³­p·|­p©Î²Î­p¾°È¤T¦~¥H¤WªÌ¡C<br> ¡@¡@¤E¡B¦b¥DºÞ±Ð¨|¾÷Ãö»{¥i¤§°ª¯Å¤¤¾Ç²¦·~¡A´¿¨ü¥D­p¾÷Ãö»{¥i¤»­Ó¤ë¥H¤W¤§·|­p©Î²Î­p°V½m²¦·~¡A¨Ã¿ì²z·³­p·|­p©Î²Î­p¨Æ°È¤T¦~¥H¤WªÌ¡C<br> ¡@¡@¤Q¡B¦b¥DºÞ±Ð¨|¾÷Ãö»{¥i¤§°ª¯Å¤¤¾Ç¥H¤W¾Ç®ÕÁ¿±Â¥D­p¾Ç¬ì¤G¦~¥H¤WªÌ¡C<br> ¡@¡@¤Q¤@¡B»â¦³·|­p®vÃҮѪ̡C<br> </td> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>²Ä¤K±ø</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td> ¡@¡@©e¥ô¾·|­p²Î­p¦õ²z¤H­ûÀ³´N¨ã¦³¥ª¦C¦U´Ú¸ê®æ¤§¤@ªÌ¡A¦U«ö¨äÃö©ó·³­p·|­p²Î­p¤§¾Ç¾ú¸g¾ú¤À§O¥ô¥Î¤§¡G<br> ¡@¡@¤@¡B¸g´¶³q¦Ò¸Õ·|­p²Î­p¼f­p©Î°]°È¦æ¬F¤H­û¦Ò¸Õ¤Î®æ¡A©Î»P´¶³q¦Ò¸Õ¬Û·í¤§¯SºØ¦Ò¸Õ·|­p²Î­p¼f­p©Î°]°È¦æ¬F¤H­û¦Ò¸Õ¤Î®æªÌ¡C<br> ¡@¡@¤G¡B²{¥ô©Î´¿¥ô©e¥ô¾¤§·³­p·|­p©Î²Î­p¾°È¸g»Í±Ô¦X®æªÌ¡C<br> ¡@¡@¤T¡B¦b±Ð¨|³¡»{¥i¤§°ê¤º¥~±M¬ì¥H¤W¾Ç®Õ²¦·~´¿­×¥D­p¾Ç¬ì¤§¤@ºØªÌ¡C<br> ¡@¡@¥|¡B¦b±Ð¨|³¡»{¥i¤§°ê¤º¥~±M¬ì¥H¤W¾Ç®Õ±M­×·|­p©Î²Î­p²¦·~ªÌ¡C<br> ¡@¡@¤­¡B¦b¥DºÞ±Ð¨|¾÷Ãö»{¥i¤§°ª¯Å¾·~¾Ç®Õ°Ó¬ì²¦·~©Î°ª¯Å¤¤¾Ç²¦·~¡A´¿­×¥D­p¾Ç¬ì¤GºØ¥H¤W¨Ã¦b©x¸p©Î¤½Àç¨Æ·~¾÷Ãö¿ì²z·³­p·|­p©Î²Î­p¾°È¤@¦~¥H¤W¡A©Î¸g¤¤¥¡©Î¬Ù¥«¬F©²¥D­p¾÷Ãö°V½m¦X®æªÌ¡C<br> ¡@¡@¤»¡B¦b¥DºÞ±Ð¨|¾÷Ãö»{¥i¤§°ª¯Å¤¤¾Ç²¦·~¡A´¿¦b¥D­p¾÷Ãö©Î¦U¾÷Ãö¥D­p³¡¥÷¿ì²z·³­p·|­p©Î²Î­p¾°È¤G¦~¥H¤W¡A©Î¸g¤¤¥¡©Î¬Ù¥«¬F©²¥D­p¾÷Ãö°V½m¦X®æªÌ¡C<br> ¡@¡@¤C¡B¦b¥DºÞ±Ð¨|¾÷Ãö»{¥i¤§°ª¯Å¤¤¾Ç²¦·~¡A´¿¨ü¥D­p¾÷Ãö»{¥i¤»­Ó¤ë¥H¤W¤§·|­p©Î²Î­p°V½m²¦·~¡A¨Ã¿ì²z·³­p·|­p©Î²Î­p¨Æ°È¤@¦~¥H¤WªÌ¡C<br> ¡@¡@¤K¡B¦b¥DºÞ±Ð¨|¾÷Ãö»{¥i¤§¤¤µ¥¥H¤W¾Ç®ÕÁ¿±Â·|­p©Î²Î­p¤G¦~¥H¤WªÌ¡C<br> ¡@¡@¿¤¬F©²©ÒÄݦU¾÷Ãö·|­p­û¡B²Î­p­û¤§¸ê®æ±o¾A¥Î«e¶µ¤§³W©w¡C<br> </td> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>²Ä¤E±ø</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td> ¡@¡@¨ã¦³¥ª¦C¦U´Ú¸ê®æ¤§¤@ªÌ±o¥ô¬°§C¯Å©e¥ô¾·|­p²Î­p¦õ²z¤H­û¡G<br> ¡@¡@¤@¡B¦b¥DºÞ±Ð¨|¾÷Ãö»{¥i¤§°ª¯Å¤¤¾Ç²¦·~¨Ã´¿­×¥D­p¾Ç¬ì©Î´¿¨ü±Mªù¥D­p°V½m±o¦³ÃҮѪ̡C<br> ¡@¡@¤G¡B¦b¥DºÞ±Ð¨|¾÷Ãö»{¥i¤§°ª¯Å¾·~¾Ç®Õ°Ó¬ì²¦·~¡A¨Ã¿ì²z·³­p·|­p©Î²Î­p¨Æ°È¤»­Ó¤ë¥H¤WªÌ¡C<br> ¡@¡@¤T¡B¦b¥DºÞ±Ð¨|¾÷Ãö»{¥i¤§ªì¯Å¾·~¾Ç®Õ°Ó¬ì²¦·~¨Ã´¿¨ü¥D­p¾÷Ãö»{¥i¤»­Ó¤ë¥H¤W¤§·|­p©Î²Î­p°V½m²¦·~¡A¨Ã¿ì²z·³­p·|­p©Î²Î­p¨Æ°È¤@¦~¥H¤WªÌ¡C<br> ¡@¡@¥|¡B¦b¥DºÞ±Ð¨|¾÷Ãö»{¥i¤§¤¤µ¥¥H¤W¾Ç®ÕÁ¿±Â·|­p©Î²Î­p¤@¦~¥H¤WªÌ¡C<br> ¡@¡@¤­¡B²{¥R¦U¯Å¬F©²¥D­p¾÷Ãö©Î¦U¾÷Ãö¥D­p³¡¥÷¤§¶±­û¡AÄ~Äò¿ì²z·³­p·|­p©Î²Î­p¨Æ°È¤T¦~¥H¤W¡A¦¨ÁZÀu¨}¡A²{¤ä³Ì°ªÁ~ÃBªÌ¡C<br> </td> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>²Ä¤Q±ø</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td> ¡@¡@¥D­p³B·³­p§½¦õ²z¤H­û¤§¥ô¥Î¸ê®æ¡A¾A¥ÎÃö©ó·|­p¦õ²z¤H­û¤§³W©w¡C<br> </td> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>²Ä¤Q¤@±ø</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td> ¡@¡@²¥ô¾¥D­p¤H­û¤§¥ô¥Î¡A¥Ñ°ê¥Á¬F©²¥æ»Í±Ô³¡¼f¬d¦X®æ«á¥ô©R¤§¡CÂË¥ô¾¥D­p¤H­û¤§¥ô¥Î¡A¥Ñ°ê¥Á¬F©²¥D­p³B°e»Í±Ô³¡¼f¬d¦X®æ«á§eÂˤ§¡C<br> ¡@¡@¤¤¥¡¾÷Ãö¡B¦U¬Ù¬F©²¤Î°|ÁÒ¥«¬F©²¥D­p¾÷Ãö¤¤©e¥ô¾¥D­p¤H­û¤§¥ô¥Î¡A¥Ñ°ê¥Á¬F©²¥D­p³B°e»Í±Ô³¡¼f¬d¦X®æ«á©e¥ô¤§¡C<br> ¡@¡@¬Ù¥«¬F©²©ÒÄݦU¾÷Ãö¡B¬ÙÁÒ¥«¬F©²¿¤¬F©²¤Î¨ä©ÒÄݦU¾÷Ãö¤¤©e¥ô¾¥D­p¤H­û¤§¥ô¥Î¡A¥Ñ¦U¸Ó¬Ù¥«¬F©²¥D­p¾÷Ãö°e»Í±Ô¾÷Ãö¼f¬d¦X®æ«á¡A§e½Ð°ê¥Á¬F©²¥D­p³B©e¥ô¤§¡C<br> </td> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>²Ä¤Q¤G±ø</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td> ¡@¡@©e¥ô¾¥D­p¤H­û¤§Â¾°È¦³¤@©w´Á¶¡ªÌ¡A±o¥Ñ¦U¥DºÞ¾÷Ãö¤À§O³W©w¥ô¥Î´Á­­¨Ì«e±ø²Ä¤G¶µ²Ä¤T¶µ©Ò©wµ{§Ç©e¥ô¤§¡A´Áº¡¸Ñ¾¡A¨ÃÂà³ø»Í±Ô³¡³Æ®×¡C<br> </td> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>²Ä¤Q¤T±ø</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td> ¡@¡@©e¥ô¾¥D­p¤H­û¸g¨Ìªk¥ô¥Î«á¡A¦p½Õ¥ô¨ä¥L¾÷Ãö¤§¦P©xµ¥¥D­p¾°È®É¡A±o§K°e»Í±Ô¾÷Ãö¼f¬d¡A¦ý¤´À³³ø½Ð¬d®Öµn°O¡C<br> </td> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>²Ä¤Q¥|±ø</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td> ¡@¡@¤½Àç¨Æ·~¾÷Ãö¤Î¤¤µ¥¥H¤W¤½¥ß¾Ç®Õ¥D­p¤H­û¤§¥ô¥Î¡A¨ä¦WºÙµ¥¯Å»P²¥ôÂË¥ô©e¥ô¾¬Û·íªÌ¡A±o¾A¥Î²Ä¤­±ø¦Ü²Ä¤E±ø¤§³W©w¡C<br> </td> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>²Ä¤Q¤­±ø</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td> ¡@¡@¥D­p¤H­û¤§©xµ¥©x­Ä¡A°£ªk«ß¥t¦³³W©w¥~¡AÀ³¤À§O¤ñ·Ó©Ò¦b¬F©²©Î¾÷Ãö©Ò©w­Äµ¹¼Ð·Ç©w¤§¡C<br> </td> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>²Ä¤Q¤»±ø</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td> ¡@¡@¥D­p¤H­û°£ªk«ß¥t¦³³W©w¥~¡A«D¨üÃg§Ù³B¤À¦D¨Æ³B¤À©Î¸Tªv²£¤§«Å§i¡A¤£±o§K¾¡C<br> </td> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>²Ä¤Q¤C±ø</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td> ¡@¡@¦U¯Å¬F©²¥D­p¾÷Ãö©Î¦U¾÷Ãö¥D¿ì°ò¥»°ê¶Õ½Õ¬d¡A©Î¦U¶µ´¶¬d©â¬d¸Õ¬d¡AÁ{®É©Ò»Ý²Î­p½Õ¬d¤H­û¡A¨ä¥ô¥Î¸ê®æ±o©ó¦U¸Ó²Î­p¤è®×¤º©w¤§¡A¤£¨ü¥»±ø¨Ò¤§­­¨î¡C<br> </td> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>²Ä¤Q¤K±ø</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td> ¡@¡@¥»±ø¨Ò¥¼³W©w¨Æ¶µ¡A¾A¥Î¤½°È­û¥ô¥Îªk¤§³W©w¡C<br> </td> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>²Ä¤Q¤E±ø</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td> ¡@¡@¥»±ø¨Ò¬I¦æ²Ó«h¡A¥Ñ»Í±Ô³¡·|¦P°ê¥Á¬F©²¥D­p³B©w¤§¡C<br> </td> </table> </table> </table> <table><tr><td>&nbsp;&nbsp;&nbsp;</td><td><font color=8000ff>²Ä¤G¤Q±ø</font> </font> <table><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td> <td> ¡@¡@¥»±ø¨Ò¦Û¤½¥¬¤é¬I¦æ¡C<br> </td> </table> </table> </table> </left> </body> <!-- Mirrored from lis.ly.gov.tw/lghtml/lawstat/version2/90089/9008932113000.htm by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 24 Mar 2013 09:27:42 GMT --> </html>
mit
hcharts/highcharts4gwt
src/main/java/com/github/highcharts4gwt/model/array/api/ArrayNumber.java
357
package com.github.highcharts4gwt.model.array.api; public interface ArrayNumber { double get(int index); int length(); void push(double value); /** * Replacement for native set method * * @param index * @param value */ void setValue(int index, double value); void setLength(int newLength); }
mit
m4nolo/steering-all
src/dot/entities/dotheart.py
817
import src.dot.dotentity class DotHeart(src.dot.dotentity.DotEntity): def __init__(self): res = [ "assets/img/red-brick.png", "assets/img/black-brick.png" ] grid = [ [0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0], [0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0], [0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0], [0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0] ] src.dot.dotentity.DotEntity.__init__(self, grid, res) def setSmall(self): self.setDotScale(0.5) def setMedium(self): self.setDotScale(0.75) def setLarge(self): self.setDotScale(1)
mit
ArnavChawla/InteliChat
Carthage/Checkouts/swift-sdk/docs/swift-api/services/TextToSpeechV1/docsets/.docset/Contents/Resources/Documents/Enums/JSON.html
22216
<!DOCTYPE html> <html lang="en"> <head> <title>JSON Enumeration Reference</title> <link rel="stylesheet" type="text/css" href="../css/jazzy.css" /> <link rel="stylesheet" type="text/css" href="../css/highlight.css" /> <meta charset='utf-8'> <script src="../js/jquery.min.js" defer></script> <script src="../js/jazzy.js" defer></script> </head> <body> <a name="//apple_ref/swift/Enum/JSON" class="dashAnchor"></a> <a title="JSON Enumeration Reference"></a> <header> <div class="content-wrapper"> <p><a href="../index.html"> Docs</a></p> <p class="header-right"><a href="https://github.com/watson-developer-cloud/ios-sdk"><img src="../img/gh.png"/>View on GitHub</a></p> </div> </header> <div class="content-wrapper"> <p id="breadcrumbs"> <a href="../index.html"> Reference</a> <img id="carat" src="../img/carat.png" /> JSON Enumeration Reference </p> </div> <div class="content-wrapper"> <nav class="sidebar"> <ul class="nav-groups"> <li class="nav-group-name"> <a href="../Classes.html">Classes</a> <ul class="nav-group-tasks"> <li class="nav-group-task"> <a href="../Classes/TextToSpeech.html">TextToSpeech</a> </li> </ul> </li> <li class="nav-group-name"> <a href="../Enums.html">Enumerations</a> <ul class="nav-group-tasks"> <li class="nav-group-task"> <a href="../Enums/JSON.html">JSON</a> </li> <li class="nav-group-task"> <a href="../Enums/RestError.html">RestError</a> </li> </ul> </li> <li class="nav-group-name"> <a href="../Structs.html">Structures</a> <ul class="nav-group-tasks"> <li class="nav-group-task"> <a href="../Structs/CreateVoiceModel.html">CreateVoiceModel</a> </li> <li class="nav-group-task"> <a href="../Structs/CreateVoiceModel/Language.html">– Language</a> </li> <li class="nav-group-task"> <a href="../Structs.html#/s:14TextToSpeechV111JSONWrapperV">JSONWrapper</a> </li> <li class="nav-group-task"> <a href="../Structs/Pronunciation.html">Pronunciation</a> </li> <li class="nav-group-task"> <a href="../Structs/SupportedFeatures.html">SupportedFeatures</a> </li> <li class="nav-group-task"> <a href="../Structs/Text.html">Text</a> </li> <li class="nav-group-task"> <a href="../Structs/Translation.html">Translation</a> </li> <li class="nav-group-task"> <a href="../Structs/Translation/PartOfSpeech.html">– PartOfSpeech</a> </li> <li class="nav-group-task"> <a href="../Structs/UpdateVoiceModel.html">UpdateVoiceModel</a> </li> <li class="nav-group-task"> <a href="../Structs/Voice.html">Voice</a> </li> <li class="nav-group-task"> <a href="../Structs/VoiceModel.html">VoiceModel</a> </li> <li class="nav-group-task"> <a href="../Structs/VoiceModels.html">VoiceModels</a> </li> <li class="nav-group-task"> <a href="../Structs/Voices.html">Voices</a> </li> <li class="nav-group-task"> <a href="../Structs/Word.html">Word</a> </li> <li class="nav-group-task"> <a href="../Structs/Word/PartOfSpeech.html">– PartOfSpeech</a> </li> <li class="nav-group-task"> <a href="../Structs/Words.html">Words</a> </li> </ul> </li> </ul> </nav> <article class="main-content"> <section> <section class="section"> <h1>JSON</h1> <div class="declaration"> <div class="language"> <pre class="highlight swift"><code><span class="kd">public</span> <span class="kd">enum</span> <span class="kt">JSON</span> <span class="p">:</span> <span class="kt">Equatable</span><span class="p">,</span> <span class="kt">Codable</span></code></pre> </div> </div> <p>A JSON value (one of string, number, object, array, true, false, or null).</p> </section> <section class="section task-group-section"> <div class="task-group"> <ul> <li class="item"> <div> <code> <a name="/s:14TextToSpeechV14JSONO4nullA2CmF"></a> <a name="//apple_ref/swift/Element/null" class="dashAnchor"></a> <a class="token" href="#/s:14TextToSpeechV14JSONO4nullA2CmF">null</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>A null value.</p> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight swift"><code><span class="k">case</span> <span class="n">null</span></code></pre> </div> </div> </section> </div> </li> <li class="item"> <div> <code> <a name="/s:14TextToSpeechV14JSONO7booleanACSbcACmF"></a> <a name="//apple_ref/swift/Element/boolean" class="dashAnchor"></a> <a class="token" href="#/s:14TextToSpeechV14JSONO7booleanACSbcACmF">boolean</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>A boolean value.</p> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight swift"><code><span class="k">case</span> <span class="nf">boolean</span><span class="p">(</span><span class="kt">Bool</span><span class="p">)</span></code></pre> </div> </div> </section> </div> </li> <li class="item"> <div> <code> <a name="/s:14TextToSpeechV14JSONO6stringACSScACmF"></a> <a name="//apple_ref/swift/Element/string" class="dashAnchor"></a> <a class="token" href="#/s:14TextToSpeechV14JSONO6stringACSScACmF">string</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>A string value.</p> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight swift"><code><span class="k">case</span> <span class="nf">string</span><span class="p">(</span><span class="kt">String</span><span class="p">)</span></code></pre> </div> </div> </section> </div> </li> <li class="item"> <div> <code> <a name="/s:14TextToSpeechV14JSONO3intACSicACmF"></a> <a name="//apple_ref/swift/Element/int" class="dashAnchor"></a> <a class="token" href="#/s:14TextToSpeechV14JSONO3intACSicACmF">int</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>A number value, represented as an integer.</p> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight swift"><code><span class="k">case</span> <span class="nf">int</span><span class="p">(</span><span class="kt">Int</span><span class="p">)</span></code></pre> </div> </div> </section> </div> </li> <li class="item"> <div> <code> <a name="/s:14TextToSpeechV14JSONO6doubleACSdcACmF"></a> <a name="//apple_ref/swift/Element/double" class="dashAnchor"></a> <a class="token" href="#/s:14TextToSpeechV14JSONO6doubleACSdcACmF">double</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>A number value, represented as a double.</p> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight swift"><code><span class="k">case</span> <span class="nf">double</span><span class="p">(</span><span class="kt">Double</span><span class="p">)</span></code></pre> </div> </div> </section> </div> </li> <li class="item"> <div> <code> <a name="/s:14TextToSpeechV14JSONO5arrayACSayACGcACmF"></a> <a name="//apple_ref/swift/Element/array" class="dashAnchor"></a> <a class="token" href="#/s:14TextToSpeechV14JSONO5arrayACSayACGcACmF">array</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>An array value.</p> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight swift"><code><span class="k">case</span> <span class="nf">array</span><span class="p">([</span><span class="kt">JSON</span><span class="p">])</span></code></pre> </div> </div> </section> </div> </li> <li class="item"> <div> <code> <a name="/s:14TextToSpeechV14JSONO6objectACs10DictionaryVySSACGcACmF"></a> <a name="//apple_ref/swift/Element/object" class="dashAnchor"></a> <a class="token" href="#/s:14TextToSpeechV14JSONO6objectACs10DictionaryVySSACGcACmF">object</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>An object value.</p> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight swift"><code><span class="k">case</span> <span class="nf">object</span><span class="p">([</span><span class="kt">String</span> <span class="p">:</span> <span class="kt">JSON</span><span class="p">])</span></code></pre> </div> </div> </section> </div> </li> <li class="item"> <div> <code> <a name="/s:14TextToSpeechV14JSONOACs7Decoder_p4from_tKcfc"></a> <a name="//apple_ref/swift/Method/init(from:)" class="dashAnchor"></a> <a class="token" href="#/s:14TextToSpeechV14JSONOACs7Decoder_p4from_tKcfc">init(from:)</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>Decode a JSON value.</p> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight swift"><code><span class="kd">public</span> <span class="nf">init</span><span class="p">(</span><span class="n">from</span> <span class="nv">decoder</span><span class="p">:</span> <span class="kt">Decoder</span><span class="p">)</span> <span class="k">throws</span></code></pre> </div> </div> </section> </div> </li> <li class="item"> <div> <code> <a name="/s:14TextToSpeechV14JSONOACx4from_tKcs9EncodableRzlufc"></a> <a name="//apple_ref/swift/Method/init(from:)" class="dashAnchor"></a> <a class="token" href="#/s:14TextToSpeechV14JSONOACx4from_tKcs9EncodableRzlufc">init(from:)</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>Initialize a JSON value from an encodable type.</p> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight swift"><code><span class="kd">public</span> <span class="kd">init</span><span class="o">&lt;</span><span class="kt">T</span><span class="o">&gt;</span><span class="p">(</span><span class="n">from</span> <span class="nv">value</span><span class="p">:</span> <span class="kt">T</span><span class="p">)</span> <span class="k">throws</span> <span class="k">where</span> <span class="kt">T</span> <span class="p">:</span> <span class="kt">Encodable</span></code></pre> </div> </div> </section> </div> </li> <li class="item"> <div> <code> <a name="/s:14TextToSpeechV14JSONO7toValuexxmKs9DecodableRzlF"></a> <a name="//apple_ref/swift/Method/toValue(_:)" class="dashAnchor"></a> <a class="token" href="#/s:14TextToSpeechV14JSONO7toValuexxmKs9DecodableRzlF">toValue(_:)</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>Convert this JSON value to a decodable type.</p> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight swift"><code><span class="kd">public</span> <span class="kd">func</span> <span class="n">toValue</span><span class="o">&lt;</span><span class="kt">T</span><span class="o">&gt;</span><span class="p">(</span><span class="n">_</span> <span class="nv">type</span><span class="p">:</span> <span class="kt">T</span><span class="o">.</span><span class="k">Type</span><span class="p">)</span> <span class="k">throws</span> <span class="o">-&gt;</span> <span class="kt">T</span> <span class="k">where</span> <span class="kt">T</span> <span class="p">:</span> <span class="kt">Decodable</span></code></pre> </div> </div> </section> </div> </li> <li class="item"> <div> <code> <a name="/s:14TextToSpeechV14JSONO6encodeys7Encoder_p2to_tKF"></a> <a name="//apple_ref/swift/Method/encode(to:)" class="dashAnchor"></a> <a class="token" href="#/s:14TextToSpeechV14JSONO6encodeys7Encoder_p2to_tKF">encode(to:)</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>Encode a JSON value.</p> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight swift"><code><span class="kd">public</span> <span class="kd">func</span> <span class="nf">encode</span><span class="p">(</span><span class="n">to</span> <span class="nv">encoder</span><span class="p">:</span> <span class="kt">Encoder</span><span class="p">)</span> <span class="k">throws</span></code></pre> </div> </div> </section> </div> </li> <li class="item"> <div> <code> <a name="/s:14TextToSpeechV14JSONO2eeoiSbAC_ACtFZ"></a> <a name="//apple_ref/swift/Method/==(_:_:)" class="dashAnchor"></a> <a class="token" href="#/s:14TextToSpeechV14JSONO2eeoiSbAC_ACtFZ">==(_:_:)</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>Compare two JSON values for equality.</p> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight swift"><code><span class="kd">public</span> <span class="kd">static</span> <span class="kd">func</span> <span class="o">==</span> <span class="p">(</span><span class="nv">lhs</span><span class="p">:</span> <span class="kt">JSON</span><span class="p">,</span> <span class="nv">rhs</span><span class="p">:</span> <span class="kt">JSON</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="kt">Bool</span></code></pre> </div> </div> </section> </div> </li> </ul> </div> </section> </section> <section id="footer"> <p>&copy; 2018 <a class="link" href="" target="_blank" rel="external"></a>. All rights reserved. (Last updated: 2018-05-18)</p> <p>Generated by <a class="link" href="https://github.com/realm/jazzy" target="_blank" rel="external">jazzy ♪♫ v0.9.3</a>, a <a class="link" href="https://realm.io" target="_blank" rel="external">Realm</a> project.</p> </section> </article> </div> </body> </div> </html>
mit
illiteratelinds/OurTinerary1
app/models/photo.rb
314
class Photo < ActiveRecord::Base belongs_to :imageable, polymorphic: true has_many :comments, as: :commentable has_attached_file :image, :styles => { :medium => "300x300>", :thumb => "100x100>" }, :default_url => "default.jpg" validates_attachment_content_type :image, :content_type => /\Aimage\/.*\Z/ end
mit
shivtools/Sudo-Soldiers-Website
index.html
1581
<!DOCTYPE html> <html> <head> <title>Sudo Soldiers - University of Washington</title> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"> <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Open+Sans:300,400,700,800"> <link rel="stylesheet" href="public/css/bootstrap.min.css"> <link rel="stylesheet" href="public/css/style.css"> </head> <body> <div class="bg"></div> <div class="container"> <div class="jumbotron"> <h1 class="title">Sudo Soldiers</h1> <p class="lead msg">Learn. Build. Connect.</p> <p class="lead">Wednesdays 6 - 7.<br>SAV 164.</p> <div class="btn-group btn-group-lg"><a role="button" href="http://eepurl.com/Md0eX" class="btn btn-success custom">Mailing List</a><a role="button" href="https://www.facebook.com/groups/uwhackers/" class="btn btn-primary custom">FB Group</a><a role="button" href="http://sudosoldiers.github.io/" class="btn btn-info custom">Presentations</a></div> </div> <div class="us"> <p>Sudo Soldiers is a registered RSO at the University of Washington. We exist to cultivate a community of makers who express their creativity through technology. We help turn ideas into projects, to power your vision of tomorrow.</p> </div> <div class="footer container"> <p>Website by&nbsp;<a href="http://www.goel.im">Karan Goel. Image by&nbsp;</a><a href="http://www.flickr.com/photos/48126477@N05/7186476574/">Matthew Pearce</a></p> </div> </div> </body> </html>
mit
mnm1021/bdbm_drv_fine_grained
ftl/algo/abm.h
4420
/* The MIT License (MIT) Copyright (c) 2014-2015 CSAIL, MIT Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef _BLUEDBM_FTL_ABM_H #define _BLUEDBM_FTL_ABM_H #if defined (KERNEL_MODE) #include <linux/module.h> #include <linux/slab.h> #include <linux/list.h> #elif defined (USER_MODE) #include <stdio.h> #include <stdint.h> #else #error Invalid Platform (KERNEL_MODE or USER_MODE) #endif #include "bdbm_drv.h" #include "params.h" enum BDBM_ABM_SUBPAGE_STATUS { BABM_ABM_SUBPAGE_NOT_INVALID = 0, BDBM_ABM_SUBPAGE_INVALID, }; typedef uint8_t babm_abm_subpage_t; /* BDBM_ABM_PAGE_STATUS */ enum BDBM_ABM_BLK_STATUS { BDBM_ABM_BLK_FREE = 0, BDBM_ABM_BLK_FREE_PREPARE, BDBM_ABM_BLK_CLEAN, BDBM_ABM_BLK_DIRTY, BDBM_ABM_BLK_BAD, }; typedef struct { uint8_t status; /* ABM_BLK_STATUS */ uint64_t channel_no; uint64_t chip_no; uint64_t block_no; uint32_t erase_count; uint32_t nr_invalid_subpages; babm_abm_subpage_t* pst; /* a page status table; used when the FTL requires */ struct list_head list; /* for list */ } bdbm_abm_block_t; typedef struct { bdbm_device_params_t* np; bdbm_abm_block_t* blocks; struct list_head** list_head_free; struct list_head** list_head_clean; struct list_head** list_head_dirty; struct list_head** list_head_bad; /* # of blocks according to their types */ uint64_t nr_total_blks; uint64_t nr_free_blks; uint64_t nr_free_blks_prepared; uint64_t nr_clean_blks; uint64_t nr_dirty_blks; uint64_t nr_bad_blks; } bdbm_abm_info_t; bdbm_abm_info_t* bdbm_abm_create (bdbm_device_params_t* np, uint8_t use_pst); void bdbm_abm_destroy (bdbm_abm_info_t* bai); bdbm_abm_block_t* bdbm_abm_get_block (bdbm_abm_info_t* bai, uint64_t channel_no, uint64_t chip_no, uint64_t block_no); bdbm_abm_block_t* bdbm_abm_get_free_block_prepare (bdbm_abm_info_t* bai, uint64_t channel_no, uint64_t chip_no); void bdbm_abm_get_free_block_rollback (bdbm_abm_info_t* bai, bdbm_abm_block_t* blk); void bdbm_abm_get_free_block_commit (bdbm_abm_info_t* bai, bdbm_abm_block_t* blk); void bdbm_abm_erase_block (bdbm_abm_info_t* bai, uint64_t channel_no, uint64_t chip_no, uint64_t block_no, uint8_t is_bad); void bdbm_abm_invalidate_page (bdbm_abm_info_t* bai, uint64_t channel_no, uint64_t chip_no, uint64_t block_no, uint64_t page_no, uint64_t subpage_no); void bdbm_abm_set_to_dirty_block (bdbm_abm_info_t* bai, uint64_t channel_no, uint64_t chip_no, uint64_t block_no); static inline uint64_t bdbm_abm_get_nr_free_blocks (bdbm_abm_info_t* bai) { return bai->nr_free_blks; } static inline uint64_t bdbm_abm_get_nr_free_blocks_prepared (bdbm_abm_info_t* bai) { return bai->nr_free_blks_prepared; } static inline uint64_t bdbm_abm_get_nr_clean_blocks (bdbm_abm_info_t* bai) { return bai->nr_clean_blks; } static inline uint64_t bdbm_abm_get_nr_dirty_blocks (bdbm_abm_info_t* bai) { return bai->nr_dirty_blks; } static inline uint64_t bdbm_abm_get_nr_total_blocks (bdbm_abm_info_t* bai) { return bai->nr_total_blks; } uint32_t bdbm_abm_load (bdbm_abm_info_t* bai, const char* fn); uint32_t bdbm_abm_store (bdbm_abm_info_t* bai, const char* fn); #define bdbm_abm_list_for_each_dirty_block(pos, bai, channel_no, chip_no) \ list_for_each (pos, &(bai->list_head_dirty[channel_no][chip_no])) #define bdbm_abm_fetch_dirty_block(pos) \ list_entry (pos, bdbm_abm_block_t, list) /* (example:) * bdbm_abm_list_for_each_dirty_block (pos, p->bai, j, k) { b = bdbm_abm_fetch_dirty_block (pos); } */ #endif
mit
jimtyhurst/urbandev-etl
postgresql/scripts/sql/CREATE-TABLE-zillow_education.sql
2828
BEGIN; CREATE TEMP TABLE blkgrp_education AS SELECT gisjoin, '1990'::varchar AS year, E33001 + E33002 + E33003 + E33004 + E33005 + E33006 + E33007 AS total, E33001 + E33002 AS no_diploma, E33003 AS diploma, E33004 + E33005 AS some_college, E33006 AS bachelor, E33007 AS advanced FROM census_educational_attainment_1990_blkgrp UNION ALL SELECT gisjoin, '2000'::varchar, -- total HD1001 + HD1017 + HD1002 + HD1018 + HD1003 + HD1019 + HD1004 + HD1020 + HD1005 + HD1021 + HD1006 + HD1022 + HD1007 + HD1023 + HD1008 + HD1024 + HD1009 + HD1025 + HD1010 + HD1026 + HD1011 + HD1027 + HD1012 + HD1028 + HD1013 + HD1029 + HD1014 + HD1030 + HD1015 + HD1031 + HD1016 + HD1032, -- no diploma HD1001 + HD1017 + HD1002 + HD1018 + HD1003 + HD1019 + HD1004 + HD1020 + HD1005 + HD1021 + HD1006 + HD1022 + HD1007 + HD1023 + HD1008 + HD1024, -- highschool diploma HD1009 + HD1025, -- some college HD1010 + HD1026 + HD1011 + HD1027 + HD1012 + HD1028, -- bachelor HD1013 + HD1029, -- advanced degree HD1014 + HD1030 + HD1015 + HD1031 + HD1016 + HD1032 FROM census_educational_attainment_2000_blkgrp UNION ALL SELECT gisjoin, '2009'::varchar, -- total RM8E001, -- no diploma RM8E003 + RM8E020 + RM8E004 + RM8E021 + RM8E005 + RM8E022 + RM8E006 + RM8E023 + RM8E007 + RM8E024 + RM8E008 + RM8E025 + RM8E009 + RM8E026 + RM8E010 + RM8E027, -- diploma RM8E011 + RM8E028, RM8E012 + RM8E029 + RM8E013 + RM8E030 + -- some college RM8E014 + RM8E031, -- bachelor RM8E015 + RM8E032, -- advanced degree RM8E016 + RM8E033 + RM8E017 + RM8E034 + RM8E018 + RM8E035 FROM acs_educational_attainment_2005_2009_blkgrp UNION ALL SELECT gisjoin, '2014'::varchar AS year, -- total ABC4E001, -- no diploma ABC4E002 + ABC4E003 + ABC4E004 + ABC4E005 + ABC4E006 + ABC4E007 + ABC4E008 + ABC4E009 + ABC4E010 + ABC4E011 + ABC4E012 + ABC4E013 + ABC4E014 + ABC4E015 + ABC4E016, -- diploma ABC4E017 + ABC4E018, -- some college ABC4E019 + ABC4E020 + ABC4E021, -- bachelor ABC4E022, -- advanced degree ABC4E023 + ABC4E024 + ABC4E025 FROM acs_educational_attainment_2010_2014_blkgrp; CREATE TABLE zillow_education AS SELECT z.name, z.regionid, z.year, sum(z.intersect_pct * e.total) AS total, sum(z.intersect_pct * e.no_diploma) AS no_diploma, sum(z.intersect_pct * e.diploma) AS diploma, sum(z.intersect_pct * e.some_college) AS some_college, sum(z.intersect_pct * e.bachelor) AS bachelor, sum(z.intersect_pct * e.advanced) AS advanced FROM zillow_blkgrps AS z JOIN blkgrp_education AS e ON z.year = e.year AND z.gisjoin = e.gisjoin GROUP BY z.name, z.regionid, z.year ORDER BY name, year; COMMIT;
mit
asposecells/Aspose_Cells_Cloud
Examples/Java/SDK/src/main/java/com/aspose/cells/cloud/examples/workbook/ConvertWorkbookWithAdditionalSettings.java
1947
package com.aspose.cells.cloud.examples.workbook; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; import com.aspose.cells.api.CellsApi; import com.aspose.cells.cloud.examples.Configuration; import com.aspose.cells.cloud.examples.Utils; import com.aspose.cells.model.ResponseMessage; import com.aspose.storage.api.StorageApi; public class ConvertWorkbookWithAdditionalSettings { public static void main(String... args) throws IOException { // ExStart: convert-workbook-additional-settings try { // Instantiate Aspose Storage API SDK StorageApi storageApi = new StorageApi(Configuration.apiKey, Configuration.appSID, true); // Instantiate Aspose Words API SDK CellsApi cellsApi = new CellsApi(Configuration.apiKey, Configuration.appSID, true); Path inputFile = Utils.getPath(ConvertWorkbookWithAdditionalSettings.class, "Workbook1.xlsx"); Path outputFile = Utils.getPath(ConvertWorkbookWithAdditionalSettings.class, "Workbook1.pdf"); String format = "pdf"; String password = ""; String outPath = ""; String xml = "<PdfSaveOptions>" + "<SaveFormat>pdf</SaveFormat>" + "<FileName>" + inputFile.getFileName().toString() + "</FileName>" + "<ImageCompression>Jpeg</ImageCompression>" + "<JpegQuality>70</JpegQuality>" + "<TextCompression>Flate</TextCompression>" + "</PdfSaveOptions>"; ResponseMessage cr = cellsApi.PutConvertWorkBook(format, password, outPath, inputFile.toFile(), xml.getBytes("UTF-8")); Files.copy(cr.getInputStream(), outputFile, StandardCopyOption.REPLACE_EXISTING); } catch (Exception e) { e.printStackTrace(); } // ExEnd: convert-workbook-additional-settings } }
mit
pilotfish/pilotfish
plugins/recorder/test/qunit-recorder.js
1124
/* Tests for the Pilotfish recorder plugin */ QUnit.module('Pilotfish Plugin recorder'); QUnit.test('basic events', function () { // Fire two test events Pilotfish('recorder', 'test_event_1'); Pilotfish('recorder', 'test_event_2'); // Check the event log var eventLog = JSON.stringify(Pilotfish('eventLog')); QUnit.ok(eventLog.indexOf('test_event_1') > -1, "test_event_1 in eventLog"); QUnit.ok(eventLog.indexOf('test_event_2') > -1, "test_event_2 in eventLog"); // Check the session data var events = Pilotfish('session').events; QUnit.ok(typeof events, "string", "window.sessionStorage.PilotfishEvents exists"); var eventsFlat = JSON.stringify(events); QUnit.ok(eventsFlat.indexOf('test_event_1') > -1, "test_event_1 in session storage"); QUnit.ok(eventsFlat.indexOf('test_event_2') > -1, "test_event_2 in session storage"); var pageViews = Pilotfish('session').pageViews; QUnit.equal(typeof pageViews, "number", "typeof Pilotfish('session').pageViews"); // Set it in the html so casper can easily get to it jQuery("#pageViews").text(pageViews); });
mit
claycarpenter/node-sandbox
rx-sandbox/creating-apps-with-observables/webpack.config.js
355
module.exports = { entry: './main.js', output: { path: './', filename: 'index.js', }, devServer: { inline: true, port: 3333, }, module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, loader: 'babel', query: { presets: ['es2015', 'react'] } } ] } }
mit
manaphp/manaphp
ManaPHP/Cli/RunnerInterface.php
87
<?php namespace ManaPHP\Cli; interface RunnerInterface { public function run(); }
mit
vjrantal/HeavenFresh-AllJoyn-Example
org.alljoyn.Humidifier.Actions/ActionsServiceEventArgs.h
25527
//----------------------------------------------------------------------------- // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // // Tool: AllJoynCodeGenerator.exe // // This tool is located in the Windows 10 SDK and the Windows 10 AllJoyn // Visual Studio Extension in the Visual Studio Gallery. // // The generated code should be packaged in a Windows 10 C++/CX Runtime // Component which can be consumed in any UWP-supported language using // APIs that are available in Windows.Devices.AllJoyn. // // Using AllJoynCodeGenerator - Invoke the following command with a valid // Introspection XML file and a writable output directory: // AllJoynCodeGenerator -i <INPUT XML FILE> -o <OUTPUT DIRECTORY> // </auto-generated> //----------------------------------------------------------------------------- #pragma once namespace org { namespace alljoyn { namespace Humidifier { namespace Actions { // Methods public ref class ActionsSetPowerToOffCalledEventArgs sealed { public: ActionsSetPowerToOffCalledEventArgs(_In_ Windows::Devices::AllJoyn::AllJoynMessageInfo^ info); property Windows::Devices::AllJoyn::AllJoynMessageInfo^ MessageInfo { Windows::Devices::AllJoyn::AllJoynMessageInfo^ get() { return m_messageInfo; } } property ActionsSetPowerToOffResult^ Result { ActionsSetPowerToOffResult^ get() { return m_result; } void set(_In_ ActionsSetPowerToOffResult^ value) { m_result = value; } } Windows::Foundation::Deferral^ GetDeferral(); static Windows::Foundation::IAsyncOperation<ActionsSetPowerToOffResult^>^ GetResultAsync(ActionsSetPowerToOffCalledEventArgs^ args) { args->InvokeAllFinished(); auto t = concurrency::create_task(args->m_tce); return concurrency::create_async([t]() -> concurrency::task<ActionsSetPowerToOffResult^> { return t; }); } private: void Complete(); void InvokeAllFinished(); void InvokeCompleteHandler(); bool m_raised; int m_completionsRequired; concurrency::task_completion_event<ActionsSetPowerToOffResult^> m_tce; std::mutex m_lock; Windows::Devices::AllJoyn::AllJoynMessageInfo^ m_messageInfo; ActionsSetPowerToOffResult^ m_result; }; public ref class ActionsSetPowerToOnCalledEventArgs sealed { public: ActionsSetPowerToOnCalledEventArgs(_In_ Windows::Devices::AllJoyn::AllJoynMessageInfo^ info); property Windows::Devices::AllJoyn::AllJoynMessageInfo^ MessageInfo { Windows::Devices::AllJoyn::AllJoynMessageInfo^ get() { return m_messageInfo; } } property ActionsSetPowerToOnResult^ Result { ActionsSetPowerToOnResult^ get() { return m_result; } void set(_In_ ActionsSetPowerToOnResult^ value) { m_result = value; } } Windows::Foundation::Deferral^ GetDeferral(); static Windows::Foundation::IAsyncOperation<ActionsSetPowerToOnResult^>^ GetResultAsync(ActionsSetPowerToOnCalledEventArgs^ args) { args->InvokeAllFinished(); auto t = concurrency::create_task(args->m_tce); return concurrency::create_async([t]() -> concurrency::task<ActionsSetPowerToOnResult^> { return t; }); } private: void Complete(); void InvokeAllFinished(); void InvokeCompleteHandler(); bool m_raised; int m_completionsRequired; concurrency::task_completion_event<ActionsSetPowerToOnResult^> m_tce; std::mutex m_lock; Windows::Devices::AllJoyn::AllJoynMessageInfo^ m_messageInfo; ActionsSetPowerToOnResult^ m_result; }; public ref class ActionsSetHumidityTo40CalledEventArgs sealed { public: ActionsSetHumidityTo40CalledEventArgs(_In_ Windows::Devices::AllJoyn::AllJoynMessageInfo^ info); property Windows::Devices::AllJoyn::AllJoynMessageInfo^ MessageInfo { Windows::Devices::AllJoyn::AllJoynMessageInfo^ get() { return m_messageInfo; } } property ActionsSetHumidityTo40Result^ Result { ActionsSetHumidityTo40Result^ get() { return m_result; } void set(_In_ ActionsSetHumidityTo40Result^ value) { m_result = value; } } Windows::Foundation::Deferral^ GetDeferral(); static Windows::Foundation::IAsyncOperation<ActionsSetHumidityTo40Result^>^ GetResultAsync(ActionsSetHumidityTo40CalledEventArgs^ args) { args->InvokeAllFinished(); auto t = concurrency::create_task(args->m_tce); return concurrency::create_async([t]() -> concurrency::task<ActionsSetHumidityTo40Result^> { return t; }); } private: void Complete(); void InvokeAllFinished(); void InvokeCompleteHandler(); bool m_raised; int m_completionsRequired; concurrency::task_completion_event<ActionsSetHumidityTo40Result^> m_tce; std::mutex m_lock; Windows::Devices::AllJoyn::AllJoynMessageInfo^ m_messageInfo; ActionsSetHumidityTo40Result^ m_result; }; public ref class ActionsSetHumidityTo45CalledEventArgs sealed { public: ActionsSetHumidityTo45CalledEventArgs(_In_ Windows::Devices::AllJoyn::AllJoynMessageInfo^ info); property Windows::Devices::AllJoyn::AllJoynMessageInfo^ MessageInfo { Windows::Devices::AllJoyn::AllJoynMessageInfo^ get() { return m_messageInfo; } } property ActionsSetHumidityTo45Result^ Result { ActionsSetHumidityTo45Result^ get() { return m_result; } void set(_In_ ActionsSetHumidityTo45Result^ value) { m_result = value; } } Windows::Foundation::Deferral^ GetDeferral(); static Windows::Foundation::IAsyncOperation<ActionsSetHumidityTo45Result^>^ GetResultAsync(ActionsSetHumidityTo45CalledEventArgs^ args) { args->InvokeAllFinished(); auto t = concurrency::create_task(args->m_tce); return concurrency::create_async([t]() -> concurrency::task<ActionsSetHumidityTo45Result^> { return t; }); } private: void Complete(); void InvokeAllFinished(); void InvokeCompleteHandler(); bool m_raised; int m_completionsRequired; concurrency::task_completion_event<ActionsSetHumidityTo45Result^> m_tce; std::mutex m_lock; Windows::Devices::AllJoyn::AllJoynMessageInfo^ m_messageInfo; ActionsSetHumidityTo45Result^ m_result; }; public ref class ActionsSetHumidityTo50CalledEventArgs sealed { public: ActionsSetHumidityTo50CalledEventArgs(_In_ Windows::Devices::AllJoyn::AllJoynMessageInfo^ info); property Windows::Devices::AllJoyn::AllJoynMessageInfo^ MessageInfo { Windows::Devices::AllJoyn::AllJoynMessageInfo^ get() { return m_messageInfo; } } property ActionsSetHumidityTo50Result^ Result { ActionsSetHumidityTo50Result^ get() { return m_result; } void set(_In_ ActionsSetHumidityTo50Result^ value) { m_result = value; } } Windows::Foundation::Deferral^ GetDeferral(); static Windows::Foundation::IAsyncOperation<ActionsSetHumidityTo50Result^>^ GetResultAsync(ActionsSetHumidityTo50CalledEventArgs^ args) { args->InvokeAllFinished(); auto t = concurrency::create_task(args->m_tce); return concurrency::create_async([t]() -> concurrency::task<ActionsSetHumidityTo50Result^> { return t; }); } private: void Complete(); void InvokeAllFinished(); void InvokeCompleteHandler(); bool m_raised; int m_completionsRequired; concurrency::task_completion_event<ActionsSetHumidityTo50Result^> m_tce; std::mutex m_lock; Windows::Devices::AllJoyn::AllJoynMessageInfo^ m_messageInfo; ActionsSetHumidityTo50Result^ m_result; }; public ref class ActionsSetHumidityTo55CalledEventArgs sealed { public: ActionsSetHumidityTo55CalledEventArgs(_In_ Windows::Devices::AllJoyn::AllJoynMessageInfo^ info); property Windows::Devices::AllJoyn::AllJoynMessageInfo^ MessageInfo { Windows::Devices::AllJoyn::AllJoynMessageInfo^ get() { return m_messageInfo; } } property ActionsSetHumidityTo55Result^ Result { ActionsSetHumidityTo55Result^ get() { return m_result; } void set(_In_ ActionsSetHumidityTo55Result^ value) { m_result = value; } } Windows::Foundation::Deferral^ GetDeferral(); static Windows::Foundation::IAsyncOperation<ActionsSetHumidityTo55Result^>^ GetResultAsync(ActionsSetHumidityTo55CalledEventArgs^ args) { args->InvokeAllFinished(); auto t = concurrency::create_task(args->m_tce); return concurrency::create_async([t]() -> concurrency::task<ActionsSetHumidityTo55Result^> { return t; }); } private: void Complete(); void InvokeAllFinished(); void InvokeCompleteHandler(); bool m_raised; int m_completionsRequired; concurrency::task_completion_event<ActionsSetHumidityTo55Result^> m_tce; std::mutex m_lock; Windows::Devices::AllJoyn::AllJoynMessageInfo^ m_messageInfo; ActionsSetHumidityTo55Result^ m_result; }; public ref class ActionsSetHumidityTo60CalledEventArgs sealed { public: ActionsSetHumidityTo60CalledEventArgs(_In_ Windows::Devices::AllJoyn::AllJoynMessageInfo^ info); property Windows::Devices::AllJoyn::AllJoynMessageInfo^ MessageInfo { Windows::Devices::AllJoyn::AllJoynMessageInfo^ get() { return m_messageInfo; } } property ActionsSetHumidityTo60Result^ Result { ActionsSetHumidityTo60Result^ get() { return m_result; } void set(_In_ ActionsSetHumidityTo60Result^ value) { m_result = value; } } Windows::Foundation::Deferral^ GetDeferral(); static Windows::Foundation::IAsyncOperation<ActionsSetHumidityTo60Result^>^ GetResultAsync(ActionsSetHumidityTo60CalledEventArgs^ args) { args->InvokeAllFinished(); auto t = concurrency::create_task(args->m_tce); return concurrency::create_async([t]() -> concurrency::task<ActionsSetHumidityTo60Result^> { return t; }); } private: void Complete(); void InvokeAllFinished(); void InvokeCompleteHandler(); bool m_raised; int m_completionsRequired; concurrency::task_completion_event<ActionsSetHumidityTo60Result^> m_tce; std::mutex m_lock; Windows::Devices::AllJoyn::AllJoynMessageInfo^ m_messageInfo; ActionsSetHumidityTo60Result^ m_result; }; public ref class ActionsSetHumidityTo65CalledEventArgs sealed { public: ActionsSetHumidityTo65CalledEventArgs(_In_ Windows::Devices::AllJoyn::AllJoynMessageInfo^ info); property Windows::Devices::AllJoyn::AllJoynMessageInfo^ MessageInfo { Windows::Devices::AllJoyn::AllJoynMessageInfo^ get() { return m_messageInfo; } } property ActionsSetHumidityTo65Result^ Result { ActionsSetHumidityTo65Result^ get() { return m_result; } void set(_In_ ActionsSetHumidityTo65Result^ value) { m_result = value; } } Windows::Foundation::Deferral^ GetDeferral(); static Windows::Foundation::IAsyncOperation<ActionsSetHumidityTo65Result^>^ GetResultAsync(ActionsSetHumidityTo65CalledEventArgs^ args) { args->InvokeAllFinished(); auto t = concurrency::create_task(args->m_tce); return concurrency::create_async([t]() -> concurrency::task<ActionsSetHumidityTo65Result^> { return t; }); } private: void Complete(); void InvokeAllFinished(); void InvokeCompleteHandler(); bool m_raised; int m_completionsRequired; concurrency::task_completion_event<ActionsSetHumidityTo65Result^> m_tce; std::mutex m_lock; Windows::Devices::AllJoyn::AllJoynMessageInfo^ m_messageInfo; ActionsSetHumidityTo65Result^ m_result; }; public ref class ActionsSetHumidityTo70CalledEventArgs sealed { public: ActionsSetHumidityTo70CalledEventArgs(_In_ Windows::Devices::AllJoyn::AllJoynMessageInfo^ info); property Windows::Devices::AllJoyn::AllJoynMessageInfo^ MessageInfo { Windows::Devices::AllJoyn::AllJoynMessageInfo^ get() { return m_messageInfo; } } property ActionsSetHumidityTo70Result^ Result { ActionsSetHumidityTo70Result^ get() { return m_result; } void set(_In_ ActionsSetHumidityTo70Result^ value) { m_result = value; } } Windows::Foundation::Deferral^ GetDeferral(); static Windows::Foundation::IAsyncOperation<ActionsSetHumidityTo70Result^>^ GetResultAsync(ActionsSetHumidityTo70CalledEventArgs^ args) { args->InvokeAllFinished(); auto t = concurrency::create_task(args->m_tce); return concurrency::create_async([t]() -> concurrency::task<ActionsSetHumidityTo70Result^> { return t; }); } private: void Complete(); void InvokeAllFinished(); void InvokeCompleteHandler(); bool m_raised; int m_completionsRequired; concurrency::task_completion_event<ActionsSetHumidityTo70Result^> m_tce; std::mutex m_lock; Windows::Devices::AllJoyn::AllJoynMessageInfo^ m_messageInfo; ActionsSetHumidityTo70Result^ m_result; }; public ref class ActionsSetHumidityTo75CalledEventArgs sealed { public: ActionsSetHumidityTo75CalledEventArgs(_In_ Windows::Devices::AllJoyn::AllJoynMessageInfo^ info); property Windows::Devices::AllJoyn::AllJoynMessageInfo^ MessageInfo { Windows::Devices::AllJoyn::AllJoynMessageInfo^ get() { return m_messageInfo; } } property ActionsSetHumidityTo75Result^ Result { ActionsSetHumidityTo75Result^ get() { return m_result; } void set(_In_ ActionsSetHumidityTo75Result^ value) { m_result = value; } } Windows::Foundation::Deferral^ GetDeferral(); static Windows::Foundation::IAsyncOperation<ActionsSetHumidityTo75Result^>^ GetResultAsync(ActionsSetHumidityTo75CalledEventArgs^ args) { args->InvokeAllFinished(); auto t = concurrency::create_task(args->m_tce); return concurrency::create_async([t]() -> concurrency::task<ActionsSetHumidityTo75Result^> { return t; }); } private: void Complete(); void InvokeAllFinished(); void InvokeCompleteHandler(); bool m_raised; int m_completionsRequired; concurrency::task_completion_event<ActionsSetHumidityTo75Result^> m_tce; std::mutex m_lock; Windows::Devices::AllJoyn::AllJoynMessageInfo^ m_messageInfo; ActionsSetHumidityTo75Result^ m_result; }; public ref class ActionsSetHumidityTo80CalledEventArgs sealed { public: ActionsSetHumidityTo80CalledEventArgs(_In_ Windows::Devices::AllJoyn::AllJoynMessageInfo^ info); property Windows::Devices::AllJoyn::AllJoynMessageInfo^ MessageInfo { Windows::Devices::AllJoyn::AllJoynMessageInfo^ get() { return m_messageInfo; } } property ActionsSetHumidityTo80Result^ Result { ActionsSetHumidityTo80Result^ get() { return m_result; } void set(_In_ ActionsSetHumidityTo80Result^ value) { m_result = value; } } Windows::Foundation::Deferral^ GetDeferral(); static Windows::Foundation::IAsyncOperation<ActionsSetHumidityTo80Result^>^ GetResultAsync(ActionsSetHumidityTo80CalledEventArgs^ args) { args->InvokeAllFinished(); auto t = concurrency::create_task(args->m_tce); return concurrency::create_async([t]() -> concurrency::task<ActionsSetHumidityTo80Result^> { return t; }); } private: void Complete(); void InvokeAllFinished(); void InvokeCompleteHandler(); bool m_raised; int m_completionsRequired; concurrency::task_completion_event<ActionsSetHumidityTo80Result^> m_tce; std::mutex m_lock; Windows::Devices::AllJoyn::AllJoynMessageInfo^ m_messageInfo; ActionsSetHumidityTo80Result^ m_result; }; public ref class ActionsSetWarmMistToOFFCalledEventArgs sealed { public: ActionsSetWarmMistToOFFCalledEventArgs(_In_ Windows::Devices::AllJoyn::AllJoynMessageInfo^ info); property Windows::Devices::AllJoyn::AllJoynMessageInfo^ MessageInfo { Windows::Devices::AllJoyn::AllJoynMessageInfo^ get() { return m_messageInfo; } } property ActionsSetWarmMistToOFFResult^ Result { ActionsSetWarmMistToOFFResult^ get() { return m_result; } void set(_In_ ActionsSetWarmMistToOFFResult^ value) { m_result = value; } } Windows::Foundation::Deferral^ GetDeferral(); static Windows::Foundation::IAsyncOperation<ActionsSetWarmMistToOFFResult^>^ GetResultAsync(ActionsSetWarmMistToOFFCalledEventArgs^ args) { args->InvokeAllFinished(); auto t = concurrency::create_task(args->m_tce); return concurrency::create_async([t]() -> concurrency::task<ActionsSetWarmMistToOFFResult^> { return t; }); } private: void Complete(); void InvokeAllFinished(); void InvokeCompleteHandler(); bool m_raised; int m_completionsRequired; concurrency::task_completion_event<ActionsSetWarmMistToOFFResult^> m_tce; std::mutex m_lock; Windows::Devices::AllJoyn::AllJoynMessageInfo^ m_messageInfo; ActionsSetWarmMistToOFFResult^ m_result; }; public ref class ActionsSetWarmMistToLOWCalledEventArgs sealed { public: ActionsSetWarmMistToLOWCalledEventArgs(_In_ Windows::Devices::AllJoyn::AllJoynMessageInfo^ info); property Windows::Devices::AllJoyn::AllJoynMessageInfo^ MessageInfo { Windows::Devices::AllJoyn::AllJoynMessageInfo^ get() { return m_messageInfo; } } property ActionsSetWarmMistToLOWResult^ Result { ActionsSetWarmMistToLOWResult^ get() { return m_result; } void set(_In_ ActionsSetWarmMistToLOWResult^ value) { m_result = value; } } Windows::Foundation::Deferral^ GetDeferral(); static Windows::Foundation::IAsyncOperation<ActionsSetWarmMistToLOWResult^>^ GetResultAsync(ActionsSetWarmMistToLOWCalledEventArgs^ args) { args->InvokeAllFinished(); auto t = concurrency::create_task(args->m_tce); return concurrency::create_async([t]() -> concurrency::task<ActionsSetWarmMistToLOWResult^> { return t; }); } private: void Complete(); void InvokeAllFinished(); void InvokeCompleteHandler(); bool m_raised; int m_completionsRequired; concurrency::task_completion_event<ActionsSetWarmMistToLOWResult^> m_tce; std::mutex m_lock; Windows::Devices::AllJoyn::AllJoynMessageInfo^ m_messageInfo; ActionsSetWarmMistToLOWResult^ m_result; }; public ref class ActionsSetWarmMistToHICalledEventArgs sealed { public: ActionsSetWarmMistToHICalledEventArgs(_In_ Windows::Devices::AllJoyn::AllJoynMessageInfo^ info); property Windows::Devices::AllJoyn::AllJoynMessageInfo^ MessageInfo { Windows::Devices::AllJoyn::AllJoynMessageInfo^ get() { return m_messageInfo; } } property ActionsSetWarmMistToHIResult^ Result { ActionsSetWarmMistToHIResult^ get() { return m_result; } void set(_In_ ActionsSetWarmMistToHIResult^ value) { m_result = value; } } Windows::Foundation::Deferral^ GetDeferral(); static Windows::Foundation::IAsyncOperation<ActionsSetWarmMistToHIResult^>^ GetResultAsync(ActionsSetWarmMistToHICalledEventArgs^ args) { args->InvokeAllFinished(); auto t = concurrency::create_task(args->m_tce); return concurrency::create_async([t]() -> concurrency::task<ActionsSetWarmMistToHIResult^> { return t; }); } private: void Complete(); void InvokeAllFinished(); void InvokeCompleteHandler(); bool m_raised; int m_completionsRequired; concurrency::task_completion_event<ActionsSetWarmMistToHIResult^> m_tce; std::mutex m_lock; Windows::Devices::AllJoyn::AllJoynMessageInfo^ m_messageInfo; ActionsSetWarmMistToHIResult^ m_result; }; public ref class ActionsSetMistVolumeToLOWCalledEventArgs sealed { public: ActionsSetMistVolumeToLOWCalledEventArgs(_In_ Windows::Devices::AllJoyn::AllJoynMessageInfo^ info); property Windows::Devices::AllJoyn::AllJoynMessageInfo^ MessageInfo { Windows::Devices::AllJoyn::AllJoynMessageInfo^ get() { return m_messageInfo; } } property ActionsSetMistVolumeToLOWResult^ Result { ActionsSetMistVolumeToLOWResult^ get() { return m_result; } void set(_In_ ActionsSetMistVolumeToLOWResult^ value) { m_result = value; } } Windows::Foundation::Deferral^ GetDeferral(); static Windows::Foundation::IAsyncOperation<ActionsSetMistVolumeToLOWResult^>^ GetResultAsync(ActionsSetMistVolumeToLOWCalledEventArgs^ args) { args->InvokeAllFinished(); auto t = concurrency::create_task(args->m_tce); return concurrency::create_async([t]() -> concurrency::task<ActionsSetMistVolumeToLOWResult^> { return t; }); } private: void Complete(); void InvokeAllFinished(); void InvokeCompleteHandler(); bool m_raised; int m_completionsRequired; concurrency::task_completion_event<ActionsSetMistVolumeToLOWResult^> m_tce; std::mutex m_lock; Windows::Devices::AllJoyn::AllJoynMessageInfo^ m_messageInfo; ActionsSetMistVolumeToLOWResult^ m_result; }; public ref class ActionsSetMistVolumeToMEDCalledEventArgs sealed { public: ActionsSetMistVolumeToMEDCalledEventArgs(_In_ Windows::Devices::AllJoyn::AllJoynMessageInfo^ info); property Windows::Devices::AllJoyn::AllJoynMessageInfo^ MessageInfo { Windows::Devices::AllJoyn::AllJoynMessageInfo^ get() { return m_messageInfo; } } property ActionsSetMistVolumeToMEDResult^ Result { ActionsSetMistVolumeToMEDResult^ get() { return m_result; } void set(_In_ ActionsSetMistVolumeToMEDResult^ value) { m_result = value; } } Windows::Foundation::Deferral^ GetDeferral(); static Windows::Foundation::IAsyncOperation<ActionsSetMistVolumeToMEDResult^>^ GetResultAsync(ActionsSetMistVolumeToMEDCalledEventArgs^ args) { args->InvokeAllFinished(); auto t = concurrency::create_task(args->m_tce); return concurrency::create_async([t]() -> concurrency::task<ActionsSetMistVolumeToMEDResult^> { return t; }); } private: void Complete(); void InvokeAllFinished(); void InvokeCompleteHandler(); bool m_raised; int m_completionsRequired; concurrency::task_completion_event<ActionsSetMistVolumeToMEDResult^> m_tce; std::mutex m_lock; Windows::Devices::AllJoyn::AllJoynMessageInfo^ m_messageInfo; ActionsSetMistVolumeToMEDResult^ m_result; }; public ref class ActionsSetMistVolumeToHICalledEventArgs sealed { public: ActionsSetMistVolumeToHICalledEventArgs(_In_ Windows::Devices::AllJoyn::AllJoynMessageInfo^ info); property Windows::Devices::AllJoyn::AllJoynMessageInfo^ MessageInfo { Windows::Devices::AllJoyn::AllJoynMessageInfo^ get() { return m_messageInfo; } } property ActionsSetMistVolumeToHIResult^ Result { ActionsSetMistVolumeToHIResult^ get() { return m_result; } void set(_In_ ActionsSetMistVolumeToHIResult^ value) { m_result = value; } } Windows::Foundation::Deferral^ GetDeferral(); static Windows::Foundation::IAsyncOperation<ActionsSetMistVolumeToHIResult^>^ GetResultAsync(ActionsSetMistVolumeToHICalledEventArgs^ args) { args->InvokeAllFinished(); auto t = concurrency::create_task(args->m_tce); return concurrency::create_async([t]() -> concurrency::task<ActionsSetMistVolumeToHIResult^> { return t; }); } private: void Complete(); void InvokeAllFinished(); void InvokeCompleteHandler(); bool m_raised; int m_completionsRequired; concurrency::task_completion_event<ActionsSetMistVolumeToHIResult^> m_tce; std::mutex m_lock; Windows::Devices::AllJoyn::AllJoynMessageInfo^ m_messageInfo; ActionsSetMistVolumeToHIResult^ m_result; }; // Readable Properties public ref class ActionsGetVersionRequestedEventArgs sealed { public: ActionsGetVersionRequestedEventArgs(_In_ Windows::Devices::AllJoyn::AllJoynMessageInfo^ info); property Windows::Devices::AllJoyn::AllJoynMessageInfo^ MessageInfo { Windows::Devices::AllJoyn::AllJoynMessageInfo^ get() { return m_messageInfo; } } property ActionsGetVersionResult^ Result { ActionsGetVersionResult^ get() { return m_result; } void set(_In_ ActionsGetVersionResult^ value) { m_result = value; } } Windows::Foundation::Deferral^ GetDeferral(); static Windows::Foundation::IAsyncOperation<ActionsGetVersionResult^>^ GetResultAsync(ActionsGetVersionRequestedEventArgs^ args) { args->InvokeAllFinished(); auto t = concurrency::create_task(args->m_tce); return concurrency::create_async([t]() -> concurrency::task<ActionsGetVersionResult^> { return t; }); } private: void Complete(); void InvokeAllFinished(); void InvokeCompleteHandler(); bool m_raised; int m_completionsRequired; concurrency::task_completion_event<ActionsGetVersionResult^> m_tce; std::mutex m_lock; Windows::Devices::AllJoyn::AllJoynMessageInfo^ m_messageInfo; ActionsGetVersionResult^ m_result; }; // Writable Properties } } } }
mit
ndrluis/Rukuli
lib/rukuli/searchable.rb
4815
# The Rukuli::Searchable module is the heart of Sikuli. It defines the # wrapper around Sikuli's on screen image searching and matching capability # It is implemented by the Region class. # module Rukuli module Searchable # Public: search for an image within a Region # # filename - A String representation of the filename to match against # similarity - A Float between 0 and 1 representing the threshold for # matching an image. Passing 1 corresponds to a 100% pixel for pixel # match. Defaults to 0.9 (90% match) # # Examples # # region.find('needle.png') # region.find('needle.png', 0.5) # # Returns an instance of Region representing the best match # # Throws Rukuli::FileNotFound if the file could not be found on the system # Throws Rukuli::ImageNotMatched if no matches are found within the region def find(filename, similarity = 0.9) begin pattern = build_pattern(filename, similarity) match = Region.new(@java_obj.find(pattern)) match.highlight if Rukuli::Config.highlight_on_find match rescue NativeException => e raise_exception e, filename end end # Public: search for an image within a region (does not raise ImageNotFound exceptions) # # filename - A String representation of the filename to match against # similarity - A Float between 0 and 1 representing the threshold for # matching an image. Passing 1 corresponds to a 100% pixel for pixel # match. Defaults to 0.9 (90% match) # # Examples # # region.find!('needle.png') # region.find!('needle.png', 0.5) # # Returns the match or nil if no match is found def find!(filename, similarity = 0.9) begin find(filename, similarity) rescue Rukuli::ImageNotFound => e nil end end # Public: search for an image within a Region and return all matches # # TODO: Sort return results so they are always returned in the same order # (top left to bottom right) # # filename - A String representation of the filename to match against # similarity - A Float between 0 and 1 representing the threshold for # matching an image. Passing 1 corresponds to a 100% pixel for pixel # match. Defaults to 0.9 (90% match) # # Examples # # region.find_all('needle.png') # region.find_all('needle.png', 0.5) # # Returns an array of Region objects that match the given file and # threshold # # Throws Rukuli::FileNotFound if the file could not be found on the system # Throws Rukuli::ImageNotMatched if no matches are found within the region def find_all(filename, similarity = 0.9) begin pattern = build_pattern(filename, similarity) matches = @java_obj.findAll(pattern) regions = matches.collect do |r| match = Region.new(r) match.highlight if Rukuli::Config.highlight_on_find match end regions rescue NativeException => e raise_exception e, filename end end # Public: wait for a match to appear within a region # # filename - A String representation of the filename to match against # time - A Fixnum representing the amount of time to wait defaults # to 2 seconds # similarity - A Float between 0 and 1 representing the threshold for # matching an image. Passing 1 corresponds to a 100% pixel for pixel # match. Defaults to 0.9 (90% match) # # Examples # # region.wait('needle.png') # wait for needle.png to appear for up to 1 second # region.wait('needle.png', 10) # wait for needle.png to appear for 10 seconds # # Returns nothing # # Throws Rukuli::FileNotFound if the file could not be found on the system # Throws Rukuli::ImageNotMatched if no matches are found within the region def wait(filename, time = 2, similarity = 0.9) begin pattern = build_pattern(filename, similarity) match = Region.new(@java_obj.wait(pattern, time)) match.highlight if Rukuli::Config.highlight_on_find match rescue NativeException => e raise_exception e, filename end end private # Private: builds a java Pattern to check # # filename - A String representation of the filename to match against # similarity - A Float between 0 and 1 representing the threshold for # matching an image. Passing 1 corresponds to a 100% pixel for pixel # match. Defaults to 0.9 (90% match) # # Returns a org.sikuli.script::Pattern object to match against def build_pattern(filename, similarity) org.sikuli.script::Pattern.new(filename).similar(similarity) end end end
mit