text
stringlengths
2
1.04M
meta
dict
import subprocess import errno import select import os _PIPE_BUF = getattr(select, 'PIPE_BUF', 512) def run_process(cmd, stdin=None, iterate_stdin=True, output_chunk_size=1024, shell=True, to_close=None, cwd=None): """ This is a modification of subprocess.Popen.communicate that accepts an iterable stdin and is itself a generator for stdout """ try: p = subprocess.Popen(cmd, shell=shell, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=cwd) if stdin: if iterate_stdin: stdin_iter = iter(stdin) stdin_buffer = '' stdin_available = True else: stdin_buffer = stdin stdin_available = False write_set = [] read_set = [] output_buffer = '' if p.stdin and stdin: write_set.append(p.stdin) if p.stdout: read_set.append(p.stdout) if p.stderr: read_set.append(p.stderr) while read_set or write_set: try: rlist, wlist, xlist = select.select(read_set, write_set, []) except select.error as e: if e.args[0] == errno.EINTR: continue raise if p.stdin in wlist: while len(stdin_buffer) < _PIPE_BUF and stdin_available: try: stdin_buffer += stdin_iter.next() except StopIteration: stdin_available = False chunk = stdin_buffer[:_PIPE_BUF] bytes_written = os.write(p.stdin.fileno(), chunk) stdin_buffer = stdin_buffer[bytes_written:] if not (stdin_buffer or stdin_available): p.stdin.close() write_set.remove(p.stdin) if p.stdout in rlist: data = os.read(p.stdout.fileno(), output_chunk_size) if data == '': p.stdout.close() read_set.remove(p.stdout) if data: output_buffer += data yield data if p.stderr in rlist: data = os.read(p.stderr.fileno(), output_chunk_size) if data == '': p.stderr.close() read_set.remove(p.stderr) if data: output_buffer += data if len(output_buffer) > output_chunk_size: output_buffer = output_buffer[-output_chunk_size:] return_code = p.poll() if return_code: e = subprocess.CalledProcessError(return_code, cmd) e.output = output_buffer raise e finally: if to_close: to_close.close()
{ "content_hash": "cecd2d7b20a70387b0fbd1414804c6de", "timestamp": "", "source": "github", "line_count": 86, "max_line_length": 126, "avg_line_length": 33.04651162790697, "alnum_prop": 0.49929627023223083, "repo_name": "sdcooke/django_bundles", "id": "979d44b8a6930a45b74f414d256bc3094f563ff2", "size": "2842", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "django_bundles/utils/processes.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "56105" } ], "symlink_target": "" }
use super::from_bytes::FromBytes; #[repr(packed)] pub struct VdevLabel { pub blank: [u8; 8 * 1024], pub boot_header: [u8; 8 * 1024], pub nv_pairs: [u8; 112 * 1024], pub uberblocks: [u8; 128 * 1024], } impl FromBytes for VdevLabel { } //////////////////////////////////////////////////////////////////////////////////////////////////// pub struct Vdev { id: u64, // child number in vdev parent guid: u64, // unique ID for this vdev guid_sum: u64, // self guid + all child guids orig_guid: u64, // orig. guid prior to remove asize: u64, // allocatable device capacity min_asize: u64, // min acceptable asize max_asize: u64, // max acceptable asize ashift: u64, // block alignment shift // Top level only ms_array: u64, // Leaf only }
{ "content_hash": "13caff9a21ebc40c7c8597f5464b67c9", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 100, "avg_line_length": 27.517241379310345, "alnum_prop": 0.543859649122807, "repo_name": "NobbZ/redox", "id": "67d020ae3c43ece8097b7fb0d21c904fff201485", "size": "798", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "filesystem/apps/zfs/vdev.rs", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "22108" }, { "name": "Batchfile", "bytes": "78" }, { "name": "C", "bytes": "533226" }, { "name": "C++", "bytes": "106201" }, { "name": "Lua", "bytes": "80" }, { "name": "Makefile", "bytes": "22410" }, { "name": "Rust", "bytes": "3352823" }, { "name": "Shell", "bytes": "76410" } ], "symlink_target": "" }
package com.amazonaws.services.codecommit.model; import java.io.Serializable; import javax.annotation.Generated; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/codecommit-2015-04-13/PostCommentForComparedCommit" * target="_top">AWS API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class PostCommentForComparedCommitResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable { /** * <p> * The name of the repository where you posted a comment on the comparison between commits. * </p> */ private String repositoryName; /** * <p> * In the directionality you established, the full commit ID of the before commit. * </p> */ private String beforeCommitId; /** * <p> * In the directionality you established, the full commit ID of the after commit. * </p> */ private String afterCommitId; /** * <p> * In the directionality you established, the blob ID of the before blob. * </p> */ private String beforeBlobId; /** * <p> * In the directionality you established, the blob ID of the after blob. * </p> */ private String afterBlobId; /** * <p> * The location of the comment in the comparison between the two commits. * </p> */ private Location location; /** * <p> * The content of the comment you posted. * </p> */ private Comment comment; /** * <p> * The name of the repository where you posted a comment on the comparison between commits. * </p> * * @param repositoryName * The name of the repository where you posted a comment on the comparison between commits. */ public void setRepositoryName(String repositoryName) { this.repositoryName = repositoryName; } /** * <p> * The name of the repository where you posted a comment on the comparison between commits. * </p> * * @return The name of the repository where you posted a comment on the comparison between commits. */ public String getRepositoryName() { return this.repositoryName; } /** * <p> * The name of the repository where you posted a comment on the comparison between commits. * </p> * * @param repositoryName * The name of the repository where you posted a comment on the comparison between commits. * @return Returns a reference to this object so that method calls can be chained together. */ public PostCommentForComparedCommitResult withRepositoryName(String repositoryName) { setRepositoryName(repositoryName); return this; } /** * <p> * In the directionality you established, the full commit ID of the before commit. * </p> * * @param beforeCommitId * In the directionality you established, the full commit ID of the before commit. */ public void setBeforeCommitId(String beforeCommitId) { this.beforeCommitId = beforeCommitId; } /** * <p> * In the directionality you established, the full commit ID of the before commit. * </p> * * @return In the directionality you established, the full commit ID of the before commit. */ public String getBeforeCommitId() { return this.beforeCommitId; } /** * <p> * In the directionality you established, the full commit ID of the before commit. * </p> * * @param beforeCommitId * In the directionality you established, the full commit ID of the before commit. * @return Returns a reference to this object so that method calls can be chained together. */ public PostCommentForComparedCommitResult withBeforeCommitId(String beforeCommitId) { setBeforeCommitId(beforeCommitId); return this; } /** * <p> * In the directionality you established, the full commit ID of the after commit. * </p> * * @param afterCommitId * In the directionality you established, the full commit ID of the after commit. */ public void setAfterCommitId(String afterCommitId) { this.afterCommitId = afterCommitId; } /** * <p> * In the directionality you established, the full commit ID of the after commit. * </p> * * @return In the directionality you established, the full commit ID of the after commit. */ public String getAfterCommitId() { return this.afterCommitId; } /** * <p> * In the directionality you established, the full commit ID of the after commit. * </p> * * @param afterCommitId * In the directionality you established, the full commit ID of the after commit. * @return Returns a reference to this object so that method calls can be chained together. */ public PostCommentForComparedCommitResult withAfterCommitId(String afterCommitId) { setAfterCommitId(afterCommitId); return this; } /** * <p> * In the directionality you established, the blob ID of the before blob. * </p> * * @param beforeBlobId * In the directionality you established, the blob ID of the before blob. */ public void setBeforeBlobId(String beforeBlobId) { this.beforeBlobId = beforeBlobId; } /** * <p> * In the directionality you established, the blob ID of the before blob. * </p> * * @return In the directionality you established, the blob ID of the before blob. */ public String getBeforeBlobId() { return this.beforeBlobId; } /** * <p> * In the directionality you established, the blob ID of the before blob. * </p> * * @param beforeBlobId * In the directionality you established, the blob ID of the before blob. * @return Returns a reference to this object so that method calls can be chained together. */ public PostCommentForComparedCommitResult withBeforeBlobId(String beforeBlobId) { setBeforeBlobId(beforeBlobId); return this; } /** * <p> * In the directionality you established, the blob ID of the after blob. * </p> * * @param afterBlobId * In the directionality you established, the blob ID of the after blob. */ public void setAfterBlobId(String afterBlobId) { this.afterBlobId = afterBlobId; } /** * <p> * In the directionality you established, the blob ID of the after blob. * </p> * * @return In the directionality you established, the blob ID of the after blob. */ public String getAfterBlobId() { return this.afterBlobId; } /** * <p> * In the directionality you established, the blob ID of the after blob. * </p> * * @param afterBlobId * In the directionality you established, the blob ID of the after blob. * @return Returns a reference to this object so that method calls can be chained together. */ public PostCommentForComparedCommitResult withAfterBlobId(String afterBlobId) { setAfterBlobId(afterBlobId); return this; } /** * <p> * The location of the comment in the comparison between the two commits. * </p> * * @param location * The location of the comment in the comparison between the two commits. */ public void setLocation(Location location) { this.location = location; } /** * <p> * The location of the comment in the comparison between the two commits. * </p> * * @return The location of the comment in the comparison between the two commits. */ public Location getLocation() { return this.location; } /** * <p> * The location of the comment in the comparison between the two commits. * </p> * * @param location * The location of the comment in the comparison between the two commits. * @return Returns a reference to this object so that method calls can be chained together. */ public PostCommentForComparedCommitResult withLocation(Location location) { setLocation(location); return this; } /** * <p> * The content of the comment you posted. * </p> * * @param comment * The content of the comment you posted. */ public void setComment(Comment comment) { this.comment = comment; } /** * <p> * The content of the comment you posted. * </p> * * @return The content of the comment you posted. */ public Comment getComment() { return this.comment; } /** * <p> * The content of the comment you posted. * </p> * * @param comment * The content of the comment you posted. * @return Returns a reference to this object so that method calls can be chained together. */ public PostCommentForComparedCommitResult withComment(Comment comment) { setComment(comment); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getRepositoryName() != null) sb.append("RepositoryName: ").append(getRepositoryName()).append(","); if (getBeforeCommitId() != null) sb.append("BeforeCommitId: ").append(getBeforeCommitId()).append(","); if (getAfterCommitId() != null) sb.append("AfterCommitId: ").append(getAfterCommitId()).append(","); if (getBeforeBlobId() != null) sb.append("BeforeBlobId: ").append(getBeforeBlobId()).append(","); if (getAfterBlobId() != null) sb.append("AfterBlobId: ").append(getAfterBlobId()).append(","); if (getLocation() != null) sb.append("Location: ").append(getLocation()).append(","); if (getComment() != null) sb.append("Comment: ").append(getComment()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof PostCommentForComparedCommitResult == false) return false; PostCommentForComparedCommitResult other = (PostCommentForComparedCommitResult) obj; if (other.getRepositoryName() == null ^ this.getRepositoryName() == null) return false; if (other.getRepositoryName() != null && other.getRepositoryName().equals(this.getRepositoryName()) == false) return false; if (other.getBeforeCommitId() == null ^ this.getBeforeCommitId() == null) return false; if (other.getBeforeCommitId() != null && other.getBeforeCommitId().equals(this.getBeforeCommitId()) == false) return false; if (other.getAfterCommitId() == null ^ this.getAfterCommitId() == null) return false; if (other.getAfterCommitId() != null && other.getAfterCommitId().equals(this.getAfterCommitId()) == false) return false; if (other.getBeforeBlobId() == null ^ this.getBeforeBlobId() == null) return false; if (other.getBeforeBlobId() != null && other.getBeforeBlobId().equals(this.getBeforeBlobId()) == false) return false; if (other.getAfterBlobId() == null ^ this.getAfterBlobId() == null) return false; if (other.getAfterBlobId() != null && other.getAfterBlobId().equals(this.getAfterBlobId()) == false) return false; if (other.getLocation() == null ^ this.getLocation() == null) return false; if (other.getLocation() != null && other.getLocation().equals(this.getLocation()) == false) return false; if (other.getComment() == null ^ this.getComment() == null) return false; if (other.getComment() != null && other.getComment().equals(this.getComment()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getRepositoryName() == null) ? 0 : getRepositoryName().hashCode()); hashCode = prime * hashCode + ((getBeforeCommitId() == null) ? 0 : getBeforeCommitId().hashCode()); hashCode = prime * hashCode + ((getAfterCommitId() == null) ? 0 : getAfterCommitId().hashCode()); hashCode = prime * hashCode + ((getBeforeBlobId() == null) ? 0 : getBeforeBlobId().hashCode()); hashCode = prime * hashCode + ((getAfterBlobId() == null) ? 0 : getAfterBlobId().hashCode()); hashCode = prime * hashCode + ((getLocation() == null) ? 0 : getLocation().hashCode()); hashCode = prime * hashCode + ((getComment() == null) ? 0 : getComment().hashCode()); return hashCode; } @Override public PostCommentForComparedCommitResult clone() { try { return (PostCommentForComparedCommitResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
{ "content_hash": "0ea9e3a7176c865fca7a68cd933394e2", "timestamp": "", "source": "github", "line_count": 433, "max_line_length": 161, "avg_line_length": 32.08083140877598, "alnum_prop": 0.6134907494060903, "repo_name": "aws/aws-sdk-java", "id": "f72e3ff51e33858d3c1869cafaf44566b2e95594", "size": "14471", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "aws-java-sdk-codecommit/src/main/java/com/amazonaws/services/codecommit/model/PostCommentForComparedCommitResult.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
export EDITOR=vim export SHELL=/bin/bash #SVN_EDITOR='/Applications/TextWrangler.app/Contents/MacOS/TextWrangler' export SVN_EDITOR='vim' # add to PATH export PATH="$PATH:/usr/local/sbin:~/Shell" # enable shims and autocompletion if which rbenv > /dev/null; then eval "$(rbenv init -)"; fi # command aliases alias ll='ls -la' alias h=history alias edt='open "/Applications/Sublime Text 2.app" $*' alias g=git # local shortcuts alias proj='cd ~/Developer/Projects' alias work='cd ~/Developer/Projects/work' alias hotl='cd ~/Google\ Drive/My-hotel/Activities' alias red='cd ~/Developer/OpenSource/redmine-all' # sunsoft shortcuts alias redmine-rem='ssh sunsoft@sunsoft.static.otenet.gr -p 5000' goo() { a='https://www.google.com/search?q=' open "$a$*" }
{ "content_hash": "56c5e975e2021a38a6ec7e98c3f99f53", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 72, "avg_line_length": 23.09090909090909, "alnum_prop": 0.7296587926509186, "repo_name": "mtsagias/.dotfiles", "id": "a79db6e2751673720d0e6ab03b4f12aa14c57443", "size": "865", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "bin/profile.sh", "mode": "33261", "license": "mit", "language": [ { "name": "Python", "bytes": "590" }, { "name": "Ruby", "bytes": "2088" }, { "name": "Shell", "bytes": "14862" }, { "name": "Vim script", "bytes": "1892" } ], "symlink_target": "" }
#ifndef PEVAL_BADUGIHANDEVALUATOR_H_ #define PEVAL_BADUGIHANDEVALUATOR_H_ #include "PokerHandEvaluator.h" namespace pokerstove { /** * A specialized hand evaluator for hold'em. Not as slow. */ class BadugiHandEvaluator : public PokerHandEvaluator { public: BadugiHandEvaluator() : PokerHandEvaluator() , _numDraws(0) {} virtual PokerHandEvaluation evaluateHand(const CardSet& hand, const CardSet&) const { return PokerHandEvaluation(hand.evaluateBadugi()); } virtual PokerEvaluation evaluateRanks(const CardSet& hand, const CardSet& board = CardSet(0)) const { throw std::runtime_error("BadugiHandEvaluator::evaluateRanks, not implemented"); } virtual PokerEvaluation evaluateSuits(const CardSet& hand, const CardSet& board = CardSet(0)) const { throw std::runtime_error("BadugiHandEvaluator::evaluateSuits, not implemented"); } virtual size_t handSize() const { return 4; } virtual size_t boardSize() const { return 0; } virtual size_t evaluationSize() const { return 1; } virtual size_t numDraws() const { return _numDraws; } virtual void setNumDraws(size_t sz) { _numDraws = sz; } private: size_t _numDraws; }; } // namespace pokerstove #endif // PEVAL_BADUGIHANDEVALUATOR_H_
{ "content_hash": "47025c626f58174d4d500b5b16a14f07", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 103, "avg_line_length": 28.282608695652176, "alnum_prop": 0.6979246733282091, "repo_name": "andrewprock/pokerstove", "id": "ca38dfe707014f98b77ded1df83ff6a7ec0470d4", "size": "1429", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/lib/pokerstove/peval/BadugiHandEvaluator.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "19468" }, { "name": "C++", "bytes": "5117433" }, { "name": "CMake", "bytes": "32641" }, { "name": "M4", "bytes": "25387" }, { "name": "Makefile", "bytes": "25779" }, { "name": "Python", "bytes": "465582" }, { "name": "Shell", "bytes": "26517" } ], "symlink_target": "" }
from validate_app import validateApp import os from distutils import spawn import sys from parse_files import parseOutHTseq, bringTogether from bashSub import bashSub def checkPreprocessApplications(): applications = ["./contaminant_screen.sh", "./extract_unmapped_reads.py", "super_deduper", "sickle", "flash2"] for app in applications: if spawn.find_executable(app) is None: sys.stderr.write("It doesn't look like you have app - " + app + "\n") exit(0) else: sys.stderr.write(app + " found\n") def returnReads(dictSampleSeqFiles): SE = "" PE1 = "" PE2 = "" # data struct # { (sampleKey, seqKey) : [[SE], [SE], [PE1, PE2], [PE1, PE2]] } # diving into each of the sub lists in the dictionary value key for e in dictSampleSeqFiles: # if sublist only has one elment then it is SE read if len(e) == 1: if SE == "": SE = e[0] else: SE += "," + e[0] else: if PE1 == "": PE1 = e[0] PE2 = e[1] else: PE1 += "," + e[0] PE2 += "," + e[1] return [SE, PE1, PE2] def check_dir(Dir): if not os.path.exists(Dir): os.mkdir(Dir) class forcepairCMD: def __init__(self): self.metaDataFolder = "MetaData" def index(self, ref): if not os.path.exists(ref): print "Would you mind adding a gtf file? (-R) Thank you." exit(1) def execute(self, args): time = 0 logFiles = [] # checkPreprocessApplications() validate = validateApp() validate.setValidation(True) dictSampleSeqFiles = validate.validateSampleSheet(args.readFolder, args.forcepairFolder, args.samplesFile, args.force, True) for keys in dictSampleSeqFiles.keys(): check_dir(args.forcepairFolder) check_dir(keys[1]) terminal = [] #countFile = os.path.join(keys[1], keys[0].split("/")[-1]) + ".counts" print keys if (len(dictSampleSeqFiles[keys][0]) == 3): cmdString = "cp " + dictSampleSeqFiles[keys][0][0] + " " + os.path.join(keys[1], ".") + " & " cmdString += " cp " + dictSampleSeqFiles[keys][0][1] + " " + os.path.join(keys[1], ".") + ";" r1File = os.path.join(keys[1], dictSampleSeqFiles[keys][0][0].split("/")[-1]) r2File = os.path.join(keys[1], dictSampleSeqFiles[keys][0][1].split("/")[-1]) cmdString += """awk '{ printf "%s/1\\n", $0 getline print substr($0, 0, length/2) getline print $0 getline print substr($0, 0, length/2) }' """ + dictSampleSeqFiles[keys][0][2] + " >> " + r1File + " & " cmdString += """awk 'BEGIN { j = n = split("A C G T", t) for (i = 0; ++i <= n;) map[t[i]] = t[j--] } { printf "%s/2\\n", $0 getline for (i = length; i > length/2 ; i--) { printf "%s", map[substr($0, i, 1)] } printf "\\n" getline print $0 getline for (i = length; i > length/2; i--) { printf "%s", substr($0, i, 1) } printf "\\n" }' """ + dictSampleSeqFiles[keys][0][2] + " >> " + r2File terminal.append(bashSub(cmdString, [''], [''], '', '')) print terminal[-1].getCommand() terminal[-1].runCmd("") sys.stderr.flush() time += terminal[-1].returnTime() #logFiles.append(parseOutHTseq(keys[1], keys[1].split("/")[-1])) #bringTogether(logFiles, os.path.join(args.finalDir, "Counts_Summary.log")) print "Total amount of seconds to run all samples" print "Seconds: " + str(time)
{ "content_hash": "a34601f5b108f032d660ceb1cfe8f01f", "timestamp": "", "source": "github", "line_count": 125, "max_line_length": 132, "avg_line_length": 34.312, "alnum_prop": 0.45908137094893914, "repo_name": "msettles/expHTS", "id": "8d9ad50ad305f4b5bfd57f22474b942568488fcc", "size": "4289", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "expHTS/forcepairCMD.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "17319" }, { "name": "Python", "bytes": "103211" } ], "symlink_target": "" }
// Type definitions for React v15.0 // Project: http://facebook.github.io/react/ // Definitions by: Asana <https://asana.com>, AssureSign <http://www.assuresign.com>, Microsoft <https://microsoft.com>, John Reilly <https://github.com/johnnyreilly/> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export = React; export as namespace React; declare namespace React { // // React Elements // ---------------------------------------------------------------------- type ReactType = string | ComponentClass<any> | StatelessComponent<any>; type Key = string | number; type Ref<T> = string | ((instance: T) => any); type ComponentState = {} | void; interface Attributes { key?: Key; } interface ClassAttributes<T> extends Attributes { ref?: Ref<T>; } interface ReactElement<P> { type: string | ComponentClass<P> | SFC<P>; props: P; key: Key | null; } interface SFCElement<P> extends ReactElement<P> { type: SFC<P>; } type CElement<P, T extends Component<P, ComponentState>> = ComponentElement<P, T>; interface ComponentElement<P, T extends Component<P, ComponentState>> extends ReactElement<P> { type: ComponentClass<P>; ref?: Ref<T>; } type ClassicElement<P> = CElement<P, ClassicComponent<P, ComponentState>>; interface DOMElement<P extends DOMAttributes<T>, T extends Element> extends ReactElement<P> { type: string; ref: Ref<T>; } interface ReactHTMLElement<T extends HTMLElement> extends DOMElement<HTMLAttributes<T>, T> { } interface ReactSVGElement extends DOMElement<SVGAttributes<SVGElement>, SVGElement> { } // // Factories // ---------------------------------------------------------------------- interface Factory<P> { (props?: Attributes & P, ...children: ReactNode[]): ReactElement<P>; } interface SFCFactory<P> { (props?: Attributes & P, ...children: ReactNode[]): SFCElement<P>; } interface ComponentFactory<P, T extends Component<P, ComponentState>> { (props?: ClassAttributes<T> & P, ...children: ReactNode[]): CElement<P, T>; } type CFactory<P, T extends Component<P, ComponentState>> = ComponentFactory<P, T>; type ClassicFactory<P> = CFactory<P, ClassicComponent<P, ComponentState>>; interface DOMFactory<P extends DOMAttributes<T>, T extends Element> { (props?: ClassAttributes<T> & P | null, ...children: ReactNode[]): DOMElement<P, T>; } interface HTMLFactory<T extends HTMLElement> extends DOMFactory<HTMLAttributes<T>, T> { } interface SVGFactory extends DOMFactory<SVGAttributes<SVGElement>, SVGElement> { } // // React Nodes // http://facebook.github.io/react/docs/glossary.html // ---------------------------------------------------------------------- type ReactText = string | number; type ReactChild = ReactElement<any> | ReactText; // Should be Array<ReactNode> but type aliases cannot be recursive type ReactFragment = {} | Array<ReactChild | any[] | boolean>; type ReactNode = ReactChild | ReactFragment | boolean | null | undefined; // // Top Level API // ---------------------------------------------------------------------- function createClass<P, S>(spec: ComponentSpec<P, S>): ClassicComponentClass<P>; function createFactory<P extends DOMAttributes<T>, T extends Element>( type: string): DOMFactory<P, T>; function createFactory<P>(type: SFC<P>): SFCFactory<P>; function createFactory<P>( type: ClassType<P, ClassicComponent<P, ComponentState>, ClassicComponentClass<P>>): CFactory<P, ClassicComponent<P, ComponentState>>; function createFactory<P, T extends Component<P, ComponentState>, C extends ComponentClass<P>>( type: ClassType<P, T, C>): CFactory<P, T>; function createFactory<P>(type: ComponentClass<P>): Factory<P>; function createElement<P extends DOMAttributes<T>, T extends Element>( type: string, props?: ClassAttributes<T> & P, ...children: ReactNode[]): DOMElement<P, T>; function createElement<P>( type: SFC<P>, props?: Attributes & P, ...children: ReactNode[]): SFCElement<P>; function createElement<P>( type: ClassType<P, ClassicComponent<P, ComponentState>, ClassicComponentClass<P>>, props?: ClassAttributes<ClassicComponent<P, ComponentState>> & P, ...children: ReactNode[]): CElement<P, ClassicComponent<P, ComponentState>>; function createElement<P, T extends Component<P, ComponentState>, C extends ComponentClass<P>>( type: ClassType<P, T, C>, props?: ClassAttributes<T> & P, ...children: ReactNode[]): CElement<P, T>; function createElement<P>( type: ComponentClass<P>, props?: Attributes & P, ...children: ReactNode[]): ReactElement<P>; function cloneElement<P extends DOMAttributes<T>, T extends Element>( element: DOMElement<P, T>, props?: ClassAttributes<T> & P, ...children: ReactNode[]): DOMElement<P, T>; function cloneElement<P extends Q, Q>( element: SFCElement<P>, props?: Q, // should be Q & Attributes, but then Q is inferred as {} ...children: ReactNode[]): SFCElement<P>; function cloneElement<P extends Q, Q, T extends Component<P, ComponentState>>( element: CElement<P, T>, props?: Q, // should be Q & ClassAttributes<T> ...children: ReactNode[]): CElement<P, T>; function cloneElement<P extends Q, Q>( element: ReactElement<P>, props?: Q, // should be Q & Attributes ...children: ReactNode[]): ReactElement<P>; function isValidElement<P>(object: {}): object is ReactElement<P>; var DOM: ReactDOM; var PropTypes: ReactPropTypes; var Children: ReactChildren; var version: string; // // Component API // ---------------------------------------------------------------------- type ReactInstance = Component<any, any> | Element; // Base component for plain JS classes class Component<P, S> implements ComponentLifecycle<P, S> { constructor(props?: P, context?: any); constructor(...args: any[]); setState(f: (prevState: S, props: P) => S, callback?: () => any): void; setState(state: S, callback?: () => any): void; forceUpdate(callBack?: () => any): void; render(): JSX.Element | null; // React.Props<T> is now deprecated, which means that the `children` // property is not available on `P` by default, even though you can // always pass children as variadic arguments to `createElement`. // In the future, if we can define its call signature conditionally // on the existence of `children` in `P`, then we should remove this. props: { children?: ReactNode } & P; state: S; context: any; refs: { [key: string]: ReactInstance }; } class PureComponent<P, S> extends Component<P, S> { } interface ClassicComponent<P, S> extends Component<P, S> { replaceState(nextState: S, callback?: () => any): void; isMounted(): boolean; getInitialState?(): S; } interface ChildContextProvider<CC> { getChildContext(): CC; } // // Class Interfaces // ---------------------------------------------------------------------- type SFC<P> = StatelessComponent<P>; interface StatelessComponent<P> { (props: P & { children?: ReactNode }, context?: any): ReactElement<any>; propTypes?: ValidationMap<P>; contextTypes?: ValidationMap<any>; defaultProps?: P; displayName?: string; } interface ComponentClass<P> { new (props?: P, context?: any): Component<P, ComponentState>; propTypes?: ValidationMap<P>; contextTypes?: ValidationMap<any>; childContextTypes?: ValidationMap<any>; defaultProps?: P; displayName?: string; } interface ClassicComponentClass<P> extends ComponentClass<P> { new (props?: P, context?: any): ClassicComponent<P, ComponentState>; getDefaultProps?(): P; } /** * We use an intersection type to infer multiple type parameters from * a single argument, which is useful for many top-level API defs. * See https://github.com/Microsoft/TypeScript/issues/7234 for more info. */ type ClassType<P, T extends Component<P, ComponentState>, C extends ComponentClass<P>> = C & (new () => T) & (new () => { props: P }); // // Component Specs and Lifecycle // ---------------------------------------------------------------------- interface ComponentLifecycle<P, S> { componentWillMount?(): void; componentDidMount?(): void; componentWillReceiveProps?(nextProps: P, nextContext: any): void; shouldComponentUpdate?(nextProps: P, nextState: S, nextContext: any): boolean; componentWillUpdate?(nextProps: P, nextState: S, nextContext: any): void; componentDidUpdate?(prevProps: P, prevState: S, prevContext: any): void; componentWillUnmount?(): void; } interface Mixin<P, S> extends ComponentLifecycle<P, S> { mixins?: Mixin<P, S>; statics?: { [key: string]: any; }; displayName?: string; propTypes?: ValidationMap<any>; contextTypes?: ValidationMap<any>; childContextTypes?: ValidationMap<any>; getDefaultProps?(): P; getInitialState?(): S; } interface ComponentSpec<P, S> extends Mixin<P, S> { render(): ReactElement<any> | null; [propertyName: string]: any; } // // Event System // ---------------------------------------------------------------------- interface SyntheticEventBase<CURRENT, TARGET> { bubbles: boolean; currentTarget: EventTarget & CURRENT; cancelable: boolean; defaultPrevented: boolean; eventPhase: number; isTrusted: boolean; nativeEvent: Event; preventDefault(): void; isDefaultPrevented(): boolean; stopPropagation(): void; isPropagationStopped(): boolean; persist(): void; target: EventTarget & TARGET; timeStamp: Date; type: string; } interface SyntheticEvent<T> extends SyntheticEventBase<T, EventTarget> { // If you thought target should be `EventTarget & T`, // see https://github.com/DefinitelyTyped/DefinitelyTyped/pull/12239 } interface ClipboardEvent<T> extends SyntheticEvent<T> { clipboardData: DataTransfer; } interface CompositionEvent<T> extends SyntheticEvent<T> { data: string; } interface DragEvent<T> extends MouseEvent<T> { dataTransfer: DataTransfer; } interface FocusEvent<T> extends SyntheticEvent<T> { relatedTarget: EventTarget; } interface FormEvent<T> extends SyntheticEvent<T> { } interface ChangeEvent<T> extends SyntheticEventBase<T, T> { } interface KeyboardEvent<T> extends SyntheticEvent<T> { altKey: boolean; charCode: number; ctrlKey: boolean; getModifierState(key: string): boolean; key: string; keyCode: number; locale: string; location: number; metaKey: boolean; repeat: boolean; shiftKey: boolean; which: number; } interface MouseEvent<T> extends SyntheticEvent<T> { altKey: boolean; button: number; buttons: number; clientX: number; clientY: number; ctrlKey: boolean; getModifierState(key: string): boolean; metaKey: boolean; pageX: number; pageY: number; relatedTarget: EventTarget; screenX: number; screenY: number; shiftKey: boolean; } interface TouchEvent<T> extends SyntheticEvent<T> { altKey: boolean; changedTouches: TouchList; ctrlKey: boolean; getModifierState(key: string): boolean; metaKey: boolean; shiftKey: boolean; targetTouches: TouchList; touches: TouchList; } interface UIEvent<T> extends SyntheticEvent<T> { detail: number; view: AbstractView; } interface WheelEvent<T> extends MouseEvent<T> { deltaMode: number; deltaX: number; deltaY: number; deltaZ: number; } interface AnimationEvent extends SyntheticEvent<{}> { animationName: string; pseudoElement: string; elapsedTime: number; } interface TransitionEvent extends SyntheticEvent<{}> { propertyName: string; pseudoElement: string; elapsedTime: number; } // // Event Handler Types // ---------------------------------------------------------------------- interface EventHandler<E extends SyntheticEvent<any>> { (event: E): void; } type ReactEventHandler<T> = EventHandler<SyntheticEvent<T>>; type ClipboardEventHandler<T> = EventHandler<ClipboardEvent<T>>; type CompositionEventHandler<T> = EventHandler<CompositionEvent<T>>; type DragEventHandler<T> = EventHandler<DragEvent<T>>; type FocusEventHandler<T> = EventHandler<FocusEvent<T>>; type FormEventHandler<T> = EventHandler<FormEvent<T>>; type ChangeEventHandler<T> = EventHandler<ChangeEvent<T>>; type KeyboardEventHandler<T> = EventHandler<KeyboardEvent<T>>; type MouseEventHandler<T> = EventHandler<MouseEvent<T>>; type TouchEventHandler<T> = EventHandler<TouchEvent<T>>; type UIEventHandler<T> = EventHandler<UIEvent<T>>; type WheelEventHandler<T> = EventHandler<WheelEvent<T>>; type AnimationEventHandler = EventHandler<AnimationEvent>; type TransitionEventHandler = EventHandler<TransitionEvent>; // // Props / DOM Attributes // ---------------------------------------------------------------------- /** * @deprecated. This was used to allow clients to pass `ref` and `key` * to `createElement`, which is no longer necessary due to intersection * types. If you need to declare a props object before passing it to * `createElement` or a factory, use `ClassAttributes<T>`: * * ```ts * var b: Button; * var props: ButtonProps & ClassAttributes<Button> = { * ref: b => button = b, // ok! * label: "I'm a Button" * }; * ``` */ interface Props<T> { children?: ReactNode; key?: Key; ref?: Ref<T>; } interface HTMLProps<T> extends HTMLAttributes<T>, ClassAttributes<T> { } interface SVGProps extends SVGAttributes<SVGElement>, ClassAttributes<SVGElement> { } interface DOMAttributes<T> { children?: ReactNode; dangerouslySetInnerHTML?: { __html: string; }; // Clipboard Events onCopy?: ClipboardEventHandler<T>; onCopyCapture?: ClipboardEventHandler<T>; onCut?: ClipboardEventHandler<T>; onCutCapture?: ClipboardEventHandler<T>; onPaste?: ClipboardEventHandler<T>; onPasteCapture?: ClipboardEventHandler<T>; // Composition Events onCompositionEnd?: CompositionEventHandler<T>; onCompositionEndCapture?: CompositionEventHandler<T>; onCompositionStart?: CompositionEventHandler<T>; onCompositionStartCapture?: CompositionEventHandler<T>; onCompositionUpdate?: CompositionEventHandler<T>; onCompositionUpdateCapture?: CompositionEventHandler<T>; // Focus Events onFocus?: FocusEventHandler<T>; onFocusCapture?: FocusEventHandler<T>; onBlur?: FocusEventHandler<T>; onBlurCapture?: FocusEventHandler<T>; // Form Events onChange?: ChangeEventHandler<T>; onChangeCapture?: FormEventHandler<T>; onInput?: FormEventHandler<T>; onInputCapture?: FormEventHandler<T>; onReset?: FormEventHandler<T>; onResetCapture?: FormEventHandler<T>; onSubmit?: FormEventHandler<T>; onSubmitCapture?: FormEventHandler<T>; // Image Events onLoad?: ReactEventHandler<T>; onLoadCapture?: ReactEventHandler<T>; onError?: ReactEventHandler<T>; // also a Media Event onErrorCapture?: ReactEventHandler<T>; // also a Media Event // Keyboard Events onKeyDown?: KeyboardEventHandler<T>; onKeyDownCapture?: KeyboardEventHandler<T>; onKeyPress?: KeyboardEventHandler<T>; onKeyPressCapture?: KeyboardEventHandler<T>; onKeyUp?: KeyboardEventHandler<T>; onKeyUpCapture?: KeyboardEventHandler<T>; // Media Events onAbort?: ReactEventHandler<T>; onAbortCapture?: ReactEventHandler<T>; onCanPlay?: ReactEventHandler<T>; onCanPlayCapture?: ReactEventHandler<T>; onCanPlayThrough?: ReactEventHandler<T>; onCanPlayThroughCapture?: ReactEventHandler<T>; onDurationChange?: ReactEventHandler<T>; onDurationChangeCapture?: ReactEventHandler<T>; onEmptied?: ReactEventHandler<T>; onEmptiedCapture?: ReactEventHandler<T>; onEncrypted?: ReactEventHandler<T>; onEncryptedCapture?: ReactEventHandler<T>; onEnded?: ReactEventHandler<T>; onEndedCapture?: ReactEventHandler<T>; onLoadedData?: ReactEventHandler<T>; onLoadedDataCapture?: ReactEventHandler<T>; onLoadedMetadata?: ReactEventHandler<T>; onLoadedMetadataCapture?: ReactEventHandler<T>; onLoadStart?: ReactEventHandler<T>; onLoadStartCapture?: ReactEventHandler<T>; onPause?: ReactEventHandler<T>; onPauseCapture?: ReactEventHandler<T>; onPlay?: ReactEventHandler<T>; onPlayCapture?: ReactEventHandler<T>; onPlaying?: ReactEventHandler<T>; onPlayingCapture?: ReactEventHandler<T>; onProgress?: ReactEventHandler<T>; onProgressCapture?: ReactEventHandler<T>; onRateChange?: ReactEventHandler<T>; onRateChangeCapture?: ReactEventHandler<T>; onSeeked?: ReactEventHandler<T>; onSeekedCapture?: ReactEventHandler<T>; onSeeking?: ReactEventHandler<T>; onSeekingCapture?: ReactEventHandler<T>; onStalled?: ReactEventHandler<T>; onStalledCapture?: ReactEventHandler<T>; onSuspend?: ReactEventHandler<T>; onSuspendCapture?: ReactEventHandler<T>; onTimeUpdate?: ReactEventHandler<T>; onTimeUpdateCapture?: ReactEventHandler<T>; onVolumeChange?: ReactEventHandler<T>; onVolumeChangeCapture?: ReactEventHandler<T>; onWaiting?: ReactEventHandler<T>; onWaitingCapture?: ReactEventHandler<T>; // MouseEvents onClick?: MouseEventHandler<T>; onClickCapture?: MouseEventHandler<T>; onContextMenu?: MouseEventHandler<T>; onContextMenuCapture?: MouseEventHandler<T>; onDoubleClick?: MouseEventHandler<T>; onDoubleClickCapture?: MouseEventHandler<T>; onDrag?: DragEventHandler<T>; onDragCapture?: DragEventHandler<T>; onDragEnd?: DragEventHandler<T>; onDragEndCapture?: DragEventHandler<T>; onDragEnter?: DragEventHandler<T>; onDragEnterCapture?: DragEventHandler<T>; onDragExit?: DragEventHandler<T>; onDragExitCapture?: DragEventHandler<T>; onDragLeave?: DragEventHandler<T>; onDragLeaveCapture?: DragEventHandler<T>; onDragOver?: DragEventHandler<T>; onDragOverCapture?: DragEventHandler<T>; onDragStart?: DragEventHandler<T>; onDragStartCapture?: DragEventHandler<T>; onDrop?: DragEventHandler<T>; onDropCapture?: DragEventHandler<T>; onMouseDown?: MouseEventHandler<T>; onMouseDownCapture?: MouseEventHandler<T>; onMouseEnter?: MouseEventHandler<T>; onMouseLeave?: MouseEventHandler<T>; onMouseMove?: MouseEventHandler<T>; onMouseMoveCapture?: MouseEventHandler<T>; onMouseOut?: MouseEventHandler<T>; onMouseOutCapture?: MouseEventHandler<T>; onMouseOver?: MouseEventHandler<T>; onMouseOverCapture?: MouseEventHandler<T>; onMouseUp?: MouseEventHandler<T>; onMouseUpCapture?: MouseEventHandler<T>; // Selection Events onSelect?: ReactEventHandler<T>; onSelectCapture?: ReactEventHandler<T>; // Touch Events onTouchCancel?: TouchEventHandler<T>; onTouchCancelCapture?: TouchEventHandler<T>; onTouchEnd?: TouchEventHandler<T>; onTouchEndCapture?: TouchEventHandler<T>; onTouchMove?: TouchEventHandler<T>; onTouchMoveCapture?: TouchEventHandler<T>; onTouchStart?: TouchEventHandler<T>; onTouchStartCapture?: TouchEventHandler<T>; // UI Events onScroll?: UIEventHandler<T>; onScrollCapture?: UIEventHandler<T>; // Wheel Events onWheel?: WheelEventHandler<T>; onWheelCapture?: WheelEventHandler<T>; // Animation Events onAnimationStart?: AnimationEventHandler; onAnimationStartCapture?: AnimationEventHandler; onAnimationEnd?: AnimationEventHandler; onAnimationEndCapture?: AnimationEventHandler; onAnimationIteration?: AnimationEventHandler; onAnimationIterationCapture?: AnimationEventHandler; // Transition Events onTransitionEnd?: TransitionEventHandler; onTransitionEndCapture?: TransitionEventHandler; } // This interface is not complete. Only properties accepting // unitless numbers are listed here (see CSSProperty.js in React) interface CSSProperties { /** * Aligns a flex container's lines within the flex container when there is extra space in the cross-axis, similar to how justify-content aligns individual items within the main-axis. */ alignContent?: any; /** * Sets the default alignment in the cross axis for all of the flex container's items, including anonymous flex items, similarly to how justify-content aligns items along the main axis. */ alignItems?: any; /** * Allows the default alignment to be overridden for individual flex items. */ alignSelf?: any; /** * This property allows precise alignment of elements, such as graphics, that do not have a baseline-table or lack the desired baseline in their baseline-table. With the alignment-adjust property, the position of the baseline identified by the alignment-baseline can be explicitly determined. It also determines precisely the alignment point for each glyph within a textual element. */ alignmentAdjust?: any; alignmentBaseline?: any; /** * Defines a length of time to elapse before an animation starts, allowing an animation to begin execution some time after it is applied. */ animationDelay?: any; /** * Defines whether an animation should run in reverse on some or all cycles. */ animationDirection?: any; /** * Specifies how many times an animation cycle should play. */ animationIterationCount?: any; /** * Defines the list of animations that apply to the element. */ animationName?: any; /** * Defines whether an animation is running or paused. */ animationPlayState?: any; /** * Allows changing the style of any element to platform-based interface elements or vice versa. */ appearance?: any; /** * Determines whether or not the “back” side of a transformed element is visible when facing the viewer. */ backfaceVisibility?: any; /** * Shorthand property to set the values for one or more of: * background-clip, background-color, background-image, * background-origin, background-position, background-repeat, * background-size, and background-attachment. */ background?: any; /** * If a background-image is specified, this property determines * whether that image's position is fixed within the viewport, * or scrolls along with its containing block. */ backgroundAttachment?: "scroll" | "fixed" | "local"; /** * This property describes how the element's background images should blend with each other and the element's background color. * The value is a list of blend modes that corresponds to each background image. Each element in the list will apply to the corresponding element of background-image. If a property doesn’t have enough comma-separated values to match the number of layers, the UA must calculate its used value by repeating the list of values until there are enough. */ backgroundBlendMode?: any; /** * Sets the background color of an element. */ backgroundColor?: any; backgroundComposite?: any; /** * Applies one or more background images to an element. These can be any valid CSS image, including url() paths to image files or CSS gradients. */ backgroundImage?: any; /** * Specifies what the background-position property is relative to. */ backgroundOrigin?: any; /** * Sets the position of a background image. */ backgroundPosition?: any; /** * Background-repeat defines if and how background images will be repeated after they have been sized and positioned */ backgroundRepeat?: any; /** * Obsolete - spec retired, not implemented. */ baselineShift?: any; /** * Non standard. Sets or retrieves the location of the Dynamic HTML (DHTML) behavior. */ behavior?: any; /** * Shorthand property that defines the different properties of all four sides of an element's border in a single declaration. It can be used to set border-width, border-style and border-color, or a subset of these. */ border?: any; /** * Shorthand that sets the values of border-bottom-color, * border-bottom-style, and border-bottom-width. */ borderBottom?: any; /** * Sets the color of the bottom border of an element. */ borderBottomColor?: any; /** * Defines the shape of the border of the bottom-left corner. */ borderBottomLeftRadius?: any; /** * Defines the shape of the border of the bottom-right corner. */ borderBottomRightRadius?: any; /** * Sets the line style of the bottom border of a box. */ borderBottomStyle?: any; /** * Sets the width of an element's bottom border. To set all four borders, use the border-width shorthand property which sets the values simultaneously for border-top-width, border-right-width, border-bottom-width, and border-left-width. */ borderBottomWidth?: any; /** * Border-collapse can be used for collapsing the borders between table cells */ borderCollapse?: any; /** * The CSS border-color property sets the color of an element's four borders. This property can have from one to four values, made up of the elementary properties: • border-top-color * • border-right-color * • border-bottom-color * • border-left-color The default color is the currentColor of each of these values. * If you provide one value, it sets the color for the element. Two values set the horizontal and vertical values, respectively. Providing three values sets the top, vertical, and bottom values, in that order. Four values set all for sides: top, right, bottom, and left, in that order. */ borderColor?: any; /** * Specifies different corner clipping effects, such as scoop (inner curves), bevel (straight cuts) or notch (cut-off rectangles). Works along with border-radius to specify the size of each corner effect. */ borderCornerShape?: any; /** * The property border-image-source is used to set the image to be used instead of the border style. If this is set to none the border-style is used instead. */ borderImageSource?: any; /** * The border-image-width CSS property defines the offset to use for dividing the border image in nine parts, the top-left corner, central top edge, top-right-corner, central right edge, bottom-right corner, central bottom edge, bottom-left corner, and central right edge. They represent inward distance from the top, right, bottom, and left edges. */ borderImageWidth?: any; /** * Shorthand property that defines the border-width, border-style and border-color of an element's left border in a single declaration. Note that you can use the corresponding longhand properties to set specific individual properties of the left border — border-left-width, border-left-style and border-left-color. */ borderLeft?: any; /** * The CSS border-left-color property sets the color of an element's left border. This page explains the border-left-color value, but often you will find it more convenient to fix the border's left color as part of a shorthand set, either border-left or border-color. * Colors can be defined several ways. For more information, see Usage. */ borderLeftColor?: any; /** * Sets the style of an element's left border. To set all four borders, use the shorthand property, border-style. Otherwise, you can set the borders individually with border-top-style, border-right-style, border-bottom-style, border-left-style. */ borderLeftStyle?: any; /** * Sets the width of an element's left border. To set all four borders, use the border-width shorthand property which sets the values simultaneously for border-top-width, border-right-width, border-bottom-width, and border-left-width. */ borderLeftWidth?: any; /** * Shorthand property that defines the border-width, border-style and border-color of an element's right border in a single declaration. Note that you can use the corresponding longhand properties to set specific individual properties of the right border — border-right-width, border-right-style and border-right-color. */ borderRight?: any; /** * Sets the color of an element's right border. This page explains the border-right-color value, but often you will find it more convenient to fix the border's right color as part of a shorthand set, either border-right or border-color. * Colors can be defined several ways. For more information, see Usage. */ borderRightColor?: any; /** * Sets the style of an element's right border. To set all four borders, use the shorthand property, border-style. Otherwise, you can set the borders individually with border-top-style, border-right-style, border-bottom-style, border-left-style. */ borderRightStyle?: any; /** * Sets the width of an element's right border. To set all four borders, use the border-width shorthand property which sets the values simultaneously for border-top-width, border-right-width, border-bottom-width, and border-left-width. */ borderRightWidth?: any; /** * Specifies the distance between the borders of adjacent cells. */ borderSpacing?: any; /** * Sets the style of an element's four borders. This property can have from one to four values. With only one value, the value will be applied to all four borders; otherwise, this works as a shorthand property for each of border-top-style, border-right-style, border-bottom-style, border-left-style, where each border style may be assigned a separate value. */ borderStyle?: any; /** * Shorthand property that defines the border-width, border-style and border-color of an element's top border in a single declaration. Note that you can use the corresponding longhand properties to set specific individual properties of the top border — border-top-width, border-top-style and border-top-color. */ borderTop?: any; /** * Sets the color of an element's top border. This page explains the border-top-color value, but often you will find it more convenient to fix the border's top color as part of a shorthand set, either border-top or border-color. * Colors can be defined several ways. For more information, see Usage. */ borderTopColor?: any; /** * Sets the rounding of the top-left corner of the element. */ borderTopLeftRadius?: any; /** * Sets the rounding of the top-right corner of the element. */ borderTopRightRadius?: any; /** * Sets the style of an element's top border. To set all four borders, use the shorthand property, border-style. Otherwise, you can set the borders individually with border-top-style, border-right-style, border-bottom-style, border-left-style. */ borderTopStyle?: any; /** * Sets the width of an element's top border. To set all four borders, use the border-width shorthand property which sets the values simultaneously for border-top-width, border-right-width, border-bottom-width, and border-left-width. */ borderTopWidth?: any; /** * Sets the width of an element's four borders. This property can have from one to four values. This is a shorthand property for setting values simultaneously for border-top-width, border-right-width, border-bottom-width, and border-left-width. */ borderWidth?: any; /** * This property specifies how far an absolutely positioned box's bottom margin edge is offset above the bottom edge of the box's containing block. For relatively positioned boxes, the offset is with respect to the bottom edges of the box itself (i.e., the box is given a position in the normal flow, then offset from that position according to these properties). */ bottom?: any; /** * Obsolete. */ boxAlign?: any; /** * Breaks a box into fragments creating new borders, padding and repeating backgrounds or lets it stay as a continuous box on a page break, column break, or, for inline elements, at a line break. */ boxDecorationBreak?: any; /** * Deprecated */ boxDirection?: any; /** * Do not use. This property has been replaced by the flex-wrap property. * Gets or sets a value that specifies the direction to add successive rows or columns when the value of box-lines is set to multiple. */ boxLineProgression?: any; /** * Do not use. This property has been replaced by the flex-wrap property. * Gets or sets a value that specifies whether child elements wrap onto multiple lines or columns based on the space available in the object. */ boxLines?: any; /** * Do not use. This property has been replaced by flex-order. * Specifies the ordinal group that a child element of the object belongs to. This ordinal value identifies the display order (along the axis defined by the box-orient property) for the group. */ boxOrdinalGroup?: any; /** * Deprecated. */ boxFlex?: number; /** * Deprecated. */ boxFlexGroup?: number; /** * The CSS break-after property allows you to force a break on multi-column layouts. More specifically, it allows you to force a break after an element. It allows you to determine if a break should occur, and what type of break it should be. The break-after CSS property describes how the page, column or region break behaves after the generated box. If there is no generated box, the property is ignored. */ breakAfter?: any; /** * Control page/column/region breaks that fall above a block of content */ breakBefore?: any; /** * Control page/column/region breaks that fall within a block of content */ breakInside?: any; /** * The clear CSS property specifies if an element can be positioned next to or must be positioned below the floating elements that precede it in the markup. */ clear?: any; /** * Deprecated; see clip-path. * Lets you specify the dimensions of an absolutely positioned element that should be visible, and the element is clipped into this shape, and displayed. */ clip?: any; /** * Clipping crops an graphic, so that only a portion of the graphic is rendered, or filled. This clip-rule property, when used with the clip-path property, defines which clip rule, or algorithm, to use when filling the different parts of a graphics. */ clipRule?: any; /** * The color property sets the color of an element's foreground content (usually text), accepting any standard CSS color from keywords and hex values to RGB(a) and HSL(a). */ color?: any; /** * Describes the number of columns of the element. */ columnCount?: number; /** * Specifies how to fill columns (balanced or sequential). */ columnFill?: any; /** * The column-gap property controls the width of the gap between columns in multi-column elements. */ columnGap?: any; /** * Sets the width, style, and color of the rule between columns. */ columnRule?: any; /** * Specifies the color of the rule between columns. */ columnRuleColor?: any; /** * Specifies the width of the rule between columns. */ columnRuleWidth?: any; /** * The column-span CSS property makes it possible for an element to span across all columns when its value is set to all. An element that spans more than one column is called a spanning element. */ columnSpan?: any; /** * Specifies the width of columns in multi-column elements. */ columnWidth?: any; /** * This property is a shorthand property for setting column-width and/or column-count. */ columns?: any; /** * The counter-increment property accepts one or more names of counters (identifiers), each one optionally followed by an integer which specifies the value by which the counter should be incremented (e.g. if the value is 2, the counter increases by 2 each time it is invoked). */ counterIncrement?: any; /** * The counter-reset property contains a list of one or more names of counters, each one optionally followed by an integer (otherwise, the integer defaults to 0.) Each time the given element is invoked, the counters specified by the property are set to the given integer. */ counterReset?: any; /** * The cue property specifies sound files (known as an "auditory icon") to be played by speech media agents before and after presenting an element's content; if only one file is specified, it is played both before and after. The volume at which the file(s) should be played, relative to the volume of the main element, may also be specified. The icon files may also be set separately with the cue-before and cue-after properties. */ cue?: any; /** * The cue-after property specifies a sound file (known as an "auditory icon") to be played by speech media agents after presenting an element's content; the volume at which the file should be played may also be specified. The shorthand property cue sets cue sounds for both before and after the element is presented. */ cueAfter?: any; /** * Specifies the mouse cursor displayed when the mouse pointer is over an element. */ cursor?: any; /** * The direction CSS property specifies the text direction/writing direction. The rtl is used for Hebrew or Arabic text, the ltr is for other languages. */ direction?: any; /** * This property specifies the type of rendering box used for an element. It is a shorthand property for many other display properties. */ display?: any; /** * The ‘fill’ property paints the interior of the given graphical element. The area to be painted consists of any areas inside the outline of the shape. To determine the inside of the shape, all subpaths are considered, and the interior is determined according to the rules associated with the current value of the ‘fill-rule’ property. The zero-width geometric outline of a shape is included in the area to be painted. */ fill?: any; /** * SVG: Specifies the opacity of the color or the content the current object is filled with. */ fillOpacity?: number; /** * The ‘fill-rule’ property indicates the algorithm which is to be used to determine what parts of the canvas are included inside the shape. For a simple, non-intersecting path, it is intuitively clear what region lies "inside"; however, for a more complex path, such as a path that intersects itself or where one subpath encloses another, the interpretation of "inside" is not so obvious. * The ‘fill-rule’ property provides two options for how the inside of a shape is determined: */ fillRule?: any; /** * Applies various image processing effects. This property is largely unsupported. See Compatibility section for more information. */ filter?: any; /** * Shorthand for `flex-grow`, `flex-shrink`, and `flex-basis`. */ flex?: number | string; /** * Obsolete, do not use. This property has been renamed to align-items. * Specifies the alignment (perpendicular to the layout axis defined by the flex-direction property) of child elements of the object. */ flexAlign?: any; /** * The flex-basis CSS property describes the initial main size of the flex item before any free space is distributed according to the flex factors described in the flex property (flex-grow and flex-shrink). */ flexBasis?: any; /** * The flex-direction CSS property describes how flex items are placed in the flex container, by setting the direction of the flex container's main axis. */ flexDirection?: any; /** * The flex-flow CSS property defines the flex container's main and cross axis. It is a shorthand property for the flex-direction and flex-wrap properties. */ flexFlow?: any; /** * Specifies the flex grow factor of a flex item. */ flexGrow?: number; /** * Do not use. This property has been renamed to align-self * Specifies the alignment (perpendicular to the layout axis defined by flex-direction) of child elements of the object. */ flexItemAlign?: any; /** * Do not use. This property has been renamed to align-content. * Specifies how a flexbox's lines align within the flexbox when there is extra space along the axis that is perpendicular to the axis defined by the flex-direction property. */ flexLinePack?: any; /** * Gets or sets a value that specifies the ordinal group that a flexbox element belongs to. This ordinal value identifies the display order for the group. */ flexOrder?: any; /** * Specifies the flex shrink factor of a flex item. */ flexShrink?: number; /** * Elements which have the style float are floated horizontally. These elements can move as far to the left or right of the containing element. All elements after the floating element will flow around it, but elements before the floating element are not impacted. If several floating elements are placed after each other, they will float next to each other as long as there is room. */ float?: any; /** * Flows content from a named flow (specified by a corresponding flow-into) through selected elements to form a dynamic chain of layout regions. */ flowFrom?: any; /** * The font property is shorthand that allows you to do one of two things: you can either set up six of the most mature font properties in one line, or you can set one of a choice of keywords to adopt a system font setting. */ font?: any; /** * The font-family property allows one or more font family names and/or generic family names to be specified for usage on the selected element(s)' text. The browser then goes through the list; for each character in the selection it applies the first font family that has an available glyph for that character. */ fontFamily?: any; /** * The font-kerning property allows contextual adjustment of inter-glyph spacing, i.e. the spaces between the characters in text. This property controls <bold>metric kerning</bold> - that utilizes adjustment data contained in the font. Optical Kerning is not supported as yet. */ fontKerning?: any; /** * Specifies the size of the font. Used to compute em and ex units. */ fontSize?: number | string; /** * The font-size-adjust property adjusts the font-size of the fallback fonts defined with font-family, so that the x-height is the same no matter what font is used. This preserves the readability of the text when fallback happens. */ fontSizeAdjust?: any; /** * Allows you to expand or condense the widths for a normal, condensed, or expanded font face. */ fontStretch?: any; /** * The font-style property allows normal, italic, or oblique faces to be selected. Italic forms are generally cursive in nature while oblique faces are typically sloped versions of the regular face. Oblique faces can be simulated by artificially sloping the glyphs of the regular face. */ fontStyle?: any; /** * This value specifies whether the user agent is allowed to synthesize bold or oblique font faces when a font family lacks bold or italic faces. */ fontSynthesis?: any; /** * The font-variant property enables you to select the small-caps font within a font family. */ fontVariant?: any; /** * Fonts can provide alternate glyphs in addition to default glyph for a character. This property provides control over the selection of these alternate glyphs. */ fontVariantAlternates?: any; /** * Specifies the weight or boldness of the font. */ fontWeight?: "normal" | "bold" | "lighter" | "bolder" | number; /** * Lays out one or more grid items bound by 4 grid lines. Shorthand for setting grid-column-start, grid-column-end, grid-row-start, and grid-row-end in a single declaration. */ gridArea?: any; /** * Controls a grid item's placement in a grid area, particularly grid position and a grid span. Shorthand for setting grid-column-start and grid-column-end in a single declaration. */ gridColumn?: any; /** * Controls a grid item's placement in a grid area as well as grid position and a grid span. The grid-column-end property (with grid-row-start, grid-row-end, and grid-column-start) determines a grid item's placement by specifying the grid lines of a grid item's grid area. */ gridColumnEnd?: any; /** * Determines a grid item's placement by specifying the starting grid lines of a grid item's grid area . A grid item's placement in a grid area consists of a grid position and a grid span. See also ( grid-row-start, grid-row-end, and grid-column-end) */ gridColumnStart?: any; /** * Gets or sets a value that indicates which row an element within a Grid should appear in. Shorthand for setting grid-row-start and grid-row-end in a single declaration. */ gridRow?: any; /** * Determines a grid item’s placement by specifying the block-end. A grid item's placement in a grid area consists of a grid position and a grid span. The grid-row-end property (with grid-row-start, grid-column-start, and grid-column-end) determines a grid item's placement by specifying the grid lines of a grid item's grid area. */ gridRowEnd?: any; /** * Specifies a row position based upon an integer location, string value, or desired row size. * css/properties/grid-row is used as short-hand for grid-row-position and grid-row-position */ gridRowPosition?: any; gridRowSpan?: any; /** * Specifies named grid areas which are not associated with any particular grid item, but can be referenced from the grid-placement properties. The syntax of the grid-template-areas property also provides a visualization of the structure of the grid, making the overall layout of the grid container easier to understand. */ gridTemplateAreas?: any; /** * Specifies (with grid-template-rows) the line names and track sizing functions of the grid. Each sizing function can be specified as a length, a percentage of the grid container’s size, a measurement of the contents occupying the column or row, or a fraction of the free space in the grid. */ gridTemplateColumns?: any; /** * Specifies (with grid-template-columns) the line names and track sizing functions of the grid. Each sizing function can be specified as a length, a percentage of the grid container’s size, a measurement of the contents occupying the column or row, or a fraction of the free space in the grid. */ gridTemplateRows?: any; /** * Sets the height of an element. The content area of the element height does not include the padding, border, and margin of the element. */ height?: any; /** * Specifies the minimum number of characters in a hyphenated word */ hyphenateLimitChars?: any; /** * Indicates the maximum number of successive hyphenated lines in an element. The ‘no-limit’ value means that there is no limit. */ hyphenateLimitLines?: any; /** * Specifies the maximum amount of trailing whitespace (before justification) that may be left in a line before hyphenation is triggered to pull part of a word from the next line back up into the current one. */ hyphenateLimitZone?: any; /** * Specifies whether or not words in a sentence can be split by the use of a manual or automatic hyphenation mechanism. */ hyphens?: any; imeMode?: any; /** * Defines how the browser distributes space between and around flex items * along the main-axis of their container. */ justifyContent?: "flex-start" | "flex-end" | "center" | "space-between" | "space-around"; layoutGrid?: any; layoutGridChar?: any; layoutGridLine?: any; layoutGridMode?: any; layoutGridType?: any; /** * Sets the left edge of an element */ left?: any; /** * The letter-spacing CSS property specifies the spacing behavior between text characters. */ letterSpacing?: any; /** * Deprecated. Gets or sets line-breaking rules for text in selected languages such as Japanese, Chinese, and Korean. */ lineBreak?: any; lineClamp?: number; /** * Specifies the height of an inline block level element. */ lineHeight?: number | string; /** * Shorthand property that sets the list-style-type, list-style-position and list-style-image properties in one declaration. */ listStyle?: any; /** * This property sets the image that will be used as the list item marker. When the image is available, it will replace the marker set with the 'list-style-type' marker. That also means that if the image is not available, it will show the style specified by list-style-property */ listStyleImage?: any; /** * Specifies if the list-item markers should appear inside or outside the content flow. */ listStylePosition?: any; /** * Specifies the type of list-item marker in a list. */ listStyleType?: any; /** * The margin property is shorthand to allow you to set all four margins of an element at once. Its equivalent longhand properties are margin-top, margin-right, margin-bottom and margin-left. Negative values are also allowed. */ margin?: any; /** * margin-bottom sets the bottom margin of an element. */ marginBottom?: any; /** * margin-left sets the left margin of an element. */ marginLeft?: any; /** * margin-right sets the right margin of an element. */ marginRight?: any; /** * margin-top sets the top margin of an element. */ marginTop?: any; /** * The marquee-direction determines the initial direction in which the marquee content moves. */ marqueeDirection?: any; /** * The 'marquee-style' property determines a marquee's scrolling behavior. */ marqueeStyle?: any; /** * This property is shorthand for setting mask-image, mask-mode, mask-repeat, mask-position, mask-clip, mask-origin, mask-composite and mask-size. Omitted values are set to their original properties' initial values. */ mask?: any; /** * This property is shorthand for setting mask-border-source, mask-border-slice, mask-border-width, mask-border-outset, and mask-border-repeat. Omitted values are set to their original properties' initial values. */ maskBorder?: any; /** * This property specifies how the images for the sides and the middle part of the mask image are scaled and tiled. The first keyword applies to the horizontal sides, the second one applies to the vertical ones. If the second keyword is absent, it is assumed to be the same as the first, similar to the CSS border-image-repeat property. */ maskBorderRepeat?: any; /** * This property specifies inward offsets from the top, right, bottom, and left edges of the mask image, dividing it into nine regions: four corners, four edges, and a middle. The middle image part is discarded and treated as fully transparent black unless the fill keyword is present. The four values set the top, right, bottom and left offsets in that order, similar to the CSS border-image-slice property. */ maskBorderSlice?: any; /** * Specifies an image to be used as a mask. An image that is empty, fails to download, is non-existent, or cannot be displayed is ignored and does not mask the element. */ maskBorderSource?: any; /** * This property sets the width of the mask box image, similar to the CSS border-image-width property. */ maskBorderWidth?: any; /** * Determines the mask painting area, which defines the area that is affected by the mask. The painted content of an element may be restricted to this area. */ maskClip?: any; /** * For elements rendered as a single box, specifies the mask positioning area. For elements rendered as multiple boxes (e.g., inline boxes on several lines, boxes on several pages) specifies which boxes box-decoration-break operates on to determine the mask positioning area(s). */ maskOrigin?: any; /** * This property must not be used. It is no longer included in any standard or standard track specification, nor is it implemented in any browser. It is only used when the text-align-last property is set to size. It controls allowed adjustments of font-size to fit line content. */ maxFontSize?: any; /** * Sets the maximum height for an element. It prevents the height of the element to exceed the specified value. If min-height is specified and is greater than max-height, max-height is overridden. */ maxHeight?: any; /** * Sets the maximum width for an element. It limits the width property to be larger than the value specified in max-width. */ maxWidth?: any; /** * Sets the minimum height for an element. It prevents the height of the element to be smaller than the specified value. The value of min-height overrides both max-height and height. */ minHeight?: any; /** * Sets the minimum width of an element. It limits the width property to be not smaller than the value specified in min-width. */ minWidth?: any; /** * Specifies the transparency of an element. */ opacity?: number; /** * Specifies the order used to lay out flex items in their flex container. * Elements are laid out in the ascending order of the order value. */ order?: number; /** * In paged media, this property defines the minimum number of lines in * a block container that must be left at the bottom of the page. */ orphans?: number; /** * The CSS outline property is a shorthand property for setting one or more of the individual outline properties outline-style, outline-width and outline-color in a single rule. In most cases the use of this shortcut is preferable and more convenient. * Outlines differ from borders in the following ways: • Outlines do not take up space, they are drawn above the content. * • Outlines may be non-rectangular. They are rectangular in Gecko/Firefox. Internet Explorer attempts to place the smallest contiguous outline around all elements or shapes that are indicated to have an outline. Opera draws a non-rectangular shape around a construct. */ outline?: any; /** * The outline-color property sets the color of the outline of an element. An outline is a line that is drawn around elements, outside the border edge, to make the element stand out. */ outlineColor?: any; /** * The outline-offset property offsets the outline and draw it beyond the border edge. */ outlineOffset?: any; /** * The overflow property controls how extra content exceeding the bounding box of an element is rendered. It can be used in conjunction with an element that has a fixed width and height, to eliminate text-induced page distortion. */ overflow?: any; /** * Specifies the preferred scrolling methods for elements that overflow. */ overflowStyle?: any; /** * Controls how extra content exceeding the x-axis of the bounding box of an element is rendered. */ overflowX?: any; /** * Controls how extra content exceeding the y-axis of the bounding box of an element is rendered. */ overflowY?: any; /** * The padding optional CSS property sets the required padding space on one to four sides of an element. The padding area is the space between an element and its border. Negative values are not allowed but decimal values are permitted. The element size is treated as fixed, and the content of the element shifts toward the center as padding is increased. * The padding property is a shorthand to avoid setting each side separately (padding-top, padding-right, padding-bottom, padding-left). */ padding?: any; /** * The padding-bottom CSS property of an element sets the padding space required on the bottom of an element. The padding area is the space between the content of the element and its border. Contrary to margin-bottom values, negative values of padding-bottom are invalid. */ paddingBottom?: any; /** * The padding-left CSS property of an element sets the padding space required on the left side of an element. The padding area is the space between the content of the element and its border. Contrary to margin-left values, negative values of padding-left are invalid. */ paddingLeft?: any; /** * The padding-right CSS property of an element sets the padding space required on the right side of an element. The padding area is the space between the content of the element and its border. Contrary to margin-right values, negative values of padding-right are invalid. */ paddingRight?: any; /** * The padding-top CSS property of an element sets the padding space required on the top of an element. The padding area is the space between the content of the element and its border. Contrary to margin-top values, negative values of padding-top are invalid. */ paddingTop?: any; /** * The page-break-after property is supported in all major browsers. With CSS3, page-break-* properties are only aliases of the break-* properties. The CSS3 Fragmentation spec defines breaks for all CSS box fragmentation. */ pageBreakAfter?: any; /** * The page-break-before property sets the page-breaking behavior before an element. With CSS3, page-break-* properties are only aliases of the break-* properties. The CSS3 Fragmentation spec defines breaks for all CSS box fragmentation. */ pageBreakBefore?: any; /** * Sets the page-breaking behavior inside an element. With CSS3, page-break-* properties are only aliases of the break-* properties. The CSS3 Fragmentation spec defines breaks for all CSS box fragmentation. */ pageBreakInside?: any; /** * The pause property determines how long a speech media agent should pause before and after presenting an element. It is a shorthand for the pause-before and pause-after properties. */ pause?: any; /** * The pause-after property determines how long a speech media agent should pause after presenting an element. It may be replaced by the shorthand property pause, which sets pause time before and after. */ pauseAfter?: any; /** * The pause-before property determines how long a speech media agent should pause before presenting an element. It may be replaced by the shorthand property pause, which sets pause time before and after. */ pauseBefore?: any; /** * The perspective property defines how far an element is placed from the view on the z-axis, from the screen to the viewer. * Perspective defines how an object is viewed. In graphic arts, perspective is the representation on a flat surface of what the viewer's eye would see in a 3D space. (See Wikipedia for more information about graphical perspective and for related illustrations.) * The illusion of perspective on a flat surface, such as a computer screen, is created by projecting points on the flat surface as they would appear if the flat surface were a window through which the viewer was looking at the object. In discussion of virtual environments, this flat surface is called a projection plane. */ perspective?: any; /** * The perspective-origin property establishes the origin for the perspective property. It effectively sets the X and Y position at which the viewer appears to be looking at the children of the element. * When used with perspective, perspective-origin changes the appearance of an object, as if a viewer were looking at it from a different origin. An object appears differently if a viewer is looking directly at it versus looking at it from below, above, or from the side. Thus, the perspective-origin is like a vanishing point. * The default value of perspective-origin is 50% 50%. This displays an object as if the viewer's eye were positioned directly at the center of the screen, both top-to-bottom and left-to-right. A value of 0% 0% changes the object as if the viewer was looking toward the top left angle. A value of 100% 100% changes the appearance as if viewed toward the bottom right angle. */ perspectiveOrigin?: any; /** * The pointer-events property allows you to control whether an element can be the target for the pointing device (e.g, mouse, pen) events. */ pointerEvents?: any; /** * The position property controls the type of positioning used by an element within its parent elements. The effect of the position property depends on a lot of factors, for example the position property of parent elements. */ position?: any; /** * Obsolete: unsupported. * This property determines whether or not a full-width punctuation mark character should be trimmed if it appears at the beginning of a line, so that its "ink" lines up with the first glyph in the line above and below. */ punctuationTrim?: any; /** * Sets the type of quotation marks for embedded quotations. */ quotes?: any; /** * Controls whether the last region in a chain displays additional 'overset' content according its default overflow property, or if it displays a fragment of content as if it were flowing into a subsequent region. */ regionFragment?: any; /** * The rest-after property determines how long a speech media agent should pause after presenting an element's main content, before presenting that element's exit cue sound. It may be replaced by the shorthand property rest, which sets rest time before and after. */ restAfter?: any; /** * The rest-before property determines how long a speech media agent should pause after presenting an intro cue sound for an element, before presenting that element's main content. It may be replaced by the shorthand property rest, which sets rest time before and after. */ restBefore?: any; /** * Specifies the position an element in relation to the right side of the containing element. */ right?: any; rubyAlign?: any; rubyPosition?: any; /** * Defines the alpha channel threshold used to extract a shape from an image. Can be thought of as a "minimum opacity" threshold; that is, a value of 0.5 means that the shape will enclose all the pixels that are more than 50% opaque. */ shapeImageThreshold?: any; /** * A future level of CSS Shapes will define a shape-inside property, which will define a shape to wrap content within the element. See Editor's Draft <http://dev.w3.org/csswg/css-shapes/> and CSSWG wiki page on next-level plans <http://wiki.csswg.org/spec/css-shapes> */ shapeInside?: any; /** * Adds a margin to a shape-outside. In effect, defines a new shape that is the smallest contour around all the points that are the shape-margin distance outward perpendicular to each point on the underlying shape. For points where a perpendicular direction is not defined (e.g., a triangle corner), takes all points on a circle centered at the point and with a radius of the shape-margin distance. This property accepts only non-negative values. */ shapeMargin?: any; /** * Declares a shape around which text should be wrapped, with possible modifications from the shape-margin property. The shape defined by shape-outside and shape-margin changes the geometry of a float element's float area. */ shapeOutside?: any; /** * The speak property determines whether or not a speech synthesizer will read aloud the contents of an element. */ speak?: any; /** * The speak-as property determines how the speech synthesizer interprets the content: words as whole words or as a sequence of letters, numbers as a numerical value or a sequence of digits, punctuation as pauses in speech or named punctuation characters. */ speakAs?: any; /** * SVG: Specifies the opacity of the outline on the current object. */ strokeOpacity?: number; /** * SVG: Specifies the width of the outline on the current object. */ strokeWidth?: number; /** * The tab-size CSS property is used to customise the width of a tab (U+0009) character. */ tabSize?: any; /** * The 'table-layout' property controls the algorithm used to lay out the table cells, rows, and columns. */ tableLayout?: any; /** * The text-align CSS property describes how inline content like text is aligned in its parent block element. text-align does not control the alignment of block elements itself, only their inline content. */ textAlign?: any; /** * The text-align-last CSS property describes how the last line of a block element or a line before line break is aligned in its parent block element. */ textAlignLast?: any; /** * The text-decoration CSS property is used to set the text formatting to underline, overline, line-through or blink. * underline and overline decorations are positioned under the text, line-through over it. */ textDecoration?: any; /** * Sets the color of any text decoration, such as underlines, overlines, and strike throughs. */ textDecorationColor?: any; /** * Sets what kind of line decorations are added to an element, such as underlines, overlines, etc. */ textDecorationLine?: any; textDecorationLineThrough?: any; textDecorationNone?: any; textDecorationOverline?: any; /** * Specifies what parts of an element’s content are skipped over when applying any text decoration. */ textDecorationSkip?: any; /** * This property specifies the style of the text decoration line drawn on the specified element. The intended meaning for the values are the same as those of the border-style-properties. */ textDecorationStyle?: any; textDecorationUnderline?: any; /** * The text-emphasis property will apply special emphasis marks to the elements text. Slightly similar to the text-decoration property only that this property can have affect on the line-height. It also is noted that this is shorthand for text-emphasis-style and for text-emphasis-color. */ textEmphasis?: any; /** * The text-emphasis-color property specifies the foreground color of the emphasis marks. */ textEmphasisColor?: any; /** * The text-emphasis-style property applies special emphasis marks to an element's text. */ textEmphasisStyle?: any; /** * This property helps determine an inline box's block-progression dimension, derived from the text-height and font-size properties for non-replaced elements, the height or the width for replaced elements, and the stacked block-progression dimension for inline-block elements. The block-progression dimension determines the position of the padding, border and margin for the element. */ textHeight?: any; /** * Specifies the amount of space horizontally that should be left on the first line of the text of an element. This horizontal spacing is at the beginning of the first line and is in respect to the left edge of the containing block box. */ textIndent?: any; textJustifyTrim?: any; textKashidaSpace?: any; /** * The text-line-through property is a shorthand property for text-line-through-style, text-line-through-color and text-line-through-mode. (Considered obsolete; use text-decoration instead.) */ textLineThrough?: any; /** * Specifies the line colors for the line-through text decoration. * (Considered obsolete; use text-decoration-color instead.) */ textLineThroughColor?: any; /** * Sets the mode for the line-through text decoration, determining whether the text decoration affects the space characters or not. * (Considered obsolete; use text-decoration-skip instead.) */ textLineThroughMode?: any; /** * Specifies the line style for line-through text decoration. * (Considered obsolete; use text-decoration-style instead.) */ textLineThroughStyle?: any; /** * Specifies the line width for the line-through text decoration. */ textLineThroughWidth?: any; /** * The text-overflow shorthand CSS property determines how overflowed content that is not displayed is signaled to the users. It can be clipped, display an ellipsis ('…', U+2026 HORIZONTAL ELLIPSIS) or a Web author-defined string. It covers the two long-hand properties text-overflow-mode and text-overflow-ellipsis */ textOverflow?: any; /** * The text-overline property is the shorthand for the text-overline-style, text-overline-width, text-overline-color, and text-overline-mode properties. */ textOverline?: any; /** * Specifies the line color for the overline text decoration. */ textOverlineColor?: any; /** * Sets the mode for the overline text decoration, determining whether the text decoration affects the space characters or not. */ textOverlineMode?: any; /** * Specifies the line style for overline text decoration. */ textOverlineStyle?: any; /** * Specifies the line width for the overline text decoration. */ textOverlineWidth?: any; /** * The text-rendering CSS property provides information to the browser about how to optimize when rendering text. Options are: legibility, speed or geometric precision. */ textRendering?: any; /** * Obsolete: unsupported. */ textScript?: any; /** * The CSS text-shadow property applies one or more drop shadows to the text and <text-decorations> of an element. Each shadow is specified as an offset from the text, along with optional color and blur radius values. */ textShadow?: any; /** * This property transforms text for styling purposes. (It has no effect on the underlying content.) */ textTransform?: any; /** * Unsupported. * This property will add a underline position value to the element that has an underline defined. */ textUnderlinePosition?: any; /** * After review this should be replaced by text-decoration should it not? * This property will set the underline style for text with a line value for underline, overline, and line-through. */ textUnderlineStyle?: any; /** * This property specifies how far an absolutely positioned box's top margin edge is offset below the top edge of the box's containing block. For relatively positioned boxes, the offset is with respect to the top edges of the box itself (i.e., the box is given a position in the normal flow, then offset from that position according to these properties). */ top?: any; /** * Determines whether touch input may trigger default behavior supplied by the user agent, such as panning or zooming. */ touchAction?: any; /** * CSS transforms allow elements styled with CSS to be transformed in two-dimensional or three-dimensional space. Using this property, elements can be translated, rotated, scaled, and skewed. The value list may consist of 2D and/or 3D transform values. */ transform?: any; /** * This property defines the origin of the transformation axes relative to the element to which the transformation is applied. */ transformOrigin?: any; /** * This property allows you to define the relative position of the origin of the transformation grid along the z-axis. */ transformOriginZ?: any; /** * This property specifies how nested elements are rendered in 3D space relative to their parent. */ transformStyle?: any; /** * The transition CSS property is a shorthand property for transition-property, transition-duration, transition-timing-function, and transition-delay. It allows to define the transition between two states of an element. */ transition?: any; /** * Defines when the transition will start. A value of ‘0s’ means the transition will execute as soon as the property is changed. Otherwise, the value specifies an offset from the moment the property is changed, and the transition will delay execution by that offset. */ transitionDelay?: any; /** * The 'transition-duration' property specifies the length of time a transition animation takes to complete. */ transitionDuration?: any; /** * The 'transition-property' property specifies the name of the CSS property to which the transition is applied. */ transitionProperty?: any; /** * Sets the pace of action within a transition */ transitionTimingFunction?: any; /** * The unicode-bidi CSS property specifies the level of embedding with respect to the bidirectional algorithm. */ unicodeBidi?: any; /** * unicode-range allows you to set a specific range of characters to be downloaded from a font (embedded using @font-face) and made available for use on the current page. */ unicodeRange?: any; /** * This is for all the high level UX stuff. */ userFocus?: any; /** * For inputing user content */ userInput?: any; /** * The vertical-align property controls how inline elements or text are vertically aligned compared to the baseline. If this property is used on table-cells it controls the vertical alignment of content of the table cell. */ verticalAlign?: any; /** * The visibility property specifies whether the boxes generated by an element are rendered. */ visibility?: any; /** * The voice-balance property sets the apparent position (in stereo sound) of the synthesized voice for spoken media. */ voiceBalance?: any; /** * The voice-duration property allows the author to explicitly set the amount of time it should take a speech synthesizer to read an element's content, for example to allow the speech to be synchronized with other media. With a value of auto (the default) the length of time it takes to read the content is determined by the content itself and the voice-rate property. */ voiceDuration?: any; /** * The voice-family property sets the speaker's voice used by a speech media agent to read an element. The speaker may be specified as a named character (to match a voice option in the speech reading software) or as a generic description of the age and gender of the voice. Similar to the font-family property for visual media, a comma-separated list of fallback options may be given in case the speech reader does not recognize the character name or cannot synthesize the requested combination of generic properties. */ voiceFamily?: any; /** * The voice-pitch property sets pitch or tone (high or low) for the synthesized speech when reading an element; the pitch may be specified absolutely or relative to the normal pitch for the voice-family used to read the text. */ voicePitch?: any; /** * The voice-range property determines how much variation in pitch or tone will be created by the speech synthesize when reading an element. Emphasized text, grammatical structures and punctuation may all be rendered as changes in pitch, this property determines how strong or obvious those changes are; large ranges are associated with enthusiastic or emotional speech, while small ranges are associated with flat or mechanical speech. */ voiceRange?: any; /** * The voice-rate property sets the speed at which the voice synthesized by a speech media agent will read content. */ voiceRate?: any; /** * The voice-stress property sets the level of vocal emphasis to be used for synthesized speech reading the element. */ voiceStress?: any; /** * The voice-volume property sets the volume for spoken content in speech media. It replaces the deprecated volume property. */ voiceVolume?: any; /** * The white-space property controls whether and how white space inside the element is collapsed, and whether lines may wrap at unforced "soft wrap" opportunities. */ whiteSpace?: any; /** * Obsolete: unsupported. */ whiteSpaceTreatment?: any; /** * In paged media, this property defines the mimimum number of lines * that must be left at the top of the second page. */ widows?: number; /** * Specifies the width of the content area of an element. The content area of the element width does not include the padding, border, and margin of the element. */ width?: any; /** * The word-break property is often used when there is long generated content that is strung together without and spaces or hyphens to beak apart. A common case of this is when there is a long URL that does not have any hyphens. This case could potentially cause the breaking of the layout as it could extend past the parent element. */ wordBreak?: any; /** * The word-spacing CSS property specifies the spacing behavior between "words". */ wordSpacing?: any; /** * An alias of css/properties/overflow-wrap, word-wrap defines whether to break words when the content exceeds the boundaries of its container. */ wordWrap?: any; /** * Specifies how exclusions affect inline content within block-level elements. Elements lay out their inline content in their content area but wrap around exclusion areas. */ wrapFlow?: any; /** * Set the value that is used to offset the inner wrap shape from other shapes. Inline content that intersects a shape with this property will be pushed by this shape's margin. */ wrapMargin?: any; /** * Obsolete and unsupported. Do not use. * This CSS property controls the text when it reaches the end of the block in which it is enclosed. */ wrapOption?: any; /** * writing-mode specifies if lines of text are laid out horizontally or vertically, and the direction which lines of text and blocks progress. */ writingMode?: any; /** * The z-index property specifies the z-order of an element and its descendants. * When elements overlap, z-order determines which one covers the other. */ zIndex?: "auto" | number; /** * Sets the initial zoom factor of a document defined by @viewport. */ zoom?: "auto" | number; [propertyName: string]: any; } interface HTMLAttributes<T> extends DOMAttributes<T> { // React-specific Attributes defaultChecked?: boolean; defaultValue?: string | string[]; // Standard HTML Attributes accept?: string; acceptCharset?: string; accessKey?: string; action?: string; allowFullScreen?: boolean; allowTransparency?: boolean; alt?: string; async?: boolean; autoComplete?: string; autoFocus?: boolean; autoPlay?: boolean; capture?: boolean; cellPadding?: number | string; cellSpacing?: number | string; charSet?: string; challenge?: string; checked?: boolean; classID?: string; className?: string; cols?: number; colSpan?: number; content?: string; contentEditable?: boolean; contextMenu?: string; controls?: boolean; coords?: string; crossOrigin?: string; data?: string; dateTime?: string; default?: boolean; defer?: boolean; dir?: string; disabled?: boolean; download?: any; draggable?: boolean; encType?: string; form?: string; formAction?: string; formEncType?: string; formMethod?: string; formNoValidate?: boolean; formTarget?: string; frameBorder?: number | string; headers?: string; height?: number | string; hidden?: boolean; high?: number; href?: string; hrefLang?: string; htmlFor?: string; httpEquiv?: string; id?: string; inputMode?: string; integrity?: string; is?: string; keyParams?: string; keyType?: string; kind?: string; label?: string; lang?: string; list?: string; loop?: boolean; low?: number; manifest?: string; marginHeight?: number; marginWidth?: number; max?: number | string; maxLength?: number; media?: string; mediaGroup?: string; method?: string; min?: number | string; minLength?: number; multiple?: boolean; muted?: boolean; name?: string; nonce?: string; noValidate?: boolean; open?: boolean; optimum?: number; pattern?: string; placeholder?: string; playsInline?: boolean; poster?: string; preload?: string; radioGroup?: string; readOnly?: boolean; rel?: string; required?: boolean; reversed?: boolean; role?: string; rows?: number; rowSpan?: number; sandbox?: string; scope?: string; scoped?: boolean; scrolling?: string; seamless?: boolean; selected?: boolean; shape?: string; size?: number; sizes?: string; span?: number; spellCheck?: boolean; src?: string; srcDoc?: string; srcLang?: string; srcSet?: string; start?: number; step?: number | string; style?: CSSProperties; summary?: string; tabIndex?: number; target?: string; title?: string; type?: string; useMap?: string; value?: string | string[] | number; width?: number | string; wmode?: string; wrap?: string; // RDFa Attributes about?: string; datatype?: string; inlist?: any; prefix?: string; property?: string; resource?: string; typeof?: string; vocab?: string; // Non-standard Attributes autoCapitalize?: string; autoCorrect?: string; autoSave?: string; color?: string; itemProp?: string; itemScope?: boolean; itemType?: string; itemID?: string; itemRef?: string; results?: number; security?: string; unselectable?: boolean; } // this list is "complete" in that it contains every SVG attribute // that React supports, but the types can be improved. // Full list here: https://facebook.github.io/react/docs/dom-elements.html // // The three broad type categories are (in order of restrictiveness): // - "number | string" // - "string" // - union of string literals interface SVGAttributes<T> extends HTMLAttributes<T> { accentHeight?: number | string; accumulate?: "none" | "sum"; additive?: "replace" | "sum"; alignmentBaseline?: "auto" | "baseline" | "before-edge" | "text-before-edge" | "middle" | "central" | "after-edge" | "text-after-edge" | "ideographic" | "alphabetic" | "hanging" | "mathematical" | "inherit"; allowReorder?: "no" | "yes"; alphabetic?: number | string; amplitude?: number | string; arabicForm?: "initial" | "medial" | "terminal" | "isolated"; ascent?: number | string; attributeName?: string; attributeType?: string; autoReverse?: number | string; azimuth?: number | string; baseFrequency?: number | string; baselineShift?: number | string; baseProfile?: number | string; bbox?: number | string; begin?: number | string; bias?: number | string; by?: number | string; calcMode?: number | string; capHeight?: number | string; clip?: number | string; clipPath?: string; clipPathUnits?: number | string; clipRule?: number | string; colorInterpolation?: number | string; colorInterpolationFilters?: "auto" | "sRGB" | "linearRGB" | "inherit"; colorProfile?: number | string; colorRendering?: number | string; contentScriptType?: number | string; contentStyleType?: number | string; cursor?: number | string; cx?: number | string; cy?: number | string; d?: string; decelerate?: number | string; descent?: number | string; diffuseConstant?: number | string; direction?: number | string; display?: number | string; divisor?: number | string; dominantBaseline?: number | string; dur?: number | string; dx?: number | string; dy?: number | string; edgeMode?: number | string; elevation?: number | string; enableBackground?: number | string; end?: number | string; exponent?: number | string; externalResourcesRequired?: number | string; fill?: string; fillOpacity?: number | string; fillRule?: "nonzero" | "evenodd" | "inherit"; filter?: string; filterRes?: number | string; filterUnits?: number | string; floodColor?: number | string; floodOpacity?: number | string; focusable?: number | string; fontFamily?: string; fontSize?: number | string; fontSizeAdjust?: number | string; fontStretch?: number | string; fontStyle?: number | string; fontVariant?: number | string; fontWeight?: number | string; format?: number | string; from?: number | string; fx?: number | string; fy?: number | string; g1?: number | string; g2?: number | string; glyphName?: number | string; glyphOrientationHorizontal?: number | string; glyphOrientationVertical?: number | string; glyphRef?: number | string; gradientTransform?: string; gradientUnits?: string; hanging?: number | string; horizAdvX?: number | string; horizOriginX?: number | string; ideographic?: number | string; imageRendering?: number | string; in2?: number | string; in?: string; intercept?: number | string; k1?: number | string; k2?: number | string; k3?: number | string; k4?: number | string; k?: number | string; kernelMatrix?: number | string; kernelUnitLength?: number | string; kerning?: number | string; keyPoints?: number | string; keySplines?: number | string; keyTimes?: number | string; lengthAdjust?: number | string; letterSpacing?: number | string; lightingColor?: number | string; limitingConeAngle?: number | string; local?: number | string; markerEnd?: string; markerHeight?: number | string; markerMid?: string; markerStart?: string; markerUnits?: number | string; markerWidth?: number | string; mask?: string; maskContentUnits?: number | string; maskUnits?: number | string; mathematical?: number | string; mode?: number | string; numOctaves?: number | string; offset?: number | string; opacity?: number | string; operator?: number | string; order?: number | string; orient?: number | string; orientation?: number | string; origin?: number | string; overflow?: number | string; overlinePosition?: number | string; overlineThickness?: number | string; paintOrder?: number | string; panose1?: number | string; pathLength?: number | string; patternContentUnits?: string; patternTransform?: number | string; patternUnits?: string; pointerEvents?: number | string; points?: string; pointsAtX?: number | string; pointsAtY?: number | string; pointsAtZ?: number | string; preserveAlpha?: number | string; preserveAspectRatio?: string; primitiveUnits?: number | string; r?: number | string; radius?: number | string; refX?: number | string; refY?: number | string; renderingIntent?: number | string; repeatCount?: number | string; repeatDur?: number | string; requiredExtensions?: number | string; requiredFeatures?: number | string; restart?: number | string; result?: string; rotate?: number | string; rx?: number | string; ry?: number | string; scale?: number | string; seed?: number | string; shapeRendering?: number | string; slope?: number | string; spacing?: number | string; specularConstant?: number | string; specularExponent?: number | string; speed?: number | string; spreadMethod?: string; startOffset?: number | string; stdDeviation?: number | string stemh?: number | string; stemv?: number | string; stitchTiles?: number | string; stopColor?: string; stopOpacity?: number | string; strikethroughPosition?: number | string; strikethroughThickness?: number | string; string?: number | string; stroke?: string; strokeDasharray?: string | number; strokeDashoffset?: string | number; strokeLinecap?: "butt" | "round" | "square" | "inherit"; strokeLinejoin?: "miter" | "round" | "bevel" | "inherit"; strokeMiterlimit?: string; strokeOpacity?: number | string; strokeWidth?: number | string; surfaceScale?: number | string; systemLanguage?: number | string; tableValues?: number | string; targetX?: number | string; targetY?: number | string; textAnchor?: string; textDecoration?: number | string; textLength?: number | string; textRendering?: number | string; to?: number | string; transform?: string; type?: string; u1?: number | string; u2?: number | string; underlinePosition?: number | string; underlineThickness?: number | string; unicode?: number | string; unicodeBidi?: number | string; unicodeRange?: number | string; unitsPerEm?: number | string; vAlphabetic?: number | string; values?: string; vectorEffect?: number | string; version?: string; vertAdvY?: number | string; vertOriginX?: number | string; vertOriginY?: number | string; vHanging?: number | string; vIdeographic?: number | string; viewBox?: string; viewTarget?: number | string; visibility?: number | string; vMathematical?: number | string; widths?: number | string; wordSpacing?: number | string; writingMode?: number | string; x1?: number | string; x2?: number | string; x?: number | string; xChannelSelector?: string; xHeight?: number | string; xlinkActuate?: string; xlinkArcrole?: string; xlinkHref?: string; xlinkRole?: string; xlinkShow?: string; xlinkTitle?: string; xlinkType?: string; xmlBase?: string; xmlLang?: string; xmlns?: string; xmlnsXlink?: string; xmlSpace?: string; y1?: number | string; y2?: number | string; y?: number | string; yChannelSelector?: string; z?: number | string; zoomAndPan?: string; } // // React.DOM // ---------------------------------------------------------------------- interface ReactDOM { // HTML a: HTMLFactory<HTMLAnchorElement>; abbr: HTMLFactory<HTMLElement>; address: HTMLFactory<HTMLElement>; area: HTMLFactory<HTMLAreaElement>; article: HTMLFactory<HTMLElement>; aside: HTMLFactory<HTMLElement>; audio: HTMLFactory<HTMLAudioElement>; b: HTMLFactory<HTMLElement>; base: HTMLFactory<HTMLBaseElement>; bdi: HTMLFactory<HTMLElement>; bdo: HTMLFactory<HTMLElement>; big: HTMLFactory<HTMLElement>; blockquote: HTMLFactory<HTMLElement>; body: HTMLFactory<HTMLBodyElement>; br: HTMLFactory<HTMLBRElement>; button: HTMLFactory<HTMLButtonElement>; canvas: HTMLFactory<HTMLCanvasElement>; caption: HTMLFactory<HTMLElement>; cite: HTMLFactory<HTMLElement>; code: HTMLFactory<HTMLElement>; col: HTMLFactory<HTMLTableColElement>; colgroup: HTMLFactory<HTMLTableColElement>; data: HTMLFactory<HTMLElement>; datalist: HTMLFactory<HTMLDataListElement>; dd: HTMLFactory<HTMLElement>; del: HTMLFactory<HTMLElement>; details: HTMLFactory<HTMLElement>; dfn: HTMLFactory<HTMLElement>; dialog: HTMLFactory<HTMLElement>; div: HTMLFactory<HTMLDivElement>; dl: HTMLFactory<HTMLDListElement>; dt: HTMLFactory<HTMLElement>; em: HTMLFactory<HTMLElement>; embed: HTMLFactory<HTMLEmbedElement>; fieldset: HTMLFactory<HTMLFieldSetElement>; figcaption: HTMLFactory<HTMLElement>; figure: HTMLFactory<HTMLElement>; footer: HTMLFactory<HTMLElement>; form: HTMLFactory<HTMLFormElement>; h1: HTMLFactory<HTMLHeadingElement>; h2: HTMLFactory<HTMLHeadingElement>; h3: HTMLFactory<HTMLHeadingElement>; h4: HTMLFactory<HTMLHeadingElement>; h5: HTMLFactory<HTMLHeadingElement>; h6: HTMLFactory<HTMLHeadingElement>; head: HTMLFactory<HTMLHeadElement>; header: HTMLFactory<HTMLElement>; hgroup: HTMLFactory<HTMLElement>; hr: HTMLFactory<HTMLHRElement>; html: HTMLFactory<HTMLHtmlElement>; i: HTMLFactory<HTMLElement>; iframe: HTMLFactory<HTMLIFrameElement>; img: HTMLFactory<HTMLImageElement>; input: HTMLFactory<HTMLInputElement>; ins: HTMLFactory<HTMLModElement>; kbd: HTMLFactory<HTMLElement>; keygen: HTMLFactory<HTMLElement>; label: HTMLFactory<HTMLLabelElement>; legend: HTMLFactory<HTMLLegendElement>; li: HTMLFactory<HTMLLIElement>; link: HTMLFactory<HTMLLinkElement>; main: HTMLFactory<HTMLElement>; map: HTMLFactory<HTMLMapElement>; mark: HTMLFactory<HTMLElement>; menu: HTMLFactory<HTMLElement>; menuitem: HTMLFactory<HTMLElement>; meta: HTMLFactory<HTMLMetaElement>; meter: HTMLFactory<HTMLElement>; nav: HTMLFactory<HTMLElement>; noscript: HTMLFactory<HTMLElement>; object: HTMLFactory<HTMLObjectElement>; ol: HTMLFactory<HTMLOListElement>; optgroup: HTMLFactory<HTMLOptGroupElement>; option: HTMLFactory<HTMLOptionElement>; output: HTMLFactory<HTMLElement>; p: HTMLFactory<HTMLParagraphElement>; param: HTMLFactory<HTMLParamElement>; picture: HTMLFactory<HTMLElement>; pre: HTMLFactory<HTMLPreElement>; progress: HTMLFactory<HTMLProgressElement>; q: HTMLFactory<HTMLQuoteElement>; rp: HTMLFactory<HTMLElement>; rt: HTMLFactory<HTMLElement>; ruby: HTMLFactory<HTMLElement>; s: HTMLFactory<HTMLElement>; samp: HTMLFactory<HTMLElement>; script: HTMLFactory<HTMLElement>; section: HTMLFactory<HTMLElement>; select: HTMLFactory<HTMLSelectElement>; small: HTMLFactory<HTMLElement>; source: HTMLFactory<HTMLSourceElement>; span: HTMLFactory<HTMLSpanElement>; strong: HTMLFactory<HTMLElement>; style: HTMLFactory<HTMLStyleElement>; sub: HTMLFactory<HTMLElement>; summary: HTMLFactory<HTMLElement>; sup: HTMLFactory<HTMLElement>; table: HTMLFactory<HTMLTableElement>; tbody: HTMLFactory<HTMLTableSectionElement>; td: HTMLFactory<HTMLTableDataCellElement>; textarea: HTMLFactory<HTMLTextAreaElement>; tfoot: HTMLFactory<HTMLTableSectionElement>; th: HTMLFactory<HTMLTableHeaderCellElement>; thead: HTMLFactory<HTMLTableSectionElement>; time: HTMLFactory<HTMLElement>; title: HTMLFactory<HTMLTitleElement>; tr: HTMLFactory<HTMLTableRowElement>; track: HTMLFactory<HTMLTrackElement>; u: HTMLFactory<HTMLElement>; ul: HTMLFactory<HTMLUListElement>; "var": HTMLFactory<HTMLElement>; video: HTMLFactory<HTMLVideoElement>; wbr: HTMLFactory<HTMLElement>; // SVG svg: SVGFactory; circle: SVGFactory; defs: SVGFactory; ellipse: SVGFactory; g: SVGFactory; image: SVGFactory; line: SVGFactory; linearGradient: SVGFactory; mask: SVGFactory; path: SVGFactory; pattern: SVGFactory; polygon: SVGFactory; polyline: SVGFactory; radialGradient: SVGFactory; rect: SVGFactory; stop: SVGFactory; symbol: SVGFactory; text: SVGFactory; tspan: SVGFactory; use: SVGFactory; } // // React.PropTypes // ---------------------------------------------------------------------- interface Validator<T> { (object: T, key: string, componentName: string, ...rest: any[]): Error | null; } interface Requireable<T> extends Validator<T> { isRequired: Validator<T>; } interface ValidationMap<T> { [key: string]: Validator<T>; } interface ReactPropTypes { any: Requireable<any>; array: Requireable<any>; bool: Requireable<any>; func: Requireable<any>; number: Requireable<any>; object: Requireable<any>; string: Requireable<any>; node: Requireable<any>; element: Requireable<any>; instanceOf(expectedClass: {}): Requireable<any>; oneOf(types: any[]): Requireable<any>; oneOfType(types: Validator<any>[]): Requireable<any>; arrayOf(type: Validator<any>): Requireable<any>; objectOf(type: Validator<any>): Requireable<any>; shape(type: ValidationMap<any>): Requireable<any>; } // // React.Children // ---------------------------------------------------------------------- interface ReactChildren { map<T>(children: ReactNode, fn: (child: ReactChild, index: number) => T): T[]; forEach(children: ReactNode, fn: (child: ReactChild, index: number) => any): void; count(children: ReactNode): number; only(children: ReactNode): ReactElement<any>; toArray(children: ReactNode): ReactChild[]; } // // Browser Interfaces // https://github.com/nikeee/2048-typescript/blob/master/2048/js/touch.d.ts // ---------------------------------------------------------------------- interface AbstractView { styleMedia: StyleMedia; document: Document; } interface Touch { identifier: number; target: EventTarget; screenX: number; screenY: number; clientX: number; clientY: number; pageX: number; pageY: number; } interface TouchList { [index: number]: Touch; length: number; item(index: number): Touch; identifiedTouch(identifier: number): Touch; } } declare global { namespace JSX { interface Element extends React.ReactElement<any> { } interface ElementClass extends React.Component<any, any> { render(): JSX.Element | null; } interface ElementAttributesProperty { props: {}; } interface IntrinsicAttributes extends React.Attributes { } interface IntrinsicClassAttributes<T> extends React.ClassAttributes<T> { } interface IntrinsicElements { // HTML a: React.HTMLProps<HTMLAnchorElement>; abbr: React.HTMLProps<HTMLElement>; address: React.HTMLProps<HTMLElement>; area: React.HTMLProps<HTMLAreaElement>; article: React.HTMLProps<HTMLElement>; aside: React.HTMLProps<HTMLElement>; audio: React.HTMLProps<HTMLAudioElement>; b: React.HTMLProps<HTMLElement>; base: React.HTMLProps<HTMLBaseElement>; bdi: React.HTMLProps<HTMLElement>; bdo: React.HTMLProps<HTMLElement>; big: React.HTMLProps<HTMLElement>; blockquote: React.HTMLProps<HTMLElement>; body: React.HTMLProps<HTMLBodyElement>; br: React.HTMLProps<HTMLBRElement>; button: React.HTMLProps<HTMLButtonElement>; canvas: React.HTMLProps<HTMLCanvasElement>; caption: React.HTMLProps<HTMLElement>; cite: React.HTMLProps<HTMLElement>; code: React.HTMLProps<HTMLElement>; col: React.HTMLProps<HTMLTableColElement>; colgroup: React.HTMLProps<HTMLTableColElement>; data: React.HTMLProps<HTMLElement>; datalist: React.HTMLProps<HTMLDataListElement>; dd: React.HTMLProps<HTMLElement>; del: React.HTMLProps<HTMLElement>; details: React.HTMLProps<HTMLElement>; dfn: React.HTMLProps<HTMLElement>; dialog: React.HTMLProps<HTMLElement>; div: React.HTMLProps<HTMLDivElement>; dl: React.HTMLProps<HTMLDListElement>; dt: React.HTMLProps<HTMLElement>; em: React.HTMLProps<HTMLElement>; embed: React.HTMLProps<HTMLEmbedElement>; fieldset: React.HTMLProps<HTMLFieldSetElement>; figcaption: React.HTMLProps<HTMLElement>; figure: React.HTMLProps<HTMLElement>; footer: React.HTMLProps<HTMLElement>; form: React.HTMLProps<HTMLFormElement>; h1: React.HTMLProps<HTMLHeadingElement>; h2: React.HTMLProps<HTMLHeadingElement>; h3: React.HTMLProps<HTMLHeadingElement>; h4: React.HTMLProps<HTMLHeadingElement>; h5: React.HTMLProps<HTMLHeadingElement>; h6: React.HTMLProps<HTMLHeadingElement>; head: React.HTMLProps<HTMLHeadElement>; header: React.HTMLProps<HTMLElement>; hgroup: React.HTMLProps<HTMLElement>; hr: React.HTMLProps<HTMLHRElement>; html: React.HTMLProps<HTMLHtmlElement>; i: React.HTMLProps<HTMLElement>; iframe: React.HTMLProps<HTMLIFrameElement>; img: React.HTMLProps<HTMLImageElement>; input: React.HTMLProps<HTMLInputElement>; ins: React.HTMLProps<HTMLModElement>; kbd: React.HTMLProps<HTMLElement>; keygen: React.HTMLProps<HTMLElement>; label: React.HTMLProps<HTMLLabelElement>; legend: React.HTMLProps<HTMLLegendElement>; li: React.HTMLProps<HTMLLIElement>; link: React.HTMLProps<HTMLLinkElement>; main: React.HTMLProps<HTMLElement>; map: React.HTMLProps<HTMLMapElement>; mark: React.HTMLProps<HTMLElement>; menu: React.HTMLProps<HTMLElement>; menuitem: React.HTMLProps<HTMLElement>; meta: React.HTMLProps<HTMLMetaElement>; meter: React.HTMLProps<HTMLElement>; nav: React.HTMLProps<HTMLElement>; noindex: React.HTMLProps<HTMLElement>; noscript: React.HTMLProps<HTMLElement>; object: React.HTMLProps<HTMLObjectElement>; ol: React.HTMLProps<HTMLOListElement>; optgroup: React.HTMLProps<HTMLOptGroupElement>; option: React.HTMLProps<HTMLOptionElement>; output: React.HTMLProps<HTMLElement>; p: React.HTMLProps<HTMLParagraphElement>; param: React.HTMLProps<HTMLParamElement>; picture: React.HTMLProps<HTMLElement>; pre: React.HTMLProps<HTMLPreElement>; progress: React.HTMLProps<HTMLProgressElement>; q: React.HTMLProps<HTMLQuoteElement>; rp: React.HTMLProps<HTMLElement>; rt: React.HTMLProps<HTMLElement>; ruby: React.HTMLProps<HTMLElement>; s: React.HTMLProps<HTMLElement>; samp: React.HTMLProps<HTMLElement>; script: React.HTMLProps<HTMLElement>; section: React.HTMLProps<HTMLElement>; select: React.HTMLProps<HTMLSelectElement>; small: React.HTMLProps<HTMLElement>; source: React.HTMLProps<HTMLSourceElement>; span: React.HTMLProps<HTMLSpanElement>; strong: React.HTMLProps<HTMLElement>; style: React.HTMLProps<HTMLStyleElement>; sub: React.HTMLProps<HTMLElement>; summary: React.HTMLProps<HTMLElement>; sup: React.HTMLProps<HTMLElement>; table: React.HTMLProps<HTMLTableElement>; tbody: React.HTMLProps<HTMLTableSectionElement>; td: React.HTMLProps<HTMLTableDataCellElement>; textarea: React.HTMLProps<HTMLTextAreaElement>; tfoot: React.HTMLProps<HTMLTableSectionElement>; th: React.HTMLProps<HTMLTableHeaderCellElement>; thead: React.HTMLProps<HTMLTableSectionElement>; time: React.HTMLProps<HTMLElement>; title: React.HTMLProps<HTMLTitleElement>; tr: React.HTMLProps<HTMLTableRowElement>; track: React.HTMLProps<HTMLTrackElement>; u: React.HTMLProps<HTMLElement>; ul: React.HTMLProps<HTMLUListElement>; "var": React.HTMLProps<HTMLElement>; video: React.HTMLProps<HTMLVideoElement>; wbr: React.HTMLProps<HTMLElement>; // SVG svg: React.SVGProps; circle: React.SVGProps; clipPath: React.SVGProps; defs: React.SVGProps; desc: React.SVGProps; ellipse: React.SVGProps; feBlend: React.SVGProps; feColorMatrix: React.SVGProps; feComponentTransfer: React.SVGProps; feComposite: React.SVGProps; feConvolveMatrix: React.SVGProps; feDiffuseLighting: React.SVGProps; feDisplacementMap: React.SVGProps; feDistantLight: React.SVGProps; feFlood: React.SVGProps; feFuncA: React.SVGProps; feFuncB: React.SVGProps; feFuncG: React.SVGProps; feFuncR: React.SVGProps; feGaussianBlur: React.SVGProps; feImage: React.SVGProps; feMerge: React.SVGProps; feMergeNode: React.SVGProps; feMorphology: React.SVGProps; feOffset: React.SVGProps; fePointLight: React.SVGProps; feSpecularLighting: React.SVGProps; feSpotLight: React.SVGProps; feTile: React.SVGProps; feTurbulence: React.SVGProps; filter: React.SVGProps; foreignObject: React.SVGProps; g: React.SVGProps; image: React.SVGProps; line: React.SVGProps; linearGradient: React.SVGProps; marker: React.SVGProps; mask: React.SVGProps; metadata: React.SVGProps; path: React.SVGProps; pattern: React.SVGProps; polygon: React.SVGProps; polyline: React.SVGProps; radialGradient: React.SVGProps; rect: React.SVGProps; stop: React.SVGProps; switch: React.SVGProps; symbol: React.SVGProps; text: React.SVGProps; textPath: React.SVGProps; tspan: React.SVGProps; use: React.SVGProps; view: React.SVGProps; } } }
{ "content_hash": "58de029d0574e788eb226a9c96e122c9", "timestamp": "", "source": "github", "line_count": 2806, "max_line_length": 525, "avg_line_length": 41.34212401995723, "alnum_prop": 0.6284674930607037, "repo_name": "aikar/timings", "id": "e59234ae6c275aa3b3e883b857d5f717b7932732", "size": "116064", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": ".idea/libraries/react.d.ts", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "92793" }, { "name": "PHP", "bytes": "39387" }, { "name": "SCSS", "bytes": "54091" }, { "name": "Shell", "bytes": "2070" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="fr"> <head> <!-- Generated by javadoc (version 1.7.0_01) on Sat Mar 24 00:58:28 CET 2012 --> <meta http-equiv="Content-Type" content="text/html" charset="UTF-8"> <title>Uses of Class org.resthub.identity.service.RoleService.RoleChange (RESThub 1.1.3 API)</title> <meta name="date" content="2012-03-24"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.resthub.identity.service.RoleService.RoleChange (RESThub 1.1.3 API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../org/resthub/identity/service/RoleService.RoleChange.html" title="enum in org.resthub.identity.service">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/resthub/identity/service/\class-useRoleService.RoleChange.html" target="_top">Frames</a></li> <li><a href="RoleService.RoleChange.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class org.resthub.identity.service.RoleService.RoleChange" class="title">Uses of Class<br>org.resthub.identity.service.RoleService.RoleChange</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../org/resthub/identity/service/RoleService.RoleChange.html" title="enum in org.resthub.identity.service">RoleService.RoleChange</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#org.resthub.identity.service">org.resthub.identity.service</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="org.resthub.identity.service"> <!-- --> </a> <h3>Uses of <a href="../../../../../org/resthub/identity/service/RoleService.RoleChange.html" title="enum in org.resthub.identity.service">RoleService.RoleChange</a> in <a href="../../../../../org/resthub/identity/service/package-summary.html">org.resthub.identity.service</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../org/resthub/identity/service/package-summary.html">org.resthub.identity.service</a> that return <a href="../../../../../org/resthub/identity/service/RoleService.RoleChange.html" title="enum in org.resthub.identity.service">RoleService.RoleChange</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>static <a href="../../../../../org/resthub/identity/service/RoleService.RoleChange.html" title="enum in org.resthub.identity.service">RoleService.RoleChange</a></code></td> <td class="colLast"><span class="strong">RoleService.RoleChange.</span><code><strong><a href="../../../../../org/resthub/identity/service/RoleService.RoleChange.html#valueOf(java.lang.String)">valueOf</a></strong>(<a href="http://download.oracle.com/javase/6/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>&nbsp;name)</code> <div class="block">Returns the enum constant of this type with the specified name.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static <a href="../../../../../org/resthub/identity/service/RoleService.RoleChange.html" title="enum in org.resthub.identity.service">RoleService.RoleChange</a>[]</code></td> <td class="colLast"><span class="strong">RoleService.RoleChange.</span><code><strong><a href="../../../../../org/resthub/identity/service/RoleService.RoleChange.html#values()">values</a></strong>()</code> <div class="block">Returns an array containing the constants of this enum type, in the order they are declared.</div> </td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../org/resthub/identity/service/RoleService.RoleChange.html" title="enum in org.resthub.identity.service">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/resthub/identity/service/\class-useRoleService.RoleChange.html" target="_top">Frames</a></li> <li><a href="RoleService.RoleChange.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2009-2012. All Rights Reserved.</small></p> </body> </html>
{ "content_hash": "88b21100c4af59ef5fbac3a8eddfb078", "timestamp": "", "source": "github", "line_count": 166, "max_line_length": 376, "avg_line_length": 44.644578313253014, "alnum_prop": 0.6560518148697881, "repo_name": "resthub/resthub.github.io", "id": "d179b4b5529418083125c237c95ed1594813ffee", "size": "7411", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "apidocs/spring/1.1/org/resthub/identity/service/class-use/RoleService.RoleChange.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "265011" }, { "name": "HTML", "bytes": "14909519" }, { "name": "JavaScript", "bytes": "104585" }, { "name": "Ruby", "bytes": "1676" } ], "symlink_target": "" }
<?php /** * @file * Contains \Drupal\Core\Routing\RouteProvider. */ namespace Drupal\Core\Routing; use Drupal\Core\Cache\Cache; use Drupal\Core\Cache\CacheBackendInterface; use Drupal\Core\Cache\CacheTagsInvalidatorInterface; use Drupal\Core\Path\CurrentPathStack; use Drupal\Core\PathProcessor\InboundPathProcessorInterface; use Drupal\Core\State\StateInterface; use Symfony\Cmf\Component\Routing\PagedRouteCollection; use Symfony\Cmf\Component\Routing\PagedRouteProviderInterface; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Routing\Exception\RouteNotFoundException; use Symfony\Component\Routing\RouteCollection; use Symfony\Component\Routing\Exception\ResourceNotFoundException; use \Drupal\Core\Database\Connection; /** * A Route Provider front-end for all Drupal-stored routes. */ class RouteProvider implements PreloadableRouteProviderInterface, PagedRouteProviderInterface, EventSubscriberInterface { /** * The database connection from which to read route information. * * @var \Drupal\Core\Database\Connection */ protected $connection; /** * The name of the SQL table from which to read the routes. * * @var string */ protected $tableName; /** * The state. * * @var \Drupal\Core\State\StateInterface */ protected $state; /** * A cache of already-loaded routes, keyed by route name. * * @var \Symfony\Component\Routing\Route[] */ protected $routes = array(); /** * A cache of already-loaded serialized routes, keyed by route name. * * @var string[] */ protected $serializedRoutes = []; /** * The current path. * * @var \Drupal\Core\Path\CurrentPathStack */ protected $currentPath; /** * The cache backend. * * @var \Drupal\Core\Cache\CacheBackendInterface */ protected $cache; /** * The cache tag invalidator. * * @var \Drupal\Core\Cache\CacheTagsInvalidatorInterface */ protected $cacheTagInvalidator; /** * A path processor manager for resolving the system path. * * @var \Drupal\Core\PathProcessor\InboundPathProcessorInterface */ protected $pathProcessor; /** * Cache ID prefix used to load routes. */ const ROUTE_LOAD_CID_PREFIX = 'route_provider.route_load:'; /** * Constructs a new PathMatcher. * * @param \Drupal\Core\Database\Connection $connection * A database connection object. * @param \Drupal\Core\State\StateInterface $state * The state. * @param \Drupal\Core\Path\CurrentPathStack $current_path * The current path. * @param \Drupal\Core\Cache\CacheBackendInterface $cache_backend * The cache backend. * @param \Drupal\Core\PathProcessor\InboundPathProcessorInterface $path_processor * The path processor. * @param \Drupal\Core\Cache\CacheTagsInvalidatorInterface $cache_tag_invalidator * The cache tag invalidator. * @param string $table * (Optional) The table in the database to use for matching. Defaults to 'router' */ public function __construct(Connection $connection, StateInterface $state, CurrentPathStack $current_path, CacheBackendInterface $cache_backend, InboundPathProcessorInterface $path_processor, CacheTagsInvalidatorInterface $cache_tag_invalidator, $table = 'router') { $this->connection = $connection; $this->state = $state; $this->currentPath = $current_path; $this->cache = $cache_backend; $this->cacheTagInvalidator = $cache_tag_invalidator; $this->pathProcessor = $path_processor; $this->tableName = $table; } /** * Finds routes that may potentially match the request. * * This may return a mixed list of class instances, but all routes returned * must extend the core symfony route. The classes may also implement * RouteObjectInterface to link to a content document. * * This method may not throw an exception based on implementation specific * restrictions on the url. That case is considered a not found - returning * an empty array. Exceptions are only used to abort the whole request in * case something is seriously broken, like the storage backend being down. * * Note that implementations may not implement an optimal matching * algorithm, simply a reasonable first pass. That allows for potentially * very large route sets to be filtered down to likely candidates, which * may then be filtered in memory more completely. * * @param Request $request A request against which to match. * * @return \Symfony\Component\Routing\RouteCollection with all urls that * could potentially match $request. Empty collection if nothing can * match. */ public function getRouteCollectionForRequest(Request $request) { // Cache both the system path as well as route parameters and matching // routes. $cid = 'route:' . $request->getPathInfo() . ':' . $request->getQueryString(); if ($cached = $this->cache->get($cid)) { $this->currentPath->setPath($cached->data['path'], $request); $request->query->replace($cached->data['query']); return $cached->data['routes']; } else { // Just trim on the right side. $path = $request->getPathInfo(); $path = $path === '/' ? $path : rtrim($request->getPathInfo(), '/'); $path = $this->pathProcessor->processInbound($path, $request); $this->currentPath->setPath($path, $request); // Incoming path processors may also set query parameters. $query_parameters = $request->query->all(); $routes = $this->getRoutesByPath(rtrim($path, '/')); $cache_value = [ 'path' => $path, 'query' => $query_parameters, 'routes' => $routes, ]; $this->cache->set($cid, $cache_value, CacheBackendInterface::CACHE_PERMANENT, ['route_match']); return $routes; } } /** * Find the route using the provided route name (and parameters). * * @param string $name * The route name to fetch * * @return \Symfony\Component\Routing\Route * The found route. * * @throws \Symfony\Component\Routing\Exception\RouteNotFoundException * Thrown if there is no route with that name in this repository. */ public function getRouteByName($name) { $routes = $this->getRoutesByNames(array($name)); if (empty($routes)) { throw new RouteNotFoundException(sprintf('Route "%s" does not exist.', $name)); } return reset($routes); } /** * {@inheritdoc} */ public function preLoadRoutes($names) { if (empty($names)) { throw new \InvalidArgumentException('You must specify the route names to load'); } $routes_to_load = array_diff($names, array_keys($this->routes), array_keys($this->serializedRoutes)); if ($routes_to_load) { $cid = static::ROUTE_LOAD_CID_PREFIX . hash('sha512', serialize($routes_to_load)); if ($cache = $this->cache->get($cid)) { $routes = $cache->data; } else { $result = $this->connection->query('SELECT name, route FROM {' . $this->connection->escapeTable($this->tableName) . '} WHERE name IN ( :names[] )', array(':names[]' => $routes_to_load)); $routes = $result->fetchAllKeyed(); $this->cache->set($cid, $routes, Cache::PERMANENT, ['routes']); } $this->serializedRoutes += $routes; } } /** * {@inheritdoc} */ public function getRoutesByNames($names) { $this->preLoadRoutes($names); foreach ($names as $name) { // The specified route name might not exist or might be serialized. if (!isset($this->routes[$name]) && isset($this->serializedRoutes[$name])) { $this->routes[$name] = unserialize($this->serializedRoutes[$name]); unset($this->serializedRoutes[$name]); } } return array_intersect_key($this->routes, array_flip($names)); } /** * Returns an array of path pattern outlines that could match the path parts. * * @param array $parts * The parts of the path for which we want candidates. * * @return array * An array of outlines that could match the specified path parts. */ public function getCandidateOutlines(array $parts) { $number_parts = count($parts); $ancestors = array(); $length = $number_parts - 1; $end = (1 << $number_parts) - 1; // The highest possible mask is a 1 bit for every part of the path. We will // check every value down from there to generate a possible outline. if ($number_parts == 1) { $masks = array(1); } elseif ($number_parts <= 3) { // Optimization - don't query the state system for short paths. This also // insulates against the state entry for masks going missing for common // user-facing paths since we generate all values without checking state. $masks = range($end, 1); } elseif ($number_parts <= 0) { // No path can match, short-circuit the process. $masks = array(); } else { // Get the actual patterns that exist out of state. $masks = (array) $this->state->get('routing.menu_masks.' . $this->tableName, array()); } // Only examine patterns that actually exist as router items (the masks). foreach ($masks as $i) { if ($i > $end) { // Only look at masks that are not longer than the path of interest. continue; } elseif ($i < (1 << $length)) { // We have exhausted the masks of a given length, so decrease the length. --$length; } $current = ''; for ($j = $length; $j >= 0; $j--) { // Check the bit on the $j offset. if ($i & (1 << $j)) { // Bit one means the original value. $current .= $parts[$length - $j]; } else { // Bit zero means means wildcard. $current .= '%'; } // Unless we are at offset 0, add a slash. if ($j) { $current .= '/'; } } $ancestors[] = '/' . $current; } return $ancestors; } /** * {@inheritdoc} */ public function getRoutesByPattern($pattern) { $path = RouteCompiler::getPatternOutline($pattern); return $this->getRoutesByPath($path); } /** * Get all routes which match a certain pattern. * * @param string $path * The route pattern to search for (contains % as placeholders). * * @return \Symfony\Component\Routing\RouteCollection * Returns a route collection of matching routes. */ protected function getRoutesByPath($path) { // Split the path up on the slashes, ignoring multiple slashes in a row // or leading or trailing slashes. $parts = preg_split('@/+@', $path, NULL, PREG_SPLIT_NO_EMPTY); $collection = new RouteCollection(); $ancestors = $this->getCandidateOutlines($parts); if (empty($ancestors)) { return $collection; } // The >= check on number_parts allows us to match routes with optional // trailing wildcard parts as long as the pattern matches, since we // dump the route pattern without those optional parts. $routes = $this->connection->query("SELECT name, route, fit FROM {" . $this->connection->escapeTable($this->tableName) . "} WHERE pattern_outline IN ( :patterns[] ) AND number_parts >= :count_parts", array( ':patterns[]' => $ancestors, ':count_parts' => count($parts), )) ->fetchAll(\PDO::FETCH_ASSOC); // We sort by fit and name in PHP to avoid a SQL filesort. usort($routes, array($this, 'routeProviderRouteCompare')); foreach ($routes as $row) { $collection->add($row['name'], unserialize($row['route'])); } return $collection; } /** * Comparison function for usort on routes. */ public function routeProviderRouteCompare(array $a, array $b) { if ($a['fit'] == $b['fit']) { return strcmp($a['name'], $b['name']); } // Reverse sort from highest to lowest fit. PHP should cast to int, but // the explicit cast makes this sort more robust against unexpected input. return (int) $a['fit'] < (int) $b['fit'] ? 1 : -1; } /** * {@inheritdoc} */ public function getAllRoutes() { return new PagedRouteCollection($this); } /** * {@inheritdoc} */ public function reset() { $this->routes = array(); $this->serializedRoutes = array(); $this->cacheTagInvalidator->invalidateTags(['routes']); } /** * {@inheritdoc} */ static function getSubscribedEvents() { $events[RoutingEvents::FINISHED][] = array('reset'); return $events; } /** * {@inheritdoc} */ public function getRoutesPaged($offset, $length = NULL) { $select = $this->connection->select($this->tableName, 'router') ->fields('router', ['name', 'route']); if (isset($length)) { $select->range($offset, $length); } $routes = $select->execute()->fetchAllKeyed(); $result = []; foreach ($routes as $name => $route) { $result[$name] = unserialize($route); } return $result; } /** * {@inheritdoc} */ public function getRoutesCount() { return $this->connection->query("SELECT COUNT(*) FROM {" . $this->connection->escapeTable($this->tableName) . "}")->fetchField(); } }
{ "content_hash": "e178c29f7bbce08bc809f41294210177", "timestamp": "", "source": "github", "line_count": 421, "max_line_length": 268, "avg_line_length": 31.57007125890736, "alnum_prop": 0.6413362425701603, "repo_name": "komejo/d8demo-dev", "id": "58b8320b40cf7b04053f30b996c066089f34a96f", "size": "13291", "binary": false, "copies": "27", "ref": "refs/heads/master", "path": "web/core/lib/Drupal/Core/Routing/RouteProvider.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "9118" }, { "name": "C++", "bytes": "13044" }, { "name": "CSS", "bytes": "291673" }, { "name": "HTML", "bytes": "322832" }, { "name": "JavaScript", "bytes": "838628" }, { "name": "PHP", "bytes": "27260329" }, { "name": "Shell", "bytes": "45206" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <!-- ~ Copyright (c) 2010-2015 Evolveum ~ ~ Licensed under the Apache License, Version 2.0 (the "License"); ~ you may not use this file except in compliance with the License. ~ You may obtain a copy of the License at ~ ~ http://www.apache.org/licenses/LICENSE-2.0 ~ ~ Unless required by applicable law or agreed to in writing, software ~ distributed under the License is distributed on an "AS IS" BASIS, ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ~ See the License for the specific language governing permissions and ~ limitations under the License. --> <!-- Resource definition for an embedded OpenDJ instance. It is used in internal midPoint tests, mostly in "integration" tests. --> <resource oid="ef2bc95b-76e0-59e2-86d6-3d4f02d3ffff" xmlns="http://midpoint.evolveum.com/xml/ns/public/common/common-3" xmlns:c="http://midpoint.evolveum.com/xml/ns/public/common/common-3" xmlns:t="http://prism.evolveum.com/xml/ns/public/types-3" xmlns:q="http://prism.evolveum.com/xml/ns/public/query-3" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ri="http://midpoint.evolveum.com/xml/ns/public/resource/instance-3" xmlns:icfs="http://midpoint.evolveum.com/xml/ns/public/connector/icf-1/resource-schema-3" xmlns:icfc="http://midpoint.evolveum.com/xml/ns/public/connector/icf-1/connector-schema-3" xmlns:my="http://whatever.com/my"> <!-- Resource printable name --> <name>Embedded Test OpenDJ</name> <!-- Reference to the ICF LDAP connector. This is dynamic reference, it will be translated to OID during import. --> <connectorRef type="ConnectorType"> <filter> <q:equal> <q:path>c:connectorType</q:path> <q:value>com.evolveum.polygon.connector.ldap.LdapConnector</q:value> </q:equal> </filter> </connectorRef> <connectorConfiguration xmlns:icfcldap="http://midpoint.evolveum.com/xml/ns/public/connector/icf-1/bundle/com.evolveum.polygon.connector-ldap/com.evolveum.polygon.connector.ldap.LdapConnector"> <icfc:configurationProperties> <icfcldap:port>10389</icfcldap:port> <icfcldap:host>localhost</icfcldap:host> <icfcldap:baseContext>dc=example,dc=com</icfcldap:baseContext> <icfcldap:bindDn>cn=directory manager</icfcldap:bindDn> <icfcldap:bindPassword><t:clearValue>secret</t:clearValue></icfcldap:bindPassword> <icfcldap:pagingStrategy>auto</icfcldap:pagingStrategy> <icfcldap:vlvSortAttribute>entryUUID</icfcldap:vlvSortAttribute> <icfcldap:operationalAttributes>ds-pwp-account-disabled</icfcldap:operationalAttributes> <icfcldap:operationalAttributes>isMemberOf</icfcldap:operationalAttributes> </icfc:configurationProperties> <icfc:resultsHandlerConfiguration> <icfc:enableNormalizingResultsHandler>false</icfc:enableNormalizingResultsHandler> <icfc:enableFilteredResultsHandler>false</icfc:enableFilteredResultsHandler> <icfc:enableAttributesToGetSearchResultsHandler>false</icfc:enableAttributesToGetSearchResultsHandler> </icfc:resultsHandlerConfiguration> </connectorConfiguration> <!-- Resource namespace --> <!-- <namespace>http://midpoint.evolveum.com/xml/ns/public/resource/instance/ef2bc95b-76e0-59e2-86d6-3d4f02d3ffff</namespace> --> <!-- No schema. It will be generated from the resource. --> <schemaHandling> <objectType> <kind>account</kind> <intent>default</intent> <displayName>Default Account</displayName> <default>true</default> <objectClass>ri:inetOrgPerson</objectClass> <attribute> <ref>ri:dn</ref> <displayName>Distinguished Name</displayName> <outbound> <strength>weak</strength> <source> <path>declare default namespace "http://midpoint.evolveum.com/xml/ns/public/common/common-3";$user/name</path> </source> <expression> <script> <language>http://www.w3.org/TR/xpath/</language> <code> declare namespace c="http://midpoint.evolveum.com/xml/ns/public/common/common-3"; concat('uid=', $c:name, $c:iterationToken, ',ou=people,dc=example,dc=com') </code> </script> </expression> </outbound> </attribute> <attribute> <ref>ri:entryUUID</ref> <displayName>Entry UUID</displayName> </attribute> <attribute> <ref>ri:cn</ref> <displayName>Common Name</displayName> <limitations> <maxOccurs>1</maxOccurs> </limitations> <outbound> <strength>strong</strength> <!-- MID-3093 --> <source> <path>$user/fullName</path> </source> </outbound> <inbound> <target> <path>$user/fullName</path> </target> </inbound> </attribute> <attribute> <ref>ri:sn</ref> <displayName>Surname</displayName> <limitations> <maxOccurs>1</maxOccurs> </limitations> <outbound> <source> <path>declare default namespace "http://midpoint.evolveum.com/xml/ns/public/common/common-3";$user/familyName</path> </source> </outbound> <inbound> <target> <path>declare default namespace "http://midpoint.evolveum.com/xml/ns/public/common/common-3";$user/familyName</path> </target> </inbound> </attribute> <attribute> <ref>ri:givenName</ref> <displayName>Given Name</displayName> <limitations> <maxOccurs>1</maxOccurs> </limitations> <outbound> <source> <path>c:givenName</path> </source> <expression> <script> <language>http://www.w3.org/TR/xpath/</language> <code> declare namespace c="http://midpoint.evolveum.com/xml/ns/public/common/common-3"; $c:givenName </code> </script> </expression> </outbound> <inbound> <target> <path>$c:user/c:givenName</path> </target> </inbound> </attribute> <attribute> <ref>ri:uid</ref> <displayName>Login Name</displayName> <limitations> <minOccurs>1</minOccurs> <maxOccurs>1</maxOccurs> </limitations> <secondaryIdentifier>true</secondaryIdentifier> <outbound> <description> It is mapped from (and also to) "name" property of user. It is essentially a login name. This outbound construction is using a Groovy expression. </description> <strength>weak</strength> <source> <path>$c:user/c:name</path> </source> <expression> <script> <language>http://www.w3.org/TR/xpath/</language> <code> declare namespace c="http://midpoint.evolveum.com/xml/ns/public/common/common-3"; concat($c:name, $c:iterationToken) </code> </script> </expression> </outbound> <inbound> <description> It is mapped to (and also from) "name" property of user. It is essentially a login name </description> <strength>weak</strength> <target> <path>name</path> </target> </inbound> </attribute> <attribute> <ref>ri:carLicense</ref> <description> This attibute definition is used to test tolerance of empty values. </description> <outbound> <description> The expression will produce empty value. OpenDJ will die if empty value is provided for an attribute. midPoint should filter out the empty value and do not sent it to OpenDJ. </description> <strength>weak</strength> <expression> <script> <language>http://www.w3.org/TR/xpath/</language> <returnType>scalar</returnType> <c:code> concat('','') </c:code> </script> </expression> </outbound> <inbound> <target> <path> declare namespace i="http://midpoint.evolveum.com/xml/ns/public/common/common-3"; declare namespace my="http://whatever.com/my"; $i:user/i:extension/my:description </path> </target> </inbound> </attribute> <attribute> <ref>ri:l</ref> <c:tolerant>false</c:tolerant> <outbound> <strength>strong</strength> <source> <path>declare namespace c="http://midpoint.evolveum.com/xml/ns/public/common/common-3";$c:user/c:locality</path> </source> <expression> <script> <c:language>http://www.w3.org/TR/xpath/</c:language> <c:returnType>scalar</c:returnType> <code> declare namespace c="http://midpoint.evolveum.com/xml/ns/public/common/common-3"; if (empty($c:user/c:locality)) then "middle of nowhere" else $c:user/c:locality </code> </script> </expression> </outbound> </attribute> <attribute> <ref>ri:employeeType</ref> <displayName>Employee Type</displayName> <outbound> <strength>weak</strength> <source> <path>$c:user/c:employeeType</path> </source> </outbound> </attribute> <association> <ref>ri:group</ref> <displayName>LDAP Group Membership</displayName> <kind>entitlement</kind> <intent>ldapGroup</intent> <direction>objectToSubject</direction> <associationAttribute>ri:uniqueMember</associationAttribute> <valueAttribute>ri:dn</valueAttribute> </association> <iteration> <maxIterations>5</maxIterations> </iteration> <activation> <administrativeStatus> <outbound/> <inbound> <strength>weak</strength> <expression> <asIs/> </expression> </inbound> </administrativeStatus> </activation> <!-- <activation> --> <!-- <enabled> --> <!-- <outbound> --> <!-- <expression> --> <!-- <asIs/> --> <!-- </expression> --> <!-- </outbound> --> <!-- <inbound> --> <!-- <expression> --> <!-- <asIs/> --> <!-- </expression> --> <!-- </inbound> --> <!-- </enabled> --> <!-- </activation> --> <credentials> <password> <outbound> <expression> <asIs/> </expression> </outbound> <inbound> <strength>weak</strength> <expression> <generate/> </expression> </inbound> </password> </credentials> </objectType> <objectType> <kind>entitlement</kind> <intent>ldapGroup</intent> <displayName>LDAP Group</displayName> <objectClass>ri:groupOfUniqueNames</objectClass> </objectType> </schemaHandling> <capabilities xmlns:cap="http://midpoint.evolveum.com/xml/ns/public/resource/capabilities-3"> <configured> <cap:activation> <cap:status> <cap:attribute>ri:ds-pwp-account-disabled</cap:attribute> <cap:enableValue/> <cap:disableValue>true</cap:disableValue> </cap:status> </cap:activation> </configured> </capabilities> <!-- <consistency> --> <!-- <avoidDuplicateValues>true</avoidDuplicateValues> --> <!-- </consistency> --> <!-- Synchronization section describes the synchronization policy, timing, reactions and similar synchronization settings. --> <c:synchronization> <objectSynchronization> <!-- The synchronization for this resource is enabled. It means that the synchronization will poll for changes once per interval specified below. --> <c:enabled>true</c:enabled> <!-- Correlation expression. It will be used to find appropriate user entry for an account. --> <c:correlation> <!-- Correlation rule is a search query --> <!-- The clause <c:type uri="http://midpoint.evolveum.com/xml/ns/public/common/common-3#UserType"/> is implicit in correlation rules --> <!-- Following search query will look for users that have "name" equal to the "uid" attribute of the account. Simply speaking, it will look for match in usernames in the IDM and the resource. --> <q:equal> <q:path>declare namespace c="http://midpoint.evolveum.com/xml/ns/public/common/common-3";c:name</q:path> <expression> <script> <language>http://www.w3.org/TR/xpath/</language> <code> declare namespace c="http://midpoint.evolveum.com/xml/ns/public/common/common-3"; declare namespace dj="http://midpoint.evolveum.com/xml/ns/public/resource/instance-3"; $c:account/c:attributes/dj:uid </code> </script> </expression> </q:equal> </c:correlation> <!-- Confirmation rule may be here, but as the search above will always return at most one match, the confirmation rule is not needed. --> <objectTemplateRef oid="c0c010c0-d34d-b33f-f00d-777111111111"/> <!-- Following section describes reactions to a situations. The setting here assumes that this resource is authoritative, therefore all accounts created on the resource should be reflected as new users in IDM. See http://wiki.evolveum.com/display/midPoint/Synchronization+Situations --> <c:reaction> <c:situation>linked</c:situation> <synchronize>true</synchronize> </c:reaction> <c:reaction> <c:situation>deleted</c:situation> <synchronize>true</synchronize> <action> <handlerUri>http://midpoint.evolveum.com/xml/ns/public/model/action-3#unlink</handlerUri> </action> </c:reaction> <c:reaction> <c:situation>unlinked</c:situation> <synchronize>true</synchronize> <action> <handlerUri>http://midpoint.evolveum.com/xml/ns/public/model/action-3#link</handlerUri> </action> </c:reaction> <c:reaction> <c:situation>unmatched</c:situation> <synchronize>true</synchronize> <action> <handlerUri>http://midpoint.evolveum.com/xml/ns/public/model/action-3#addFocus</handlerUri> </action> </c:reaction> </objectSynchronization> </c:synchronization> </resource>
{ "content_hash": "99ba8d5920924c0088f89c041ab4aa52", "timestamp": "", "source": "github", "line_count": 444, "max_line_length": 194, "avg_line_length": 37.31306306306306, "alnum_prop": 0.5387215548982918, "repo_name": "PetrGasparik/midpoint", "id": "d10e180e918e4e438318fff3cc8c5aca62a86f80", "size": "16567", "binary": false, "copies": "1", "ref": "refs/heads/CAS-auth", "path": "testing/consistency-mechanism/src/test/resources/repo/resource-opendj.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "321145" }, { "name": "CSS", "bytes": "234702" }, { "name": "HTML", "bytes": "651627" }, { "name": "Java", "bytes": "24107826" }, { "name": "JavaScript", "bytes": "17224" }, { "name": "PLSQL", "bytes": "2171" }, { "name": "PLpgSQL", "bytes": "8169" }, { "name": "Shell", "bytes": "390442" } ], "symlink_target": "" }
if (!$PSScriptRoot) { $PSScriptRoot = Split-Path $MyInvocation.MyCommand.Path -Parent } Write-Output "Retrieving signature card templates..." $CommonCardTemplates = @{ "A-1" = Get-Content $PSScriptRoot"\A-1.txt"; "A-2" = Get-Content $PSScriptRoot"\A-2.txt"; "A-3" = Get-Content $PSScriptRoot"\A-3.txt"; "B-1" = Get-Content $PSScriptRoot"\B-1.txt"; "B-2" = Get-Content $PSScriptRoot"\B-2.txt"; "B-3" = Get-Content $PSScriptRoot"\B-3.txt"; "C-1" = Get-Content $PSScriptRoot"\C-1.txt"; "C-2" = Get-Content $PSScriptRoot"\C-2.txt"; "C-3" = Get-Content $PSScriptRoot"\C-3.txt"; "D-1" = Get-Content $PSScriptRoot"\D-1.txt"; "D-2" = Get-Content $PSScriptRoot"\D-2.txt"; "D-3" = Get-Content $PSScriptRoot"\D-3.txt"; } $CommonCardTemplatesNK = ($CommonCardTemplates.Keys | Measure-Object).Count $CommonCardTemplatesNV = ($CommonCardTemplates.Values | Measure-Object).Count if (-not $CommonCardTemplatesNK -eq $CommonCardTemplatesNV ) { Write-Error "At least one Common Card template file could not be found or accessed in this folder. Please make sure it exists and then try again. Aborting." exit } $CommonCardTemplates = @{ "A-1" = $CommonCardTemplates["A-1"] | Out-String; "A-2" = $CommonCardTemplates["A-2"] | Out-String; "A-3" = $CommonCardTemplates["A-3"] | Out-String; "B-1" = $CommonCardTemplates["B-1"] | Out-String; "B-2" = $CommonCardTemplates["B-2"] | Out-String; "B-3" = $CommonCardTemplates["B-3"] | Out-String; "C-1" = $CommonCardTemplates["C-1"] | Out-String; "C-2" = $CommonCardTemplates["C-2"] | Out-String; "C-3" = $CommonCardTemplates["C-3"] | Out-String; "D-1" = $CommonCardTemplates["D-1"] | Out-String; "D-2" = $CommonCardTemplates["D-2"] | Out-String; "D-3" = $CommonCardTemplates["D-3"] | Out-String; } $CustomCardTemplates = @{} ForEach ($CustomCardFile in Get-ChildItem $PSScriptRoot -Filter "*@*.txt") { $CustomCardTemplates[$CustomCardFile.BaseName] = Get-Content $CustomCardFile.VersionInfo.FileName | Out-String } $CustomCardTemplatesNK = ($CustomCardTemplates.Keys | Measure-Object).Count $CustomCardTemplatesNV = ($CustomCardTemplates.Values | Measure-Object).Count if (-not $CustomCardTemplatesNK -eq $CustomCardTemplatesNV ) { Write-Error "At least one Custom Card template file could not be read in this folder. Please check permissions and then try again. Aborting." exit } Write-Output "Uninstalling old signature card templates..." $OldTransportRules = Get-TransportRule "Signature | *" $OldTransportRules | %{ Remove-TransportRule -Identity $_.Guid.Guid -Confirm:$false } Write-Output "Installing new signature card templates..." New-TransportRule -Name "Signature | Reset" -RemoveHeader "X-SignatureCards" New-TransportRule -Name "Signature | Start" -Enabled $false ` -SentToScope "NotInOrganization" -ExceptIfHeaderMatchesMessageHeader "In-Reply-To" -ExceptIfHeaderMatchesPatterns "\w" ` -SetHeaderName "X-SignatureCards" -SetHeaderValue "Ready" ForEach ($EmailAddress in $CustomCardTemplates.Keys) { $Disclaimer = $CustomCardTemplates[$EmailAddress] New-TransportRule -Name "Signature | Custom Card | $($EmailAddress)" ` -HeaderContainsMessageHeader "X-SignatureCards" -HeaderContainsWords "Ready" ` -From $EmailAddress ` -ApplyHtmlDisclaimerLocation "Append" -ApplyHtmlDisclaimerText $Disclaimer -ApplyHtmlDisclaimerFallbackAction Wrap ` -SetHeaderName "X-SignatureCards" -SetHeaderValue "Finished" } New-TransportRule -Name "Signature | CC-1 | > IF phonenumber" ` -SenderADAttributeMatchesPatterns "phonenumber:\w" ` -HeaderContainsMessageHeader "X-SignatureCards" -HeaderContainsWords "Ready" ` -SetHeaderName "X-SignatureCards" -SetHeaderValue "CC-Scope-1" New-TransportRule -Name "Signature | CC-2 | >> IF mobilenumber" ` -SenderADAttributeMatchesPatterns "mobilenumber:\w" ` -HeaderContainsMessageHeader "X-SignatureCards" -HeaderContainsWords "CC-Scope-1" ` -SetHeaderName "X-SignatureCards" -SetHeaderValue "CC-Scope-1 CC-Scope-2" New-TransportRule -Name "Signature | CC-3 | >>> IF hasvcard" ` -FromMemberOf "hasvcard" ` -HeaderContainsMessageHeader "X-SignatureCards" -HeaderContainsWords "CC-Scope-2" ` -SetHeaderName "X-SignatureCards" -SetHeaderValue "CC-Scope-1 CC-Scope-2 CC-Scope-3" New-TransportRule -Name "Signature | CC-4 | >>>> IF initials THEN A-2" ` -SenderADAttributeMatchesPatterns "initials:\w" ` -HeaderContainsMessageHeader "X-SignatureCards" -HeaderContainsWords "CC-Scope-3" ` -ApplyHtmlDisclaimerLocation "Append" -ApplyHtmlDisclaimerText $CommonCardTemplates["A-2"] -ApplyHtmlDisclaimerFallbackAction Wrap ` -SetHeaderName "X-SignatureCards" -SetHeaderValue "Finished" New-TransportRule -Name "Signature | CC-5 | >>>> ELSE A-1" ` -ExceptIfHeaderContainsMessageHeader "X-SignatureCards" -ExceptIfHeaderContainsWords "CC-Scope-4" ` -HeaderContainsMessageHeader "X-SignatureCards" -HeaderContainsWords "CC-Scope-3" ` -ApplyHtmlDisclaimerLocation "Append" -ApplyHtmlDisclaimerText $CommonCardTemplates["A-1"] -ApplyHtmlDisclaimerFallbackAction Wrap ` -SetHeaderName "X-SignatureCards" -SetHeaderValue "Finished" New-TransportRule -Name "Signature | CC-6 | >>> ELSE A-3" ` -ExceptIfHeaderContainsMessageHeader "X-SignatureCards" -ExceptIfHeaderContainsWords "CC-Scope-3" ` -HeaderContainsMessageHeader "X-SignatureCards" -HeaderContainsWords "CC-Scope-2" ` -ApplyHtmlDisclaimerLocation "Append" -ApplyHtmlDisclaimerText $CommonCardTemplates["A-3"] -ApplyHtmlDisclaimerFallbackAction Wrap ` -SetHeaderName "X-SignatureCards" -SetHeaderValue "Finished" New-TransportRule -Name "Signature | CC-7 | >> ELSE" ` -ExceptIfHeaderContainsMessageHeader "X-SignatureCards" -ExceptIfHeaderContainsWords "CC-Scope-2" ` -HeaderContainsMessageHeader "X-SignatureCards" -HeaderContainsWords "CC-Scope-1" ` -SetHeaderName "X-SignatureCards" -SetHeaderValue "CC-Scope-1 CC-Scope-2" New-TransportRule -Name "Signature | CC-8 | >>> IF hasvcard" ` -FromMemberOf "hasvcard" ` -HeaderContainsMessageHeader "X-SignatureCards" -HeaderContainsWords "CC-Scope-2" ` -SetHeaderName "X-SignatureCards" -SetHeaderValue "CC-Scope-1 CC-Scope-2 CC-Scope-3" New-TransportRule -Name "Signature | CC-9 | >>>> IF initials THEN B-2" ` -SenderADAttributeMatchesPatterns "initials:\w" ` -HeaderContainsMessageHeader "X-SignatureCards" -HeaderContainsWords "CC-Scope-3" ` -ApplyHtmlDisclaimerLocation "Append" -ApplyHtmlDisclaimerText $CommonCardTemplates["B-2"] -ApplyHtmlDisclaimerFallbackAction Wrap ` -SetHeaderName "X-SignatureCards" -SetHeaderValue "Finished" New-TransportRule -Name "Signature | CC-10 | >>>> ELSE B-1" ` -ExceptIfHeaderContainsMessageHeader "X-SignatureCards" -ExceptIfHeaderContainsWords "CC-Scope-4" ` -HeaderContainsMessageHeader "X-SignatureCards" -HeaderContainsWords "CC-Scope-3" ` -ApplyHtmlDisclaimerLocation "Append" -ApplyHtmlDisclaimerText $CommonCardTemplates["B-1"] -ApplyHtmlDisclaimerFallbackAction Wrap ` -SetHeaderName "X-SignatureCards" -SetHeaderValue "Finished" New-TransportRule -Name "Signature | CC-11 | >>> ELSE B-3" ` -ExceptIfHeaderContainsMessageHeader "X-SignatureCards" -ExceptIfHeaderContainsWords "CC-Scope-3" ` -HeaderContainsMessageHeader "X-SignatureCards" -HeaderContainsWords "CC-Scope-2" ` -ApplyHtmlDisclaimerLocation "Append" -ApplyHtmlDisclaimerText $CommonCardTemplates["B-3"] -ApplyHtmlDisclaimerFallbackAction Wrap ` -SetHeaderName "X-SignatureCards" -SetHeaderValue "Finished" New-TransportRule -Name "Signature | CC-12 | > ELSE" ` -ExceptIfHeaderContainsMessageHeader "X-SignatureCards" -ExceptIfHeaderContainsWords "CC-Scope-1" ` -HeaderContainsMessageHeader "X-SignatureCards" -HeaderContainsWords "Ready" ` -SetHeaderName "X-SignatureCards" -SetHeaderValue "CC-Scope-1" New-TransportRule -Name "Signature | CC-13 | >> IF mobilenumber" ` -SenderADAttributeMatchesPatterns "mobilenumber:\w" ` -HeaderContainsMessageHeader "X-SignatureCards" -HeaderContainsWords "CC-Scope-1" ` -SetHeaderName "X-SignatureCards" -SetHeaderValue "CC-Scope-1 CC-Scope-2" New-TransportRule -Name "Signature | CC-14 | >>> IF hasvcard" ` -FromMemberOf "hasvcard" ` -HeaderContainsMessageHeader "X-SignatureCards" -HeaderContainsWords "CC-Scope-2" ` -SetHeaderName "X-SignatureCards" -SetHeaderValue "CC-Scope-1 CC-Scope-2 CC-Scope-3" New-TransportRule -Name "Signature | CC-15 | >>>> IF initials THEN C-2" ` -SenderADAttributeMatchesPatterns "initials:\w" ` -HeaderContainsMessageHeader "X-SignatureCards" -HeaderContainsWords "CC-Scope-3" ` -ApplyHtmlDisclaimerLocation "Append" -ApplyHtmlDisclaimerText $CommonCardTemplates["C-2"] -ApplyHtmlDisclaimerFallbackAction Wrap ` -SetHeaderName "X-SignatureCards" -SetHeaderValue "Finished" New-TransportRule -Name "Signature | CC-16 | >>>> ELSE C-1" ` -ExceptIfHeaderContainsMessageHeader "X-SignatureCards" -ExceptIfHeaderContainsWords "CC-Scope-4" ` -HeaderContainsMessageHeader "X-SignatureCards" -HeaderContainsWords "CC-Scope-3" ` -ApplyHtmlDisclaimerLocation "Append" -ApplyHtmlDisclaimerText $CommonCardTemplates["C-1"] -ApplyHtmlDisclaimerFallbackAction Wrap ` -SetHeaderName "X-SignatureCards" -SetHeaderValue "Finished" New-TransportRule -Name "Signature | CC-17 | >>> ELSE C-3" ` -ExceptIfHeaderContainsMessageHeader "X-SignatureCards" -ExceptIfHeaderContainsWords "CC-Scope-3" ` -HeaderContainsMessageHeader "X-SignatureCards" -HeaderContainsWords "CC-Scope-2" ` -ApplyHtmlDisclaimerLocation "Append" -ApplyHtmlDisclaimerText $CommonCardTemplates["C-3"] -ApplyHtmlDisclaimerFallbackAction Wrap ` -SetHeaderName "X-SignatureCards" -SetHeaderValue "Finished" New-TransportRule -Name "Signature | CC-18 | >> ELSE" ` -ExceptIfHeaderContainsMessageHeader "X-SignatureCards" -ExceptIfHeaderContainsWords "CC-Scope-2" ` -HeaderContainsMessageHeader "X-SignatureCards" -HeaderContainsWords "CC-Scope-1" ` -SetHeaderName "X-SignatureCards" -SetHeaderValue "CC-Scope-1 CC-Scope-2" New-TransportRule -Name "Signature | CC-19 | >>> IF hasvcard" ` -FromMemberOf "hasvcard" ` -HeaderContainsMessageHeader "X-SignatureCards" -HeaderContainsWords "CC-Scope-2" ` -SetHeaderName "X-SignatureCards" -SetHeaderValue "CC-Scope-1 CC-Scope-2 CC-Scope-3" New-TransportRule -Name "Signature | CC-20 | >>>> IF initials THEN D-2" ` -SenderADAttributeMatchesPatterns "initials:\w" ` -HeaderContainsMessageHeader "X-SignatureCards" -HeaderContainsWords "CC-Scope-3" ` -ApplyHtmlDisclaimerLocation "Append" -ApplyHtmlDisclaimerText $CommonCardTemplates["D-2"] -ApplyHtmlDisclaimerFallbackAction Wrap ` -SetHeaderName "X-SignatureCards" -SetHeaderValue "Finished" New-TransportRule -Name "Signature | CC-21 | >>>> ELSE D-1" ` -ExceptIfHeaderContainsMessageHeader "X-SignatureCards" -ExceptIfHeaderContainsWords "CC-Scope-4" ` -HeaderContainsMessageHeader "X-SignatureCards" -HeaderContainsWords "CC-Scope-3" ` -ApplyHtmlDisclaimerLocation "Append" -ApplyHtmlDisclaimerText $CommonCardTemplates["D-1"] -ApplyHtmlDisclaimerFallbackAction Wrap ` -SetHeaderName "X-SignatureCards" -SetHeaderValue "Finished" New-TransportRule -Name "Signature | CC-22 | >>> ELSE D-3" ` -ExceptIfHeaderContainsMessageHeader "X-SignatureCards" -ExceptIfHeaderContainsWords "CC-Scope-3" ` -HeaderContainsMessageHeader "X-SignatureCards" -HeaderContainsWords "CC-Scope-2" ` -ApplyHtmlDisclaimerLocation "Append" -ApplyHtmlDisclaimerText $CommonCardTemplates["D-3"] -ApplyHtmlDisclaimerFallbackAction Wrap ` -SetHeaderName "X-SignatureCards" -SetHeaderValue "Finished" New-TransportRule -Name "Signature | End" -RemoveHeader "X-SignatureCards" Write-Output "Enabling new signature card templates..." Enable-TransportRule -Identity "Signature | Start" Write-Output "Done."
{ "content_hash": "c8e8a17196e7886fe74a4cdb8a2b38fe", "timestamp": "", "source": "github", "line_count": 207, "max_line_length": 160, "avg_line_length": 56.54106280193237, "alnum_prop": 0.7636705399863295, "repo_name": "Lidaron/ExchangeSignatureCards", "id": "541b0e0162367be3c70b0a6f37884a99675ce693", "size": "11704", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "InstallScript.ps1", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "13539" }, { "name": "PowerShell", "bytes": "11704" } ], "symlink_target": "" }
@import UIKit; extern NSString *const kOTRProtocolLoginSuccess; extern NSString *const kOTRProtocolLoginFail; extern NSString *const kOTRProtocolLoginFailErrorKey; extern NSString *const kOTRProtocolLoginFailSSLStatusKey; extern NSString *const kOTRProtocolLoginFailHostnameKey; extern NSString *const kOTRProtocolLoginFailSSLCertificateDataKey; extern NSString *const kOTRNotificationErrorKey; extern NSString *const kOTRFacebookDomain; extern NSString *const kOTRGoogleTalkDomain; extern NSString *const kOTRProtocolTypeXMPP; extern NSString *const kOTRProtocolTypeAIM; extern NSString *const kOTRNotificationAccountNameKey; extern NSString *const kOTRNotificationUserNameKey; extern NSString *const kOTRNotificationProtocolKey; extern NSString *const kOTRNotificationBuddyUniqueIdKey; extern NSString *const kOTRXMPPAccountSendDeliveryReceiptsKey; extern NSString *const kOTRXMPPAccountSendTypingNotificationsKey; extern NSString *const kOTRXMPPResource; extern NSString *const kOTRFacebookUsernameLink; extern NSString *const kOTRFeedbackEmail; extern NSString *const kOTRServiceName; extern NSString *const kOTRCertificateServiceName; extern NSString *const kOTRSettingKeyFontSize; extern NSString *const kOTRSettingKeyDeleteOnDisconnect; extern NSString *const kOTRSettingKeyOpportunisticOtr; extern NSString *const kOTRSettingKeyShowDisconnectionWarning; extern NSString *const kOTRSettingUserAgreedToEULA; extern NSString *const kOTRSettingAccountsKey; extern NSString *const kOTRSettingKeyLanguage; extern NSString *const kOTRAppVersionKey; extern NSString *const OTRActivityTypeQRCode; extern NSString *const OTRArchiverKey; extern NSString *const FACEBOOK_APP_ID; extern NSString *const GOOGLE_APP_ID; extern NSString *const GOOGLE_APP_SCOPE; extern NSString *const OTRFailedRemoteNotificationRegistration; extern NSString *const OTRSuccessfulRemoteNotificationRegistration; extern NSString *const OTRYapDatabasePassphraseAccountName; extern NSString *const OTRYapDatabaseName; //Chatview extern CGFloat const kOTRSentDateFontSize; extern CGFloat const kOTRDeliveredFontSize; extern CGFloat const kOTRMessageFontSize; extern CGFloat const kOTRMessageSentDateLabelHeight; extern CGFloat const kOTRMessageDeliveredLabelHeight; extern NSString *const kOTRErrorDomain; extern NSUInteger const kOTRMinimumPassphraseLength; extern NSUInteger const kOTRMaximumPassphraseLength;
{ "content_hash": "c06bd11bd6ac07f94c6f1b50b62d71a3", "timestamp": "", "source": "github", "line_count": 66, "max_line_length": 67, "avg_line_length": 36.34848484848485, "alnum_prop": 0.8728636932055023, "repo_name": "riteshiosdev/iOS-UIKit", "id": "08e77e45d99782a8be568c8f0fdf67262b5ed1db", "size": "3238", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "Chat/ChatSecure-iOS-master/ChatSecure/Classes/Utilities/OTRConstants.h", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "ActionScript", "bytes": "2297" }, { "name": "C", "bytes": "196523" }, { "name": "C++", "bytes": "8369" }, { "name": "CMake", "bytes": "475" }, { "name": "CSS", "bytes": "7533" }, { "name": "Go", "bytes": "1429" }, { "name": "HTML", "bytes": "31710" }, { "name": "JavaScript", "bytes": "5607" }, { "name": "Makefile", "bytes": "2606" }, { "name": "Matlab", "bytes": "12125" }, { "name": "Objective-C", "bytes": "7133639" }, { "name": "Objective-C++", "bytes": "8125" }, { "name": "Python", "bytes": "10346" }, { "name": "Ruby", "bytes": "20795" }, { "name": "Shell", "bytes": "17711" }, { "name": "Swift", "bytes": "126947" } ], "symlink_target": "" }
CREATE TABLE [dbo].[ZZ_M_Movie_History] ( [HistoryID] INT IDENTITY (1, 1) NOT NULL, [ID] INT NOT NULL, [Year] INT NULL, [ImdbID] NVARCHAR (30) NULL, [ImdbRating] FLOAT (53) NULL, [ImdbPoster] NVARCHAR (500) NULL, [ImdbParsed] BIT NOT NULL, [ImdbLastParseDate] DATETIME NULL, [InsertDate] DATETIME NOT NULL, [InsertUserID] INT NOT NULL, [UpdateDate] DATETIME NOT NULL, [UpdateUserID] INT NOT NULL, CONSTRAINT [PK_M_Movie_History] PRIMARY KEY CLUSTERED ([HistoryID] ASC) );
{ "content_hash": "bbac4ddc68f1e809a390b1e3477c1ad5", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 75, "avg_line_length": 44.1875, "alnum_prop": 0.4893917963224894, "repo_name": "chakian/movie-archive", "id": "0bb737fdd729491c44b5444b2789d38659449142", "size": "709", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "MovieArchiveDB/dbo/Tables/ZZ_M_Movie_History.sql", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "431" }, { "name": "C#", "bytes": "611549" }, { "name": "CSS", "bytes": "11837" }, { "name": "JavaScript", "bytes": "604737" }, { "name": "PLpgSQL", "bytes": "2242" } ], "symlink_target": "" }
package swagger import ( "encoding/json" "reflect" "strings" ) // ModelBuildable is used for extending Structs that need more control over // how the Model appears in the Swagger api declaration. type ModelBuildable interface { PostBuildModel(m *Model) *Model } type modelBuilder struct { Models *ModelList Config *Config } type documentable interface { SwaggerDoc() map[string]string } // Check if this structure has a method with signature func (<theModel>) SwaggerDoc() map[string]string // If it exists, retrive the documentation and overwrite all struct tag descriptions func getDocFromMethodSwaggerDoc2(model reflect.Type) map[string]string { if docable, ok := reflect.New(model).Elem().Interface().(documentable); ok { return docable.SwaggerDoc() } return make(map[string]string) } // addModelFrom creates and adds a Model to the builder and detects and calls // the post build hook for customizations func (b modelBuilder) addModelFrom(sample interface{}) { if modelOrNil := b.addModel(reflect.TypeOf(sample), ""); modelOrNil != nil { // allow customizations if buildable, ok := sample.(ModelBuildable); ok { modelOrNil = buildable.PostBuildModel(modelOrNil) b.Models.Put(modelOrNil.Id, *modelOrNil) } } } func (b modelBuilder) addModel(st reflect.Type, nameOverride string) *Model { modelName := b.keyFrom(st) if nameOverride != "" { modelName = nameOverride } // no models needed for primitive types if b.isPrimitiveType(modelName) { return nil } // golang encoding/json packages says array and slice values encode as // JSON arrays, except that []byte encodes as a base64-encoded string. // If we see a []byte here, treat it at as a primitive type (string) // and deal with it in buildArrayTypeProperty. if (st.Kind() == reflect.Slice || st.Kind() == reflect.Array) && st.Elem().Kind() == reflect.Uint8 { return nil } // see if we already have visited this model if _, ok := b.Models.At(modelName); ok { return nil } sm := Model{ Id: modelName, Required: []string{}, Properties: ModelPropertyList{}} // reference the model before further initializing (enables recursive structs) b.Models.Put(modelName, sm) // check for slice or array if st.Kind() == reflect.Slice || st.Kind() == reflect.Array { b.addModel(st.Elem(), "") return &sm } // check for structure or primitive type if st.Kind() != reflect.Struct { return &sm } fullDoc := getDocFromMethodSwaggerDoc2(st) modelDescriptions := []string{} for i := 0; i < st.NumField(); i++ { field := st.Field(i) jsonName, modelDescription, prop := b.buildProperty(field, &sm, modelName) if len(modelDescription) > 0 { modelDescriptions = append(modelDescriptions, modelDescription) } // add if not omitted if len(jsonName) != 0 { // update description if fieldDoc, ok := fullDoc[jsonName]; ok { prop.Description = fieldDoc } // update Required if b.isPropertyRequired(field) { sm.Required = append(sm.Required, jsonName) } sm.Properties.Put(jsonName, prop) } } // We always overwrite documentation if SwaggerDoc method exists // "" is special for documenting the struct itself if modelDoc, ok := fullDoc[""]; ok { sm.Description = modelDoc } else if len(modelDescriptions) != 0 { sm.Description = strings.Join(modelDescriptions, "\n") } // update model builder with completed model b.Models.Put(modelName, sm) return &sm } func (b modelBuilder) isPropertyRequired(field reflect.StructField) bool { required := true if jsonTag := field.Tag.Get("json"); jsonTag != "" { s := strings.Split(jsonTag, ",") if len(s) > 1 && s[1] == "omitempty" { return false } } return required } func (b modelBuilder) buildProperty(field reflect.StructField, model *Model, modelName string) (jsonName, modelDescription string, prop ModelProperty) { jsonName = b.jsonNameOfField(field) if len(jsonName) == 0 { // empty name signals skip property return "", "", prop } if field.Name == "XMLName" && field.Type.String() == "xml.Name" { // property is metadata for the xml.Name attribute, can be skipped return "", "", prop } if tag := field.Tag.Get("modelDescription"); tag != "" { modelDescription = tag } prop.setPropertyMetadata(field) if prop.Type != nil { return jsonName, modelDescription, prop } fieldType := field.Type // check if type is doing its own marshalling marshalerType := reflect.TypeOf((*json.Marshaler)(nil)).Elem() if fieldType.Implements(marshalerType) { var pType = "string" if prop.Type == nil { prop.Type = &pType } if prop.Format == "" { prop.Format = b.jsonSchemaFormat(fieldType.String()) } return jsonName, modelDescription, prop } // check if annotation says it is a string if jsonTag := field.Tag.Get("json"); jsonTag != "" { s := strings.Split(jsonTag, ",") if len(s) > 1 && s[1] == "string" { stringt := "string" prop.Type = &stringt return jsonName, modelDescription, prop } } fieldKind := fieldType.Kind() switch { case fieldKind == reflect.Struct: jsonName, prop := b.buildStructTypeProperty(field, jsonName, model) return jsonName, modelDescription, prop case fieldKind == reflect.Slice || fieldKind == reflect.Array: jsonName, prop := b.buildArrayTypeProperty(field, jsonName, modelName) return jsonName, modelDescription, prop case fieldKind == reflect.Ptr: jsonName, prop := b.buildPointerTypeProperty(field, jsonName, modelName) return jsonName, modelDescription, prop case fieldKind == reflect.String: stringt := "string" prop.Type = &stringt return jsonName, modelDescription, prop case fieldKind == reflect.Map: // if it's a map, it's unstructured, and swagger 1.2 can't handle it objectType := "object" prop.Type = &objectType return jsonName, modelDescription, prop } if b.isPrimitiveType(fieldType.String()) { mapped := b.jsonSchemaType(fieldType.String()) prop.Type = &mapped prop.Format = b.jsonSchemaFormat(fieldType.String()) return jsonName, modelDescription, prop } modelType := fieldType.String() prop.Ref = &modelType if fieldType.Name() == "" { // override type of anonymous structs nestedTypeName := modelName + "." + jsonName prop.Ref = &nestedTypeName b.addModel(fieldType, nestedTypeName) } return jsonName, modelDescription, prop } func hasNamedJSONTag(field reflect.StructField) bool { parts := strings.Split(field.Tag.Get("json"), ",") if len(parts) == 0 { return false } for _, s := range parts[1:] { if s == "inline" { return false } } return len(parts[0]) > 0 } func (b modelBuilder) buildStructTypeProperty(field reflect.StructField, jsonName string, model *Model) (nameJson string, prop ModelProperty) { prop.setPropertyMetadata(field) // Check for type override in tag if prop.Type != nil { return jsonName, prop } fieldType := field.Type // check for anonymous if len(fieldType.Name()) == 0 { // anonymous anonType := model.Id + "." + jsonName b.addModel(fieldType, anonType) prop.Ref = &anonType return jsonName, prop } if field.Name == fieldType.Name() && field.Anonymous && !hasNamedJSONTag(field) { // embedded struct sub := modelBuilder{new(ModelList), b.Config} sub.addModel(fieldType, "") subKey := sub.keyFrom(fieldType) // merge properties from sub subModel, _ := sub.Models.At(subKey) subModel.Properties.Do(func(k string, v ModelProperty) { model.Properties.Put(k, v) // if subModel says this property is required then include it required := false for _, each := range subModel.Required { if k == each { required = true break } } if required { model.Required = append(model.Required, k) } }) // add all new referenced models sub.Models.Do(func(key string, sub Model) { if key != subKey { if _, ok := b.Models.At(key); !ok { b.Models.Put(key, sub) } } }) // empty name signals skip property return "", prop } // simple struct b.addModel(fieldType, "") var pType = fieldType.String() prop.Ref = &pType return jsonName, prop } func (b modelBuilder) buildArrayTypeProperty(field reflect.StructField, jsonName, modelName string) (nameJson string, prop ModelProperty) { // check for type override in tags prop.setPropertyMetadata(field) if prop.Type != nil { return jsonName, prop } fieldType := field.Type if fieldType.Elem().Kind() == reflect.Uint8 { stringt := "string" prop.Type = &stringt return jsonName, prop } var pType = "array" prop.Type = &pType isPrimitive := b.isPrimitiveType(fieldType.Elem().Name()) elemTypeName := b.getElementTypeName(modelName, jsonName, fieldType.Elem()) prop.Items = new(Item) if isPrimitive { mapped := b.jsonSchemaType(elemTypeName) prop.Items.Type = &mapped } else { prop.Items.Ref = &elemTypeName } // add|overwrite model for element type if fieldType.Elem().Kind() == reflect.Ptr { fieldType = fieldType.Elem() } if !isPrimitive { b.addModel(fieldType.Elem(), elemTypeName) } return jsonName, prop } func (b modelBuilder) buildPointerTypeProperty(field reflect.StructField, jsonName, modelName string) (nameJson string, prop ModelProperty) { prop.setPropertyMetadata(field) // Check for type override in tags if prop.Type != nil { return jsonName, prop } fieldType := field.Type // override type of pointer to list-likes if fieldType.Elem().Kind() == reflect.Slice || fieldType.Elem().Kind() == reflect.Array { var pType = "array" prop.Type = &pType isPrimitive := b.isPrimitiveType(fieldType.Elem().Elem().Name()) elemName := b.getElementTypeName(modelName, jsonName, fieldType.Elem().Elem()) if isPrimitive { primName := b.jsonSchemaType(elemName) prop.Items = &Item{Ref: &primName} } else { prop.Items = &Item{Ref: &elemName} } if !isPrimitive { // add|overwrite model for element type b.addModel(fieldType.Elem().Elem(), elemName) } } else { // non-array, pointer type var pType = b.jsonSchemaType(fieldType.String()[1:]) // no star, include pkg path if b.isPrimitiveType(fieldType.String()[1:]) { prop.Type = &pType prop.Format = b.jsonSchemaFormat(fieldType.String()[1:]) return jsonName, prop } prop.Ref = &pType elemName := "" if fieldType.Elem().Name() == "" { elemName = modelName + "." + jsonName prop.Ref = &elemName } b.addModel(fieldType.Elem(), elemName) } return jsonName, prop } func (b modelBuilder) getElementTypeName(modelName, jsonName string, t reflect.Type) string { if t.Kind() == reflect.Ptr { return t.String()[1:] } if t.Name() == "" { return modelName + "." + jsonName } return b.keyFrom(t) } func (b modelBuilder) keyFrom(st reflect.Type) string { key := st.String() if len(st.Name()) == 0 { // unnamed type // Swagger UI has special meaning for [ key = strings.Replace(key, "[]", "||", -1) } return key } // see also https://golang.org/ref/spec#Numeric_types func (b modelBuilder) isPrimitiveType(modelName string) bool { if len(modelName) == 0 { return false } return strings.Contains("uint uint8 uint16 uint32 uint64 int int8 int16 int32 int64 float32 float64 bool string byte rune time.Time", modelName) } // jsonNameOfField returns the name of the field as it should appear in JSON format // An empty string indicates that this field is not part of the JSON representation func (b modelBuilder) jsonNameOfField(field reflect.StructField) string { if jsonTag := field.Tag.Get("json"); jsonTag != "" { s := strings.Split(jsonTag, ",") if s[0] == "-" { // empty name signals skip property return "" } else if s[0] != "" { return s[0] } } return field.Name } // see also http://json-schema.org/latest/json-schema-core.html#anchor8 func (b modelBuilder) jsonSchemaType(modelName string) string { schemaMap := map[string]string{ "uint": "integer", "uint8": "integer", "uint16": "integer", "uint32": "integer", "uint64": "integer", "int": "integer", "int8": "integer", "int16": "integer", "int32": "integer", "int64": "integer", "byte": "integer", "float64": "number", "float32": "number", "bool": "boolean", "time.Time": "string", } mapped, ok := schemaMap[modelName] if !ok { return modelName // use as is (custom or struct) } return mapped } func (b modelBuilder) jsonSchemaFormat(modelName string) string { if b.Config != nil && b.Config.SchemaFormatHandler != nil { if mapped := b.Config.SchemaFormatHandler(modelName); mapped != "" { return mapped } } schemaMap := map[string]string{ "int": "int32", "int32": "int32", "int64": "int64", "byte": "byte", "uint": "integer", "uint8": "byte", "float64": "double", "float32": "float", "time.Time": "date-time", "*time.Time": "date-time", } mapped, ok := schemaMap[modelName] if !ok { return "" // no format } return mapped }
{ "content_hash": "3d55c9ee80905eb1aaf58d39497d399a", "timestamp": "", "source": "github", "line_count": 454, "max_line_length": 152, "avg_line_length": 28.389867841409693, "alnum_prop": 0.6810458530529909, "repo_name": "timoreimann/kubernetes-goclient-example", "id": "be58871d9dee20d710208a695163cf08b6a8fd63", "size": "12889", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "vendor/github.com/emicklei/go-restful/swagger/model_builder.go", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "8309" }, { "name": "Shell", "bytes": "1320" } ], "symlink_target": "" }
using System; using System.Net; using System.Net.Sockets; using System.Text.RegularExpressions; using IPTables.Net.Exceptions; namespace IPTables.Net.Iptables.DataTypes { public struct IPPortOrRange { private static Regex ParsePattern = new Regex( @"^(?:(?:(?:\[(?<ip1_1>[0-9a-fA-f\:]+)\]-)?\[(?<ip2_1>[0-9a-fA-f\:]+)\](?::(?<port_1>[0-9\-]+))?)|(?:(?:(?<ip1_2>[0-9\.]+)-)?(?<ip2_2>[0-9\.]+)(?::(?<port_2>[0-9\-]+))?)|(?:(?:(?<ip1_3>[0-9a-fA-f\:]+)-)?(?<ip2_3>[0-9a-fA-f\:]+)))$"); private readonly IPAddress _lowerAddress; private readonly IPAddress _upperAddress; private PortOrRange _port; public IPPortOrRange(IPAddress lowerAddress, IPAddress upperAddress, PortOrRange port) { _lowerAddress = lowerAddress; _upperAddress = upperAddress; _port = port; } public IPPortOrRange(IPAddress lowerAddress, IPAddress upperAddress) { _lowerAddress = lowerAddress; _upperAddress = upperAddress; _port = PortOrRange.Any; } public IPPortOrRange(IPAddress lowerAddress, PortOrRange port) { _upperAddress = _lowerAddress = lowerAddress; _port = port; } public IPPortOrRange(IPAddress lowerAddress) { _upperAddress = _lowerAddress = lowerAddress; _port = PortOrRange.Any; } public IPAddress LowerAddress => _lowerAddress; public IPAddress UpperAddress => _upperAddress; public PortOrRange Port => _port; private string PortStringRepresentation() { if (_port.LowerPort == 0 && _port.UpperPort == 0) return ""; return _port.ToString(); } public override string ToString() { var strPort = PortStringRepresentation(); if (LowerAddress.Equals(UpperAddress)) { if (strPort.Length == 0) return LowerAddress.ToString(); return FormatIp(LowerAddress) + ":" + PortStringRepresentation(); } if (strPort.Length == 0) return string.Format("{0}-{1}", FormatIp(LowerAddress), FormatIp(UpperAddress)); return string.Format("{0}-{1}:{2}", FormatIp(LowerAddress), FormatIp(UpperAddress), strPort); } private string FormatIp(IPAddress ip) { if (ip.AddressFamily == AddressFamily.InterNetworkV6) return "[" + ip + "]"; return ip.ToString(); } public static IPPortOrRange Parse(string getNextArg) { var match = ParsePattern.Match(getNextArg); if (!match.Success) throw new ArgumentException("Invalid IP port or range format"); IPAddress lowerIp = null; IPAddress upperIp = null; string port = null; for (var i = 0; i < match.Groups.Count; i++) { var g = match.Groups[i]; if (g.Value == "") continue; var name = ParsePattern.GroupNameFromNumber(i); if (name == "ip1_1" || name == "ip1_2" || name == "ip1_3") lowerIp = IPAddress.Parse(g.Value); else if (name == "ip2_1" || name == "ip2_2" || name == "ip2_3") upperIp = IPAddress.Parse(g.Value); else if (name == "port_1" || name == "port_2" || name == "port_3") port = g.Value; } if (lowerIp == null) lowerIp = upperIp; if (port == null) return new IPPortOrRange(lowerIp, upperIp); return new IPPortOrRange(lowerIp, upperIp, PortOrRange.Parse(port, '-')); } } }
{ "content_hash": "19bb996f54a67cf2a7e4029339b03b77", "timestamp": "", "source": "github", "line_count": 105, "max_line_length": 245, "avg_line_length": 35.34285714285714, "alnum_prop": 0.5443276744812718, "repo_name": "splitice/IPTables.Net", "id": "b0e20c8c9e18841ec318477e34e115273b377657", "size": "3713", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "IPTables.Net/Iptables/DataTypes/IPPortOrRange.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "208687" }, { "name": "C#", "bytes": "689675" }, { "name": "C++", "bytes": "19359" }, { "name": "Makefile", "bytes": "7342" }, { "name": "Shell", "bytes": "1248" } ], "symlink_target": "" }
'use strict'; describe('PIXI.Container', function () { describe('parent', function () { it('should be present when adding children to Container', function () { const container = new PIXI.Container(); const child = new PIXI.DisplayObject(); expect(container.children.length).to.be.equals(0); container.addChild(child); expect(container.children.length).to.be.equals(1); expect(child.parent).to.be.equals(container); }); }); describe('events', function () { it('should trigger "added" and "removed" events on its children', function () { const container = new PIXI.Container(); const child = new PIXI.DisplayObject(); let triggeredAdded = false; let triggeredRemoved = false; child.on('added', (to) => { triggeredAdded = true; expect(container.children.length).to.be.equals(1); expect(child.parent).to.be.equals(to); }); child.on('removed', (from) => { triggeredRemoved = true; expect(container.children.length).to.be.equals(0); expect(child.parent).to.be.null; expect(container).to.be.equals(from); }); container.addChild(child); expect(triggeredAdded).to.be.true; expect(triggeredRemoved).to.be.false; container.removeChild(child); expect(triggeredRemoved).to.be.true; }); }); describe('addChild', function () { it('should remove from current parent', function () { const parent = new PIXI.Container(); const container = new PIXI.Container(); const child = new PIXI.DisplayObject(); assertRemovedFromParent(parent, container, child, () => { container.addChild(child); }); }); it('should call onChildrenChange', function () { const container = new PIXI.Container(); const child = new PIXI.DisplayObject(); const spy = sinon.spy(container, 'onChildrenChange'); container.addChild(child); expect(spy).to.have.been.called; expect(spy).to.have.been.calledWith(0); }); }); describe('removeChildAt', function () { it('should remove from current parent', function () { const parent = new PIXI.Container(); const child = new PIXI.DisplayObject(); assertRemovedFromParent(parent, null, child, () => { parent.removeChildAt(0); }); }); it('should call onChildrenChange', function () { const container = new PIXI.Container(); const child = new PIXI.DisplayObject(); container.addChild(child); const spy = sinon.spy(container, 'onChildrenChange'); container.removeChildAt(0); expect(spy).to.have.been.called; expect(spy).to.have.been.calledWith(0); }); }); describe('addChildAt', function () { it('should allow placements at start', function () { const container = new PIXI.Container(); const child = new PIXI.DisplayObject(); container.addChild(new PIXI.DisplayObject()); container.addChildAt(child, 0); expect(container.children.length).to.be.equals(2); expect(container.children[0]).to.be.equals(child); }); it('should allow placements at end', function () { const container = new PIXI.Container(); const child = new PIXI.DisplayObject(); container.addChild(new PIXI.DisplayObject()); container.addChildAt(child, 1); expect(container.children.length).to.be.equals(2); expect(container.children[1]).to.be.equals(child); }); it('should throw on out-of-bounds', function () { const container = new PIXI.Container(); const child = new PIXI.DisplayObject(); container.addChild(new PIXI.DisplayObject()); expect(() => container.addChildAt(child, -1)).to.throw('The index -1 supplied is out of bounds 1'); expect(() => container.addChildAt(child, 2)).to.throw('The index 2 supplied is out of bounds 1'); }); it('should remove from current parent', function () { const parent = new PIXI.Container(); const container = new PIXI.Container(); const child = new PIXI.DisplayObject(); assertRemovedFromParent(parent, container, child, () => { container.addChildAt(child, 0); }); }); it('should call onChildrenChange', function () { const container = new PIXI.Container(); const child = new PIXI.DisplayObject(); container.addChild(new PIXI.DisplayObject()); const spy = sinon.spy(container, 'onChildrenChange'); container.addChildAt(child, 0); expect(spy).to.have.been.called; expect(spy).to.have.been.calledWith(0); }); }); describe('removeChild', function () { it('should ignore non-children', function () { const container = new PIXI.Container(); const child = new PIXI.DisplayObject(); container.addChild(child); container.removeChild(new PIXI.DisplayObject()); expect(container.children.length).to.be.equals(1); }); it('should remove all children supplied', function () { const container = new PIXI.Container(); const child1 = new PIXI.DisplayObject(); const child2 = new PIXI.DisplayObject(); container.addChild(child1, child2); expect(container.children.length).to.be.equals(2); container.removeChild(child1, child2); expect(container.children.length).to.be.equals(0); }); it('should call onChildrenChange', function () { const container = new PIXI.Container(); const child = new PIXI.DisplayObject(); container.addChild(child); const spy = sinon.spy(container, 'onChildrenChange'); container.removeChild(child); expect(spy).to.have.been.called; expect(spy).to.have.been.calledWith(0); }); }); describe('getChildIndex', function () { it('should return the correct index', function () { const container = new PIXI.Container(); const child = new PIXI.DisplayObject(); container.addChild(new PIXI.DisplayObject(), child, new PIXI.DisplayObject()); expect(container.getChildIndex(child)).to.be.equals(1); }); it('should throw when child does not exist', function () { const container = new PIXI.Container(); const child = new PIXI.DisplayObject(); expect(() => container.getChildIndex(child)) .to.throw('The supplied DisplayObject must be a child of the caller'); }); }); describe('getChildAt', function () { it('should throw when out-of-bounds', () => { const container = new PIXI.Container(); expect(() => container.getChildAt(-1)).to.throw('getChildAt: Index (-1) does not exist.'); expect(() => container.getChildAt(1)).to.throw('getChildAt: Index (1) does not exist.'); }); }); describe('setChildIndex', function () { it('should throw on out-of-bounds', function () { const container = new PIXI.Container(); const child = new PIXI.DisplayObject(); container.addChild(child); expect(() => container.setChildIndex(child, -1)).to.throw('The supplied index is out of bounds'); expect(() => container.setChildIndex(child, 1)).to.throw('The supplied index is out of bounds'); }); it('should throw when child does not belong', function () { const container = new PIXI.Container(); const child = new PIXI.DisplayObject(); container.addChild(new PIXI.DisplayObject()); expect(() => container.setChildIndex(child, 0)) .to.throw('The supplied DisplayObject must be a child of the caller'); }); it('should set index', function () { const container = new PIXI.Container(); const child = new PIXI.DisplayObject(); container.addChild(child, new PIXI.DisplayObject(), new PIXI.DisplayObject()); expect(container.children.indexOf(child)).to.be.equals(0); container.setChildIndex(child, 1); expect(container.children.indexOf(child)).to.be.equals(1); container.setChildIndex(child, 2); expect(container.children.indexOf(child)).to.be.equals(2); container.setChildIndex(child, 0); expect(container.children.indexOf(child)).to.be.equals(0); }); it('should call onChildrenChange', function () { const container = new PIXI.Container(); const child = new PIXI.DisplayObject(); container.addChild(child, new PIXI.DisplayObject()); const spy = sinon.spy(container, 'onChildrenChange'); container.setChildIndex(child, 1); expect(spy).to.have.been.called; expect(spy).to.have.been.calledWith(1); }); }); describe('swapChildren', function () { it('should call onChildrenChange', function () { const container = new PIXI.Container(); const child1 = new PIXI.DisplayObject(); const child2 = new PIXI.DisplayObject(); container.addChild(child1, child2); const spy = sinon.spy(container, 'onChildrenChange'); container.swapChildren(child1, child2); expect(spy).to.have.been.called; expect(spy).to.have.been.calledWith(0); // second call required to complete returned index coverage container.swapChildren(child1, child2); expect(spy).to.have.been.calledTwice; expect(spy).to.have.been.calledWith(0); }); it('should not call onChildrenChange if supplied children are equal', function () { const container = new PIXI.Container(); const child = new PIXI.DisplayObject(); container.addChild(child, new PIXI.DisplayObject()); const spy = sinon.spy(container, 'onChildrenChange'); container.swapChildren(child, child); expect(spy).to.not.have.been.called; }); it('should throw if children do not belong', function () { const container = new PIXI.Container(); const child = new PIXI.Container(); container.addChild(child, new PIXI.DisplayObject()); expect(() => container.swapChildren(child, new PIXI.DisplayObject())) .to.throw('The supplied DisplayObject must be a child of the caller'); expect(() => container.swapChildren(new PIXI.DisplayObject(), child)) .to.throw('The supplied DisplayObject must be a child of the caller'); }); it('should result in swapped child positions', function () { const container = new PIXI.Container(); const child1 = new PIXI.DisplayObject(); const child2 = new PIXI.DisplayObject(); container.addChild(child1, child2); expect(container.children.indexOf(child1)).to.be.equals(0); expect(container.children.indexOf(child2)).to.be.equals(1); container.swapChildren(child1, child2); expect(container.children.indexOf(child2)).to.be.equals(0); expect(container.children.indexOf(child1)).to.be.equals(1); }); }); describe('render', function () { it('should not render when object not visible', function () { const container = new PIXI.Container(); const webGLSpy = sinon.spy(container._renderWebGL); const canvasSpy = sinon.spy(container._renderCanvas); container.visible = false; container.renderWebGL(); expect(webGLSpy).to.not.have.been.called; container.renderCanvas(); expect(canvasSpy).to.not.have.been.called; }); it('should not render when alpha is zero', function () { const container = new PIXI.Container(); const webGLSpy = sinon.spy(container._renderWebGL); const canvasSpy = sinon.spy(container._renderCanvas); container.worldAlpha = 0; container.renderWebGL(); expect(webGLSpy).to.not.have.been.called; container.renderCanvas(); expect(canvasSpy).to.not.have.been.called; }); it('should not render when object not renderable', function () { const container = new PIXI.Container(); const webGLSpy = sinon.spy(container._renderWebGL); const canvasSpy = sinon.spy(container._renderCanvas); container.renderable = false; container.renderWebGL(); expect(webGLSpy).to.not.have.been.called; container.renderCanvas(); expect(canvasSpy).to.not.have.been.called; }); it('should render children', function () { const container = new PIXI.Container(); const child = new PIXI.Container(); const webGLSpy = sinon.spy(child, '_renderWebGL'); const canvasSpy = sinon.spy(child, '_renderCanvas'); container.addChild(child); container.renderWebGL(); expect(webGLSpy).to.have.been.called; container.renderCanvas(); expect(canvasSpy).to.have.been.called; }); }); describe('removeChildren', function () { it('should remove all children when no arguments supplied', function () { const container = new PIXI.Container(); let removed = []; container.addChild(new PIXI.DisplayObject(), new PIXI.DisplayObject(), new PIXI.DisplayObject()); expect(container.children.length).to.be.equals(3); removed = container.removeChildren(); expect(container.children.length).to.be.equals(0); expect(removed.length).to.be.equals(3); }); it('should return empty array if no children', function () { const container = new PIXI.Container(); const removed = container.removeChildren(); expect(removed.length).to.be.equals(0); }); it('should handle a range greater than length', function () { const container = new PIXI.Container(); let removed = []; container.addChild(new PIXI.DisplayObject()); removed = container.removeChildren(0, 2); expect(removed.length).to.be.equals(1); }); it('should throw outside acceptable range', function () { const container = new PIXI.Container(); container.addChild(new PIXI.DisplayObject()); expect(() => container.removeChildren(2)) .to.throw('removeChildren: numeric values are outside the acceptable range.'); expect(() => container.removeChildren(-1)) .to.throw('removeChildren: numeric values are outside the acceptable range.'); expect(() => container.removeChildren(-1, 1)) .to.throw('removeChildren: numeric values are outside the acceptable range.'); }); }); describe('destroy', function () { it('should not destroy children by default', function () { const container = new PIXI.Container(); const child = new PIXI.DisplayObject(); container.addChild(child); container.destroy(); expect(container.children.length).to.be.equals(0); expect(child.transform).to.not.be.null; }); it('should allow children destroy', function () { let container = new PIXI.Container(); let child = new PIXI.DisplayObject(); container.addChild(child); container.destroy({ children: true }); expect(container.children.length).to.be.equals(0); expect(container.transform).to.be.null; expect(child.transform).to.be.null; container = new PIXI.Container(); child = new PIXI.DisplayObject(); container.addChild(child); container.destroy(true); expect(container.children.length).to.be.equals(0); expect(container.transform).to.be.null; expect(child.transform).to.be.null; }); }); describe('width', function () { it('should reflect scale', function () { const container = new PIXI.Container(); const graphics = new PIXI.Graphics(); graphics.drawRect(0, 0, 10, 10); container.addChild(graphics); container.scale.x = 2; expect(container.width).to.be.equals(20); }); it('should adjust scale', function () { const container = new PIXI.Container(); const graphics = new PIXI.Graphics(); graphics.drawRect(0, 0, 10, 10); container.addChild(graphics); container.width = 20; expect(container.width).to.be.equals(20); expect(container.scale.x).to.be.equals(2); }); it('should reset scale', function () { const container = new PIXI.Container(); container.scale.x = 2; container.width = 5; expect(container.width).to.be.equals(0); expect(container.scale.x).to.be.equals(1); }); }); describe('height', function () { it('should reflect scale', function () { const container = new PIXI.Container(); const graphics = new PIXI.Graphics(); graphics.drawRect(0, 0, 10, 10); container.addChild(graphics); container.scale.y = 2; expect(container.height).to.be.equals(20); }); it('should adjust scale', function () { const container = new PIXI.Container(); const graphics = new PIXI.Graphics(); graphics.drawRect(0, 0, 10, 10); container.addChild(graphics); container.height = 20; expect(container.height).to.be.equals(20); expect(container.scale.y).to.be.equals(2); }); it('should reset scale', function () { const container = new PIXI.Container(); container.scale.y = 2; container.height = 5; expect(container.height).to.be.equals(0); expect(container.scale.y).to.be.equals(1); }); }); function assertRemovedFromParent(parent, container, child, functionToAssert) { parent.addChild(child); expect(parent.children.length).to.be.equals(1); expect(child.parent).to.be.equals(parent); functionToAssert(); expect(parent.children.length).to.be.equals(0); expect(child.parent).to.be.equals(container); } });
{ "content_hash": "77a2ca2b814ae37792c4269dd267ca90", "timestamp": "", "source": "github", "line_count": 610, "max_line_length": 111, "avg_line_length": 32.64590163934426, "alnum_prop": 0.56342271768605, "repo_name": "out-of-band/pixi.js", "id": "2d6518f1018c5d41b424115d397fd6f5ed9e1d65", "size": "19914", "binary": false, "copies": "1", "ref": "refs/heads/dev", "path": "test/core/Container.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2922" }, { "name": "GLSL", "bytes": "11291" }, { "name": "HTML", "bytes": "1261" }, { "name": "JavaScript", "bytes": "929949" } ], "symlink_target": "" }
namespace balls { SphericalConeMesh::SphericalConeMesh(QObject *parent) : BaseCylindricalMesh(parent, Type::SphericalCone) { m_radius = 1.0; m_size = 1.0; m_slices = 32u; m_segments = 8u; m_rings = 4u; m_start = 0.0; m_sweep = 360.0; updateMesh(); } void SphericalConeMesh::setRings(unsigned int rings) { if (rings != m_rings) { // If the user actually adjusted the number of rings... m_rings = rings; updateMesh(); } } void SphericalConeMesh::assignMesh() { m_mesh = generator::SphericalConeMesh( m_radius, m_size, m_slices, m_segments, m_rings, glm::radians(m_start), glm::radians(m_sweep)); } }
{ "content_hash": "a7fa84ea45b6ccc5dab5e22be0828c7c", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 59, "avg_line_length": 20.151515151515152, "alnum_prop": 0.637593984962406, "repo_name": "JesseTG/BALLS", "id": "a2dd84fabb5614dcf8bc5a1e86db445e071984eb", "size": "807", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "BALLS/model/mesh/SphericalConeMesh.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "424590" }, { "name": "CMake", "bytes": "197139" }, { "name": "GLSL", "bytes": "2137" }, { "name": "JavaScript", "bytes": "3188" }, { "name": "Shell", "bytes": "438" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <!-- Copyright (C) 2006 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@android:id/text1" android:layout_width="fill_parent" android:layout_height="?android:attr/listPreferredItemHeight" android:paddingLeft="?android:attr/expandableListPreferredItemPaddingLeft" android:textAppearance="?android:attr/textAppearanceLarge" android:gravity="center_vertical" />
{ "content_hash": "e0b179e28c4f94ab1a0b135131b6ed46", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 78, "avg_line_length": 44.458333333333336, "alnum_prop": 0.7357075913776945, "repo_name": "joewalnes/idea-community", "id": "052b35377326b55ad383c27ac4cf07118459feac", "size": "1067", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "plugins/android/testData/sdk1.5/platforms/android-1.5/data/res/layout/simple_expandable_list_item_1.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ActionScript", "bytes": "387" }, { "name": "C", "bytes": "136045" }, { "name": "C#", "bytes": "103" }, { "name": "C++", "bytes": "40449" }, { "name": "Emacs Lisp", "bytes": "2507" }, { "name": "Erlang", "bytes": "10" }, { "name": "Groovy", "bytes": "361320" }, { "name": "Java", "bytes": "89694599" }, { "name": "JavaScript", "bytes": "978" }, { "name": "Objective-C", "bytes": "1877" }, { "name": "PHP", "bytes": "145" }, { "name": "Perl", "bytes": "6523" }, { "name": "Python", "bytes": "1699274" }, { "name": "Shell", "bytes": "6965" }, { "name": "VimL", "bytes": "5950" } ], "symlink_target": "" }
/* */ package com.googlecode.objectify.test; import java.util.HashMap; import java.util.Map; import java.util.logging.Logger; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.Entity; import com.googlecode.objectify.Key; import com.googlecode.objectify.TranslateException; import com.googlecode.objectify.annotation.AlsoLoad; import com.googlecode.objectify.annotation.Cache; import com.googlecode.objectify.annotation.Id; import com.googlecode.objectify.annotation.IgnoreLoad; import com.googlecode.objectify.test.util.TestBase; import com.googlecode.objectify.test.util.TestObjectify; /** * More tests of using the @AlsoLoad annotation * * @author Jeff Schnitzer <jeff@infohazard.org> */ public class AlsoLoadTests2 extends TestBase { /** */ @SuppressWarnings("unused") private static Logger log = Logger.getLogger(AlsoLoadTests2.class.getName()); /** */ public static final String TEST_VALUE = "blah"; /** */ @com.googlecode.objectify.annotation.Entity @Cache static class MethodOverridesField { @Id Long id; @IgnoreLoad String foo; String bar; public void set(@AlsoLoad("foo") String overrides) { this.bar = overrides; } } /** * Add an entry to the database that should never come back from null queries. */ @BeforeMethod public void setUp() { super.setUp(); this.fact.register(MethodOverridesField.class); } /** */ @Test public void testMethodOverridingField() throws Exception { TestObjectify ofy = this.fact.begin(); com.google.appengine.api.datastore.Entity ent = new com.google.appengine.api.datastore.Entity(Key.getKind(MethodOverridesField.class)); ent.setProperty("foo", TEST_VALUE); ds().put(ent); Key<MethodOverridesField> key = Key.create(ent.getKey()); MethodOverridesField fetched = ofy.load().key(key).get(); assert fetched.foo == null; assert fetched.bar.equals(TEST_VALUE); } @com.googlecode.objectify.annotation.Entity public static class HasMap { @Id Long id; @AlsoLoad("alsoPrimitives") Map<String, Long> primitives = new HashMap<String, Long>(); } @Test public void testAlsoLoadMap() throws Exception { this.fact.register(HasMap.class); TestObjectify ofy = this.fact.begin(); DatastoreService ds = ds(); Entity ent = new Entity(Key.getKind(HasMap.class)); ent.setProperty("alsoPrimitives.one", 1L); ent.setProperty("primitives.two", 2L); ds.put(ent); Key<HasMap> key = Key.create(ent.getKey()); try { ofy.load().key(key).get(); assert false; } catch (TranslateException ex) { // couldn't load conflicting values } } }
{ "content_hash": "831224785d30d1e787e9f27d73eb6826", "timestamp": "", "source": "github", "line_count": 111, "max_line_length": 137, "avg_line_length": 25.47747747747748, "alnum_prop": 0.7033239038189534, "repo_name": "gvaish/attic-objectify-appengine", "id": "250bbf3332a3360cc883d09b4e35bea83fec1df6", "size": "2828", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src-test/com/googlecode/objectify/test/AlsoLoadTests2.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "775120" } ], "symlink_target": "" }
require 'spec_helper' Feature 'top-level feature block' do end Ability 'top-level ability block' do end Story 'top-level story block' do end Component 'top-level component block' do end Workflow 'top-level workflow block' do end
{ "content_hash": "055c48758f2b2c1d2cebbcb7af8b8ef2", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 40, "avg_line_length": 14.5625, "alnum_prop": 0.7682403433476395, "repo_name": "jnyman/specify", "id": "4fdd1da3e3f840b73e8315f418a52e0901baa3dd", "size": "233", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/top_level_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "17277" }, { "name": "Shell", "bytes": "58" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.jawnnypoo.geotune" android:installLocation="internalOnly"> <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" /> <!-- To restore previously registered geofences --> <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> <!-- Required for Maps --> <uses-permission android:name="android.permission.INTERNET" /> <!-- Geofences require this permission --> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <!--End permissions for maps--> <!-- Required in order to play the notification tone to the user --> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <application android:name=".App" android:allowBackup="true" android:fullBackupContent="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme"> <meta-data android:name="io.fabric.ApiKey" android:value="${fabric_key}" /> <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" /> <!-- For Maps and Places API --> <meta-data android:name="com.google.android.geo.API_KEY" android:value="${google_api_key}" /> <provider android:name=".data.GeoTuneContentProvider" android:authorities="com.jawnnypoo.geotune" android:exported="false" /> <activity android:name="com.jawnnypoo.geotune.activity.MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".activity.GeoMapActivity" android:launchMode="singleTop" android:theme="@style/Transparent" android:windowSoftInputMode="stateHidden" /> <activity android:name=".activity.AboutActivity" /> <service android:name=".service.GeofenceTransitionsIntentService" android:exported="false" /> <service android:name=".service.GeoTuneModService" android:exported="false" /> <receiver android:name=".util.CheckRegistrationReceiver" android:enabled="true" android:exported="true"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" /> <action android:name="android.intent.action.ACTION_POWER_CONNECTED" /> </intent-filter> </receiver> </application> </manifest>
{ "content_hash": "41d7fc33350abd83b59bd390c56b2e4c", "timestamp": "", "source": "github", "line_count": 79, "max_line_length": 97, "avg_line_length": 37.037974683544306, "alnum_prop": 0.619958988380041, "repo_name": "Commit451/GeoTune", "id": "3e6d9195f524d524ef62fa33070def8918a6095a", "size": "2926", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "app/src/main/AndroidManifest.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "10527" }, { "name": "Kotlin", "bytes": "58670" } ], "symlink_target": "" }
class LibraryEntry < ActiveRecord::Base self.table_name = "watchlists" belongs_to :user belongs_to :anime has_many :genres, through: :anime has_many :stories, dependent: :destroy, foreign_key: :watchlist_id validates :user, :anime, :status, :episodes_watched, :rewatch_count, presence: true validates :user_id, uniqueness: {scope: :anime_id} VALID_STATUSES = ["Currently Watching", "Plan to Watch", "Completed", "On Hold", "Dropped"] validates :status, inclusion: {in: VALID_STATUSES} validate :rating_is_valid def rating_is_valid if self.rating and (self.rating <= 0 or self.rating > 5 or (self.rating * 2) % 1 != 0) errors.add(:rating, "is not in the valid range") end end validate :episodes_watched_less_than_total def episodes_watched_less_than_total if (self.anime.try(:episode_count) || 0) > 0 and (self.episodes_watched || 0) > self.anime.episode_count errors.add(:episodes_watched, "cannot exceed total number of episodes") end end before_validation do # Set field defaults. self.episodes_watched = 0 if self.episodes_watched.nil? self.rewatch_count = 0 if self.rewatch_count.nil? self.private = false if self.private.nil? end before_save do # Rewatching logic and life spent on anime. if self.rewatching and self.status_changed? and self.status == "Completed" self.rewatching = false self.rewatch_count += 1 end if self.rewatch_count_changed? self.user.update_life_spent_on_anime( (self.rewatch_count - self.rewatch_count_was) * ((self.anime.episode_count || 0) * (self.anime.episode_length || 0)) ) end if self.rewatching_changed? if self.rewatching self.user.update_life_spent_on_anime( (self.anime.episode_count || 0) * (self.anime.episode_length || 0) ) else self.user.update_life_spent_on_anime( - (self.anime.episode_count || 0) * (self.anime.episode_length || 0) ) end end # Track life spent on anime. if self.episodes_watched_changed? self.user.update_life_spent_on_anime( (self.episodes_watched - self.episodes_watched_was) * (self.anime.episode_length || 0) ) end # Set the `last_watched` field. if self.episodes_watched_changed? or self.status_changed? self.last_watched = Time.now end # Track aggregated rating frequencies for the show. # Need the hand-written SQL because there's no way to other way to atomically # increment/decrement hstore fields. if self.persisted? if self.rating_changed? okey = (self.rating_was || "nil").to_s nkey = (self.rating || "nil").to_s Anime.where(id: self.anime.id).update_all( "rating_frequencies = COALESCE(rating_frequencies, hstore(ARRAY[]::text[])) || hstore('#{okey}', ((COALESCE((rating_frequencies -> '#{okey}'), '0'))::integer - 1)::text) || hstore('#{nkey}', ((COALESCE((rating_frequencies -> '#{nkey}'), '0'))::integer + 1)::text)" ) end else # New record -- just need to do an increment. nkey = (self.rating || "nil").to_s Anime.where(id: self.anime.id).update_all( "rating_frequencies = COALESCE(rating_frequencies, hstore(ARRAY[]::text[])) || hstore('#{nkey}', ((COALESCE((rating_frequencies -> '#{nkey}'), '0'))::integer + 1)::text)" ) end end after_save do # Vote for the show to appear on the trending list. TrendingAnime.vote self.anime_id # Update the user's `last_library_update` time. self.user.update_column :last_library_update, Time.now # Queue a backup for the user DropboxBackupWorker.perform_debounced(self.user_id) if self.user.has_dropbox? end after_create do Anime.increment_counter 'user_count', self.anime_id end before_destroy do Anime.decrement_counter 'user_count', self.anime_id # Update the shows rating frequencies. Handwritten SQL for atomicity. nkey = (self.rating || "nil").to_s Anime.where(id: self.anime.id).update_all( "rating_frequencies = COALESCE(rating_frequencies, hstore(ARRAY[]::text[])) || hstore('#{nkey}', ((COALESCE((rating_frequencies -> '#{nkey}'), '0'))::integer - 1)::text)" ) # Update user's life spent on anime. self.user.update_life_spent_on_anime( - self.episodes_watched * (self.anime.episode_length || 0) ) # Update the user's `last_library_update` time. self.user.update_column :last_library_update, Time.now end ALLOWED_IN_IMPORT = [:episodes_watched, :rewatch_count, :rewatching, :notes, :status, :private, :rating, :last_watched] # Imports from any object which exposes the following interface: # * Mixes in the Enumerable module # * #each() yields a sym-keyed hash of fields to set, plus :media # * #media_type() returns a symbol of the media type of the import def self.list_import(user, list) raise 'Import type mismatch' unless list.media_type == :anime list.each do |row| entry = LibraryEntry.where(user: user, anime: row[:media]).first_or_initialize row[:episodes_watched] = [row[:episodes_watched], row[:media].try(:episode_count)].compact.min entry.assign_attributes row.slice(*ALLOWED_IN_IMPORT) entry.save! end end end
{ "content_hash": "fe438d837ce49c3fae058adeb56fc6f4", "timestamp": "", "source": "github", "line_count": 131, "max_line_length": 274, "avg_line_length": 40.0763358778626, "alnum_prop": 0.6607619047619048, "repo_name": "NuckChorris/hummingbird", "id": "ac0c01319a56f949231fbfb76977923b684ee118", "size": "5905", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "app/models/library_entry.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "944418" }, { "name": "HTML", "bytes": "673759" }, { "name": "Handlebars", "bytes": "167509" }, { "name": "JavaScript", "bytes": "1047457" }, { "name": "Ruby", "bytes": "714739" }, { "name": "Shell", "bytes": "1192" } ], "symlink_target": "" }
"""Backend handler for Message Recall. Services requests as a private, dynamic backend. """ # setup_path required to allow imports from lib folder. import setup_path # pylint: disable=unused-import,g-bad-import-order import backend_views import webapp2 app = webapp2.WSGIApplication([ (r'/_ah/start', backend_views.StartBackendHandler), (r'/backend/recall_messages', backend_views.Phase1RecallMessagesHandler), (r'/backend/retrieve_domain_users', backend_views.Phase2RetrieveDomainUsersHandler), (r'/backend/recall_user_messages', backend_views.Phase3RecallUserMessagesHandler), (r'/backend/wait_for_task_completion', backend_views.Phase4WaitForTaskCompletionHandler), ], debug=False)
{ "content_hash": "08393737e258c32c7e30ae85422d12c8", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 69, "avg_line_length": 30.833333333333332, "alnum_prop": 0.7432432432432432, "repo_name": "google/googleapps-message-recall", "id": "66de27c1b60e2abb4969de9d8ba8fb4aebe624df", "size": "1338", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "message_recall/backend_app.py", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "27490" }, { "name": "Python", "bytes": "834068" } ], "symlink_target": "" }
import java.io.IOException; import java.util.Properties; import java.io.*; public class Site { private int num; public void getdata(){ Properties props = new Properties(); try { String filePath = "E:\\client\\num.properties"; InputStream fis = new FileInputStream(filePath); props.load(fis); } catch (IOException e) { e.printStackTrace(); } setNum(Integer.valueOf(props.getProperty("num"))); } public void work() { System.out.println("Default work"); } public void show() { System.out.println("Default show"); } public int getNum() { return num; } public void setNum(int num) { this.num = num; } }
{ "content_hash": "d2b0a0b9766a0ee99481bd89daeca4dd", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 69, "avg_line_length": 19.457142857142856, "alnum_prop": 0.6328928046989721, "repo_name": "xjtu3c/GranuleJ", "id": "565ab810e38c35cecaa3661242c2c839ad516f2c", "size": "681", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "GOP/GranuleJIDE/example/TourGuide/src/Site.java", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "15961" }, { "name": "Java", "bytes": "6149848" }, { "name": "Lex", "bytes": "15717" }, { "name": "Shell", "bytes": "61" } ], "symlink_target": "" }
'use strict'; function Contact(options) { if (!options) { options = {}; } this.id = options.id; this.name = options.name; this.email = options.email; } module.exports = Contact;
{ "content_hash": "37fcf44b8b3d7cf411ed96ba7ee2746f", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 16.384615384615383, "alnum_prop": 0.5727699530516432, "repo_name": "Azure-Samples/app-service-api-node-contact-list", "id": "5c12e43fa8ce7f552e06ecc8264c9c9bf6c9ee18", "size": "213", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "end/ContactList/models/contact.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "4223" } ], "symlink_target": "" }
layout: single title: "Gegen Langenberg gelingt der zweite Saisonsieg" date: 2018-03-04 categories: - Mannschaftskampf excerpt: "04.03.2018 - Bei schönstem Frühlingswetter kehrten wir mit zwei Mannschaftspunkten im Gepäck von unserem Auswärtskampf in Langenberg nach Radevormwald zurück ..." --- Bei schönstem Frühlingswetter kehrten wir mit zwei Mannschaftspunkten im Gepäck von unserem Auswärtskampf in Langenberg nach Radevormwald zurück. Zu den gewonnenen Partien von Frank, Dieter und Peter kamen noch vier Punkteteilungen bei den Partien von Ingo, Thomas, Michael und Dietmar. Das erste Hälftchen kam an Brett 4 im frühen Mittelspiel zustande. Michael (mit den schwarzen Steinen) nahm hier das Remisangebot seines Gegners an. Dann folgte auch schon bald der Sieg von Peter, ebenfalls eine Schwarzpartie. Peter hatte das klassische Springer-Scheinopfer mit anschließender Bauerngabel gebracht, wobei der Gegner den Springer nicht nahm und so mit einem Bauern in Rückstand geriet. Nach der Eroberung eines weiteren Bauern und Damentausch konnte Peter die Partie ungefährdet zum Sieg führen. Dietmars Partie am Brett 7 verlief recht ruhig und auch hier einigten sich die Spieler auf ein Remis. An Brett 3 hatte sich Thomas in der Eröffnung in eine schwierige Lage gebracht. Innerhalb weniger Züge, bei denen die Damen und je zwei Leichtfiguren abgetauscht wurden, war die Gefahr aber auch schon gebannt. Der Verlust des Rochaderechts war dabei zu verschmerzen, denn in Anbetracht des nahenden Endspiels war die Position des Königs in der Mitte gar nicht so schlecht. Im 25. Zug wurde dann ein ausgeglichenes Turmendspiel erreicht und auch hier nach einigen weiteren Zügen ein Remis vereinbart. Dominik (Brett 8) spielte recht offensiv, bekam dann aber Schwierigkeiten mit der Deckung seiner Bauern. Nach Verlust eines Bauern ging es dann mehr und mehr bergab. Zwischenstand 2,5 : 2,5 Bei drei noch laufenden Partien erhielten wir hier ein Angebot zur Punkteteilung und zu einem 4:4 - Endstand, das wir aber ablehnten, da Frank an Brett 2 sehr aussichtsreich stand und Ingo an Brett 1 mindestens ein Remis hatte. Die Stellung bei Dieter (Brett 5) war allerdings nicht so klar. In der Folge drang der Gegner mit beiden Türmen auf Dieters Grundreihe ein und drohte, Dieters König in der Ecke mattzusetzen. Dieser trat die Flucht nach vorn an, nachdem ihm der einzig mögliche Weg freigekämpft wurde. Kurze Zeit später konnte Dieter auch noch ein Damenschach mit Turmgewinn anbringen, was den Gegner zur sofortigen Aufgabe veranlasste. Ingo hatte sich einen Mehrbauern erkämpft und probierte noch, im Endspiel mit Läufer und Spinger gegen Läufer und Springer entscheidende Fortschritte zu erzielen. Die gegnerische Stellung hielt aber und so kam es auch hier zur Punkteteilung. Bleibt noch die Partie von Frank an Brett 2: Frank setzte seine Figuren, besonders sein Läuferpaar sehr schön in Szene. Auch das spätere Endspiel Läufer gegen Springer war sehenswert. Hier zeigte Frank, wieviel stärker doch ein Läufer im Vergleich zu einem Springer beim Spiel auf beiden Flügeln ist. Der Gegner hatte zwar auch einen Freibauern gebildet, doch der Springer war gegen Franks Freibauern machtlos. So holten wir hier den dritten vollen Punkt in dieser Begegnung, die damit erfreulicherweise 5:3 zu unseren Gunsten ausging. Alle Termine, Ergebnisse und Tabellen der 2. Bezirksliga gibt es unter [Schachbezirk Bergisch-Land](http://www.sbbl.org/) und beim [SBNRW Ergebnisprotal](https://nrw.svw.info/ergebnisse/show/2017/2267/termin/) Text von Thomas
{ "content_hash": "59d19a1e9a87fd7addeb292c1dfaf2c1", "timestamp": "", "source": "github", "line_count": 75, "max_line_length": 78, "avg_line_length": 47.373333333333335, "alnum_prop": 0.817900365887982, "repo_name": "rsv1925/rsv1925.github.io", "id": "adb3846ea49e248db9c020242431398271ba6e97", "size": "3592", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_posts/2018-03-04-mk2018-r6.md", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "92899" }, { "name": "HTML", "bytes": "85205" }, { "name": "JavaScript", "bytes": "162771" }, { "name": "Ruby", "bytes": "3116" } ], "symlink_target": "" }
<?php namespace Brasa\TurnoBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Table(name="tur_factura_detalle") * @ORM\Entity(repositoryClass="Brasa\TurnoBundle\Repository\TurFacturaDetalleRepository") */ class TurFacturaDetalle { /** * @ORM\Id * @ORM\Column(name="codigo_factura_detalle_pk", type="integer") * @ORM\GeneratedValue(strategy="AUTO") */ private $codigoFacturaDetallePk; /** * @ORM\Column(name="codigo_factura_fk", type="integer") */ private $codigoFacturaFk; /** * @ORM\Column(name="codigo_concepto_servicio_fk", type="integer") */ private $codigoConceptoServicioFk; /** * @ORM\Column(name="codigo_puesto_fk", type="integer", nullable=true) */ private $codigoPuestoFk; /** * @ORM\Column(name="codigo_modalidad_servicio_fk", type="integer", nullable=true) */ private $codigoModalidadServicioFk; /** * @ORM\Column(name="codigo_grupo_facturacion_fk", type="integer", nullable=true) */ private $codigoGrupoFacturacionFk; /** * @ORM\Column(name="codigo_pedido_detalle_fk", type="integer", nullable=true) */ private $codigoPedidoDetalleFk; /** * @ORM\Column(name="codigo_pedido_detalle_concepto_fk", type="integer", nullable=true) */ private $codigoPedidoDetalleConceptoFk; /** * @ORM\Column(name="codigo_factura_detalle_fk", type="integer", nullable=true) */ private $codigoFacturaDetalleFk; /** * @ORM\Column(name="fecha_programacion", type="date", nullable=true) */ private $fechaProgramacion; /** * @ORM\Column(name="por_iva", type="integer") */ private $porIva = 0; /** * @ORM\Column(name="por_base_iva", type="integer") */ private $porBaseIva = 0; /** * @ORM\Column(name="base_iva", type="integer") */ private $baseIva = 0; /** * @ORM\Column(name="cantidad", type="float") */ private $cantidad = 0; /** * @ORM\Column(name="vr_precio", type="float") */ private $vrPrecio = 0; /** * @ORM\Column(name="subtotal", type="float") */ private $subtotal = 0; /** * @ORM\Column(name="subtotal_operado", type="float") */ private $subtotalOperado = 0; /** * @ORM\Column(name="iva", type="float") */ private $iva = 0; /** * @ORM\Column(name="total", type="float") */ private $total = 0; /** * @ORM\Column(name="detalle", type="string", length=300, nullable=true) */ private $detalle; /** * @ORM\Column(name="operacion", type="integer") */ private $operacion = 0; /** * @ORM\Column(name="tipo_pedido", type="string", length=50, nullable=true) */ private $tipo_pedido; /** * @ORM\ManyToOne(targetEntity="TurFactura", inversedBy="facturasDetallesFacturaRel") * @ORM\JoinColumn(name="codigo_factura_fk", referencedColumnName="codigo_factura_pk") */ protected $facturaRel; /** * @ORM\ManyToOne(targetEntity="TurConceptoServicio", inversedBy="facturasDetallesConceptoServicioRel") * @ORM\JoinColumn(name="codigo_concepto_servicio_fk", referencedColumnName="codigo_concepto_servicio_pk") */ protected $conceptoServicioRel; /** * @ORM\ManyToOne(targetEntity="TurPedidoDetalle", inversedBy="facturasDetallesPedidoDetalleRel") * @ORM\JoinColumn(name="codigo_pedido_detalle_fk", referencedColumnName="codigo_pedido_detalle_pk") */ protected $pedidoDetalleRel; /** * @ORM\ManyToOne(targetEntity="TurPedidoDetalleConcepto", inversedBy="facturasDetallesPedidoDetalleConceptoRel") * @ORM\JoinColumn(name="codigo_pedido_detalle_concepto_fk", referencedColumnName="codigo_pedido_detalle_concepto_pk") */ protected $pedidoDetalleConceptoRel; /** * @ORM\ManyToOne(targetEntity="TurFacturaDetalle", inversedBy="facturasDetallesFacturaDetalleRel") * @ORM\JoinColumn(name="codigo_factura_detalle_fk", referencedColumnName="codigo_factura_detalle_pk") */ protected $facturaDetalleRel; /** * @ORM\ManyToOne(targetEntity="TurPuesto", inversedBy="facturasDetallesPuestoRel") * @ORM\JoinColumn(name="codigo_puesto_fk", referencedColumnName="codigo_puesto_pk") */ protected $puestoRel; /** * @ORM\ManyToOne(targetEntity="TurModalidadServicio", inversedBy="facturasDetallesModalidadServicioRel") * @ORM\JoinColumn(name="codigo_modalidad_servicio_fk", referencedColumnName="codigo_modalidad_servicio_pk") */ protected $modalidadServicioRel; /** * @ORM\ManyToOne(targetEntity="TurGrupoFacturacion", inversedBy="facturasDetallesGrupoFacturacionRel") * @ORM\JoinColumn(name="codigo_grupo_facturacion_fk", referencedColumnName="codigo_grupo_facturacion_pk") */ protected $grupoFacturacionRel; /** * @ORM\OneToMany(targetEntity="TurFacturaDetalle", mappedBy="facturaDetalleRel") */ protected $facturasDetallesFacturaDetalleRel; /** * Constructor */ public function __construct() { $this->facturasDetallesFacturaDetalleRel = new \Doctrine\Common\Collections\ArrayCollection(); } /** * Get codigoFacturaDetallePk * * @return integer */ public function getCodigoFacturaDetallePk() { return $this->codigoFacturaDetallePk; } /** * Set codigoFacturaFk * * @param integer $codigoFacturaFk * * @return TurFacturaDetalle */ public function setCodigoFacturaFk($codigoFacturaFk) { $this->codigoFacturaFk = $codigoFacturaFk; return $this; } /** * Get codigoFacturaFk * * @return integer */ public function getCodigoFacturaFk() { return $this->codigoFacturaFk; } /** * Set codigoConceptoServicioFk * * @param integer $codigoConceptoServicioFk * * @return TurFacturaDetalle */ public function setCodigoConceptoServicioFk($codigoConceptoServicioFk) { $this->codigoConceptoServicioFk = $codigoConceptoServicioFk; return $this; } /** * Get codigoConceptoServicioFk * * @return integer */ public function getCodigoConceptoServicioFk() { return $this->codigoConceptoServicioFk; } /** * Set codigoPuestoFk * * @param integer $codigoPuestoFk * * @return TurFacturaDetalle */ public function setCodigoPuestoFk($codigoPuestoFk) { $this->codigoPuestoFk = $codigoPuestoFk; return $this; } /** * Get codigoPuestoFk * * @return integer */ public function getCodigoPuestoFk() { return $this->codigoPuestoFk; } /** * Set codigoModalidadServicioFk * * @param integer $codigoModalidadServicioFk * * @return TurFacturaDetalle */ public function setCodigoModalidadServicioFk($codigoModalidadServicioFk) { $this->codigoModalidadServicioFk = $codigoModalidadServicioFk; return $this; } /** * Get codigoModalidadServicioFk * * @return integer */ public function getCodigoModalidadServicioFk() { return $this->codigoModalidadServicioFk; } /** * Set codigoGrupoFacturacionFk * * @param integer $codigoGrupoFacturacionFk * * @return TurFacturaDetalle */ public function setCodigoGrupoFacturacionFk($codigoGrupoFacturacionFk) { $this->codigoGrupoFacturacionFk = $codigoGrupoFacturacionFk; return $this; } /** * Get codigoGrupoFacturacionFk * * @return integer */ public function getCodigoGrupoFacturacionFk() { return $this->codigoGrupoFacturacionFk; } /** * Set codigoPedidoDetalleFk * * @param integer $codigoPedidoDetalleFk * * @return TurFacturaDetalle */ public function setCodigoPedidoDetalleFk($codigoPedidoDetalleFk) { $this->codigoPedidoDetalleFk = $codigoPedidoDetalleFk; return $this; } /** * Get codigoPedidoDetalleFk * * @return integer */ public function getCodigoPedidoDetalleFk() { return $this->codigoPedidoDetalleFk; } /** * Set codigoPedidoDetalleConceptoFk * * @param integer $codigoPedidoDetalleConceptoFk * * @return TurFacturaDetalle */ public function setCodigoPedidoDetalleConceptoFk($codigoPedidoDetalleConceptoFk) { $this->codigoPedidoDetalleConceptoFk = $codigoPedidoDetalleConceptoFk; return $this; } /** * Get codigoPedidoDetalleConceptoFk * * @return integer */ public function getCodigoPedidoDetalleConceptoFk() { return $this->codigoPedidoDetalleConceptoFk; } /** * Set codigoFacturaDetalleFk * * @param integer $codigoFacturaDetalleFk * * @return TurFacturaDetalle */ public function setCodigoFacturaDetalleFk($codigoFacturaDetalleFk) { $this->codigoFacturaDetalleFk = $codigoFacturaDetalleFk; return $this; } /** * Get codigoFacturaDetalleFk * * @return integer */ public function getCodigoFacturaDetalleFk() { return $this->codigoFacturaDetalleFk; } /** * Set fechaProgramacion * * @param \DateTime $fechaProgramacion * * @return TurFacturaDetalle */ public function setFechaProgramacion($fechaProgramacion) { $this->fechaProgramacion = $fechaProgramacion; return $this; } /** * Get fechaProgramacion * * @return \DateTime */ public function getFechaProgramacion() { return $this->fechaProgramacion; } /** * Set porIva * * @param integer $porIva * * @return TurFacturaDetalle */ public function setPorIva($porIva) { $this->porIva = $porIva; return $this; } /** * Get porIva * * @return integer */ public function getPorIva() { return $this->porIva; } /** * Set porBaseIva * * @param integer $porBaseIva * * @return TurFacturaDetalle */ public function setPorBaseIva($porBaseIva) { $this->porBaseIva = $porBaseIva; return $this; } /** * Get porBaseIva * * @return integer */ public function getPorBaseIva() { return $this->porBaseIva; } /** * Set baseIva * * @param integer $baseIva * * @return TurFacturaDetalle */ public function setBaseIva($baseIva) { $this->baseIva = $baseIva; return $this; } /** * Get baseIva * * @return integer */ public function getBaseIva() { return $this->baseIva; } /** * Set cantidad * * @param float $cantidad * * @return TurFacturaDetalle */ public function setCantidad($cantidad) { $this->cantidad = $cantidad; return $this; } /** * Get cantidad * * @return float */ public function getCantidad() { return $this->cantidad; } /** * Set vrPrecio * * @param float $vrPrecio * * @return TurFacturaDetalle */ public function setVrPrecio($vrPrecio) { $this->vrPrecio = $vrPrecio; return $this; } /** * Get vrPrecio * * @return float */ public function getVrPrecio() { return $this->vrPrecio; } /** * Set subtotal * * @param float $subtotal * * @return TurFacturaDetalle */ public function setSubtotal($subtotal) { $this->subtotal = $subtotal; return $this; } /** * Get subtotal * * @return float */ public function getSubtotal() { return $this->subtotal; } /** * Set iva * * @param float $iva * * @return TurFacturaDetalle */ public function setIva($iva) { $this->iva = $iva; return $this; } /** * Get iva * * @return float */ public function getIva() { return $this->iva; } /** * Set total * * @param float $total * * @return TurFacturaDetalle */ public function setTotal($total) { $this->total = $total; return $this; } /** * Get total * * @return float */ public function getTotal() { return $this->total; } /** * Set detalle * * @param string $detalle * * @return TurFacturaDetalle */ public function setDetalle($detalle) { $this->detalle = $detalle; return $this; } /** * Get detalle * * @return string */ public function getDetalle() { return $this->detalle; } /** * Set facturaRel * * @param \Brasa\TurnoBundle\Entity\TurFactura $facturaRel * * @return TurFacturaDetalle */ public function setFacturaRel(\Brasa\TurnoBundle\Entity\TurFactura $facturaRel = null) { $this->facturaRel = $facturaRel; return $this; } /** * Get facturaRel * * @return \Brasa\TurnoBundle\Entity\TurFactura */ public function getFacturaRel() { return $this->facturaRel; } /** * Set conceptoServicioRel * * @param \Brasa\TurnoBundle\Entity\TurConceptoServicio $conceptoServicioRel * * @return TurFacturaDetalle */ public function setConceptoServicioRel(\Brasa\TurnoBundle\Entity\TurConceptoServicio $conceptoServicioRel = null) { $this->conceptoServicioRel = $conceptoServicioRel; return $this; } /** * Get conceptoServicioRel * * @return \Brasa\TurnoBundle\Entity\TurConceptoServicio */ public function getConceptoServicioRel() { return $this->conceptoServicioRel; } /** * Set pedidoDetalleRel * * @param \Brasa\TurnoBundle\Entity\TurPedidoDetalle $pedidoDetalleRel * * @return TurFacturaDetalle */ public function setPedidoDetalleRel(\Brasa\TurnoBundle\Entity\TurPedidoDetalle $pedidoDetalleRel = null) { $this->pedidoDetalleRel = $pedidoDetalleRel; return $this; } /** * Get pedidoDetalleRel * * @return \Brasa\TurnoBundle\Entity\TurPedidoDetalle */ public function getPedidoDetalleRel() { return $this->pedidoDetalleRel; } /** * Set pedidoDetalleConceptoRel * * @param \Brasa\TurnoBundle\Entity\TurPedidoDetalleConcepto $pedidoDetalleConceptoRel * * @return TurFacturaDetalle */ public function setPedidoDetalleConceptoRel(\Brasa\TurnoBundle\Entity\TurPedidoDetalleConcepto $pedidoDetalleConceptoRel = null) { $this->pedidoDetalleConceptoRel = $pedidoDetalleConceptoRel; return $this; } /** * Get pedidoDetalleConceptoRel * * @return \Brasa\TurnoBundle\Entity\TurPedidoDetalleConcepto */ public function getPedidoDetalleConceptoRel() { return $this->pedidoDetalleConceptoRel; } /** * Set facturaDetalleRel * * @param \Brasa\TurnoBundle\Entity\TurFacturaDetalle $facturaDetalleRel * * @return TurFacturaDetalle */ public function setFacturaDetalleRel(\Brasa\TurnoBundle\Entity\TurFacturaDetalle $facturaDetalleRel = null) { $this->facturaDetalleRel = $facturaDetalleRel; return $this; } /** * Get facturaDetalleRel * * @return \Brasa\TurnoBundle\Entity\TurFacturaDetalle */ public function getFacturaDetalleRel() { return $this->facturaDetalleRel; } /** * Set puestoRel * * @param \Brasa\TurnoBundle\Entity\TurPuesto $puestoRel * * @return TurFacturaDetalle */ public function setPuestoRel(\Brasa\TurnoBundle\Entity\TurPuesto $puestoRel = null) { $this->puestoRel = $puestoRel; return $this; } /** * Get puestoRel * * @return \Brasa\TurnoBundle\Entity\TurPuesto */ public function getPuestoRel() { return $this->puestoRel; } /** * Set modalidadServicioRel * * @param \Brasa\TurnoBundle\Entity\TurModalidadServicio $modalidadServicioRel * * @return TurFacturaDetalle */ public function setModalidadServicioRel(\Brasa\TurnoBundle\Entity\TurModalidadServicio $modalidadServicioRel = null) { $this->modalidadServicioRel = $modalidadServicioRel; return $this; } /** * Get modalidadServicioRel * * @return \Brasa\TurnoBundle\Entity\TurModalidadServicio */ public function getModalidadServicioRel() { return $this->modalidadServicioRel; } /** * Set grupoFacturacionRel * * @param \Brasa\TurnoBundle\Entity\TurGrupoFacturacion $grupoFacturacionRel * * @return TurFacturaDetalle */ public function setGrupoFacturacionRel(\Brasa\TurnoBundle\Entity\TurGrupoFacturacion $grupoFacturacionRel = null) { $this->grupoFacturacionRel = $grupoFacturacionRel; return $this; } /** * Get grupoFacturacionRel * * @return \Brasa\TurnoBundle\Entity\TurGrupoFacturacion */ public function getGrupoFacturacionRel() { return $this->grupoFacturacionRel; } /** * Add facturasDetallesFacturaDetalleRel * * @param \Brasa\TurnoBundle\Entity\TurFacturaDetalle $facturasDetallesFacturaDetalleRel * * @return TurFacturaDetalle */ public function addFacturasDetallesFacturaDetalleRel(\Brasa\TurnoBundle\Entity\TurFacturaDetalle $facturasDetallesFacturaDetalleRel) { $this->facturasDetallesFacturaDetalleRel[] = $facturasDetallesFacturaDetalleRel; return $this; } /** * Remove facturasDetallesFacturaDetalleRel * * @param \Brasa\TurnoBundle\Entity\TurFacturaDetalle $facturasDetallesFacturaDetalleRel */ public function removeFacturasDetallesFacturaDetalleRel(\Brasa\TurnoBundle\Entity\TurFacturaDetalle $facturasDetallesFacturaDetalleRel) { $this->facturasDetallesFacturaDetalleRel->removeElement($facturasDetallesFacturaDetalleRel); } /** * Get facturasDetallesFacturaDetalleRel * * @return \Doctrine\Common\Collections\Collection */ public function getFacturasDetallesFacturaDetalleRel() { return $this->facturasDetallesFacturaDetalleRel; } /** * Set tipoPedido * * @param string $tipoPedido * * @return TurFacturaDetalle */ public function setTipoPedido($tipoPedido) { $this->tipo_pedido = $tipoPedido; return $this; } /** * Get tipoPedido * * @return string */ public function getTipoPedido() { return $this->tipo_pedido; } /** * Set subtotalOperado * * @param float $subtotalOperado * * @return TurFacturaDetalle */ public function setSubtotalOperado($subtotalOperado) { $this->subtotalOperado = $subtotalOperado; return $this; } /** * Get subtotalOperado * * @return float */ public function getSubtotalOperado() { return $this->subtotalOperado; } /** * Set operacion * * @param integer $operacion * * @return TurFacturaDetalle */ public function setOperacion($operacion) { $this->operacion = $operacion; return $this; } /** * Get operacion * * @return integer */ public function getOperacion() { return $this->operacion; } }
{ "content_hash": "1bfce45772f90cad5b1ff1e56009bc1c", "timestamp": "", "source": "github", "line_count": 926, "max_line_length": 139, "avg_line_length": 22.02267818574514, "alnum_prop": 0.5973618398470063, "repo_name": "wariox3/brasa", "id": "3735a80878ebd1f031db2790b1d5b7f0e7dd6010", "size": "20393", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Brasa/TurnoBundle/Entity/TurFacturaDetalle.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "122817" }, { "name": "HTML", "bytes": "3724591" }, { "name": "JavaScript", "bytes": "382852" }, { "name": "PHP", "bytes": "12584043" }, { "name": "Shell", "bytes": "4440" }, { "name": "TSQL", "bytes": "1403931" } ], "symlink_target": "" }
/** * conduitjs - Give any method a pre/post invocation pipeline.... * Author: Jim Cowart (http://freshbrewedcode.com/jimcowart) * Version: v0.3.2 * Url: http://github.com/ifandelse/ConduitJS * License: MIT */ (function (root, factory) { if (typeof module === "object" && module.exports) { // Node, or CommonJS-Like environments module.exports = factory(); } else if (typeof define === "function" && define.amd) { // AMD. Register as an anonymous module. define(factory(root)); } else { // Browser globals root.Conduit = factory(root); } }(this, function (global, undefined) { function Conduit(options) { if (typeof options.target !== "function") { throw new Error("You can only make functions into Conduits."); } var _steps = { pre: options.pre || [], post: options.post || [], all: [] }; var _defaultContext = options.context; var _target = options.target; var _targetStep = { isTarget: true, fn: options.sync ? function () { var args = Array.prototype.slice.call(arguments, 0); var result = _target.apply(_defaultContext, args); return result; } : function (next) { var args = Array.prototype.slice.call(arguments, 1); args.splice(1, 1, _target.apply(_defaultContext, args)); next.apply(this, args); } }; var _genPipeline = function () { _steps.all = _steps.pre.concat([_targetStep].concat(_steps.post)); }; _genPipeline(); var conduit = function () { var idx = 0; var retval; var phase; var next = function next() { var args = Array.prototype.slice.call(arguments, 0); var thisIdx = idx; var step; var nextArgs; idx += 1; if (thisIdx < _steps.all.length) { step = _steps.all[thisIdx]; phase = (phase === "target") ? "after" : (step.isTarget) ? "target" : "before"; if (options.sync) { if (phase === "before") { nextArgs = step.fn.apply(step.context || _defaultContext, args); next.apply(this, nextArgs || args); } else { retval = step.fn.apply(step.context || _defaultContext, args) || retval; next.apply(this, [retval].concat(args)); } } else { step.fn.apply(step.context || _defaultContext, [next].concat(args)); } } }; next.apply(this, arguments); return retval; }; conduit.steps = function () { return _steps.all; }; conduit.context = function (ctx) { if (arguments.length === 0) { return _defaultContext; } else { _defaultContext = ctx; } }; conduit.before = function (step, options) { step = typeof step === "function" ? { fn: step } : step; options = options || {}; if (options.prepend) { _steps.pre.unshift(step); } else { _steps.pre.push(step); } _genPipeline(); }; conduit.after = function (step, options) { step = typeof step === "function" ? { fn: step } : step; options = options || {}; if (options.prepend) { _steps.post.unshift(step); } else { _steps.post.push(step); } _genPipeline(); }; conduit.clear = function () { _steps = { pre: [], post: [], all: [] }; _genPipeline(); }; conduit.target = function (fn) { if (fn) { _target = fn; } return _target; }; return conduit; }; return { Sync: function (options) { options.sync = true; return Conduit.call(this, options) }, Async: function (options) { return Conduit.call(this, options); } } }));
{ "content_hash": "6dabdcf633cd6f12aeaffd5ccc1d10b9", "timestamp": "", "source": "github", "line_count": 136, "max_line_length": 100, "avg_line_length": 34, "alnum_prop": 0.4413927335640138, "repo_name": "robymes/WebApplicationTesting", "id": "8689c978e3dc63841124d893ca9741502a6083f7", "size": "4624", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "libraries/conduit-0.3.2.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "8516" }, { "name": "JavaScript", "bytes": "310023" }, { "name": "Shell", "bytes": "758" } ], "symlink_target": "" }
package io.vertx.ext.web.sstore; import io.vertx.codegen.annotations.VertxGen; import io.vertx.core.Vertx; import io.vertx.core.json.JsonObject; import io.vertx.ext.web.sstore.impl.ClusteredSessionStoreImpl; /** * A session store which stores sessions in a distributed map so they are available across the cluster. * * @author <a href="http://tfox.org">Tim Fox</a> * @author <a href="mailto:plopes@redhat.com">Paulo Lopes</a> */ @VertxGen public interface ClusteredSessionStore extends SessionStore { /** * The default name used for the session map */ String DEFAULT_SESSION_MAP_NAME = "vertx-web.sessions"; /** * Default retry time out, in ms, for a session not found in this store. */ long DEFAULT_RETRY_TIMEOUT = 5 * 1000; // 5 seconds /** * Create a session store * * @param vertx the Vert.x instance * @param sessionMapName the session map name * @return the session store */ static ClusteredSessionStore create(Vertx vertx, String sessionMapName) { ClusteredSessionStoreImpl store = new ClusteredSessionStoreImpl(); store.init(vertx, new JsonObject() .put("retryTimeout", DEFAULT_RETRY_TIMEOUT) .put("mapName", sessionMapName)); return store; } /** * Create a session store.<p/> * * The retry timeout value, configures how long the session handler will retry to get a session from the store * when it is not found. * * @param vertx the Vert.x instance * @param sessionMapName the session map name * @param retryTimeout the store retry timeout, in ms * @return the session store */ static ClusteredSessionStore create(Vertx vertx, String sessionMapName, long retryTimeout) { ClusteredSessionStoreImpl store = new ClusteredSessionStoreImpl(); store.init(vertx, new JsonObject() .put("retryTimeout", retryTimeout) .put("mapName", sessionMapName)); return store; } /** * Create a session store * * @param vertx the Vert.x instance * @return the session store */ static ClusteredSessionStore create(Vertx vertx) { ClusteredSessionStoreImpl store = new ClusteredSessionStoreImpl(); store.init(vertx, new JsonObject() .put("retryTimeout", DEFAULT_RETRY_TIMEOUT) .put("mapName", DEFAULT_SESSION_MAP_NAME)); return store; } /** * Create a session store.<p/> * * The retry timeout value, configures how long the session handler will retry to get a session from the store * when it is not found. * * @param vertx the Vert.x instance * @param retryTimeout the store retry timeout, in ms * @return the session store */ static ClusteredSessionStore create(Vertx vertx, long retryTimeout) { ClusteredSessionStoreImpl store = new ClusteredSessionStoreImpl(); store.init(vertx, new JsonObject() .put("retryTimeout", retryTimeout) .put("mapName", DEFAULT_SESSION_MAP_NAME)); return store; } }
{ "content_hash": "f0e5b46727a84af357c6e22554023ed9", "timestamp": "", "source": "github", "line_count": 94, "max_line_length": 112, "avg_line_length": 31.19148936170213, "alnum_prop": 0.6971350613915416, "repo_name": "vert-x3/vertx-web", "id": "b73c6cb1b0cd40492fb45a02fb2217dd9702e4e7", "size": "3456", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "vertx-web/src/main/java/io/vertx/ext/web/sstore/ClusteredSessionStore.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "249" }, { "name": "CSS", "bytes": "202" }, { "name": "Fluent", "bytes": "27" }, { "name": "FreeMarker", "bytes": "557" }, { "name": "HTML", "bytes": "12387" }, { "name": "Handlebars", "bytes": "693" }, { "name": "Java", "bytes": "3950693" }, { "name": "JavaScript", "bytes": "11056" }, { "name": "Pug", "bytes": "341" }, { "name": "Python", "bytes": "985896" }, { "name": "Shell", "bytes": "1987" } ], "symlink_target": "" }
module Main(main,hello) where import qualified Hello import qualified Hello as H import Hello(exported) hello = Hello.hello main = Hello.hello
{ "content_hash": "810f34e5747d214ff5b9234b04e56b19", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 32, "avg_line_length": 17.333333333333332, "alnum_prop": 0.7371794871794872, "repo_name": "sgtest/haskell-module-import", "id": "cd252a2410119a11e6a45c06f953b10db2869cda", "size": "156", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Main.hs", "mode": "33188", "license": "mit", "language": [ { "name": "Haskell", "bytes": "453" } ], "symlink_target": "" }
void * memset(void * destination, int32_t character, uint64_t length); void * memcpy(void * destination, const void * source, uint64_t length); void * malloc(uint32_t size); void free(void * ptr); #endif
{ "content_hash": "21963d516e48aab0684b4c3860a6a64c", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 72, "avg_line_length": 34.166666666666664, "alnum_prop": 0.7170731707317073, "repo_name": "saques/fractalOS", "id": "9300ed09bfc7f319e032486b9ff2280fa7a16cec", "size": "255", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Kernel/include/lib.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "76175" }, { "name": "Batchfile", "bytes": "447" }, { "name": "C", "bytes": "280187" }, { "name": "C++", "bytes": "2144" }, { "name": "Makefile", "bytes": "4357" }, { "name": "Shell", "bytes": "84" } ], "symlink_target": "" }
<!DOCTYPE HTML> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (16) on Thu Nov 03 10:43:13 MDT 2022 --> <title>Uses of Class com.easypost.model.Rate (com.easypost:easypost-api-client 5.10.0 API)</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="dc.created" content="2022-11-03"> <meta name="description" content="use: package: com.easypost.model, class: Rate"> <meta name="generator" content="javadoc/ClassUseWriter"> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> <link rel="stylesheet" type="text/css" href="../../../../script-dir/jquery-ui.min.css" title="Style"> <link rel="stylesheet" type="text/css" href="../../../../jquery-ui.overrides.css" title="Style"> <script type="text/javascript" src="../../../../script.js"></script> <script type="text/javascript" src="../../../../script-dir/jquery-3.5.1.min.js"></script> <script type="text/javascript" src="../../../../script-dir/jquery-ui.min.js"></script> </head> <body class="class-use-page"> <script type="text/javascript">var pathtoroot = "../../../../"; loadScripts(document, 'script');</script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <div class="flex-box"> <header role="banner" class="flex-header"> <nav role="navigation"> <!-- ========= START OF TOP NAVBAR ======= --> <div class="top-nav" id="navbar.top"> <div class="skip-nav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <ul id="navbar.top.firstrow" class="nav-list" title="Navigation"> <li><a href="../../../../index.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../Rate.html" title="class in com.easypost.model">Class</a></li> <li class="nav-bar-cell1-rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="sub-nav"> <div class="nav-list-search"><label for="search">SEARCH:</label> <input type="text" id="search" value="search" disabled="disabled"> <input type="reset" id="reset" value="reset" disabled="disabled"> </div> </div> <!-- ========= END OF TOP NAVBAR ========= --> <span class="skip-nav" id="skip.navbar.top"> <!-- --> </span></nav> </header> <div class="flex-content"> <main role="main"> <div class="header"> <h1 title="Uses of Class com.easypost.model.Rate" class="title">Uses of Class<br>com.easypost.model.Rate</h1> </div> <div class="caption"><span>Packages that use <a href="../Rate.html" title="class in com.easypost.model">Rate</a></span></div> <div class="summary-table two-column-summary"> <div class="table-header col-first">Package</div> <div class="table-header col-last">Description</div> <div class="col-first even-row-color"><a href="#com.easypost.model">com.easypost.model</a></div> <div class="col-last even-row-color"> <div class="block">Classes for the EasyPost API.</div> </div> </div> <section class="class-uses"> <ul class="block-list"> <li> <section class="detail" id="com.easypost.model"> <h2>Uses of <a href="../Rate.html" title="class in com.easypost.model">Rate</a> in <a href="../package-summary.html">com.easypost.model</a></h2> <div class="caption"><span>Subclasses of <a href="../Rate.html" title="class in com.easypost.model">Rate</a> in <a href="../package-summary.html">com.easypost.model</a></span></div> <div class="summary-table three-column-summary"> <div class="table-header col-first">Modifier and Type</div> <div class="table-header col-second">Class</div> <div class="table-header col-last">Description</div> <div class="col-first even-row-color"><code>class&nbsp;</code></div> <div class="col-second even-row-color"><code><span class="member-name-link"><a href="../PickupRate.html" title="class in com.easypost.model">PickupRate</a></span></code></div> <div class="col-last even-row-color">&nbsp;</div> <div class="col-first odd-row-color"><code>class&nbsp;</code></div> <div class="col-second odd-row-color"><code><span class="member-name-link"><a href="../Smartrate.html" title="class in com.easypost.model">Smartrate</a></span></code></div> <div class="col-last odd-row-color">&nbsp;</div> </div> <div class="caption"><span>Methods in <a href="../package-summary.html">com.easypost.model</a> that return <a href="../Rate.html" title="class in com.easypost.model">Rate</a></span></div> <div class="summary-table three-column-summary"> <div class="table-header col-first">Modifier and Type</div> <div class="table-header col-second">Method</div> <div class="table-header col-last">Description</div> <div class="col-first even-row-color"><code>static <a href="../Rate.html" title="class in com.easypost.model">Rate</a></code></div> <div class="col-second even-row-color"><span class="type-name-label">Utilities.</span><code><span class="member-name-link"><a href="../Utilities.html#getLowestObjectRate(java.util.List,java.util.List,java.util.List)">getLowestObjectRate</a></span>&#8203;(<a href="https://docs.oracle.com/javase/8/docs/api/java/util/List.html" title="class or interface in java.util" class="external-link">List</a>&lt;<a href="../Rate.html" title="class in com.easypost.model">Rate</a>&gt;&nbsp;rates, <a href="https://docs.oracle.com/javase/8/docs/api/java/util/List.html" title="class or interface in java.util" class="external-link">List</a>&lt;<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html" title="class or interface in java.lang" class="external-link">String</a>&gt;&nbsp;carriers, <a href="https://docs.oracle.com/javase/8/docs/api/java/util/List.html" title="class or interface in java.util" class="external-link">List</a>&lt;<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html" title="class or interface in java.lang" class="external-link">String</a>&gt;&nbsp;services)</code></div> <div class="col-last even-row-color"> <div class="block">Get the lowest rate from a list of rates.</div> </div> <div class="col-first odd-row-color"><code><a href="../Rate.html" title="class in com.easypost.model">Rate</a></code></div> <div class="col-second odd-row-color"><span class="type-name-label">Shipment.</span><code><span class="member-name-link"><a href="../Shipment.html#getSelectedRate()">getSelectedRate</a></span>()</code></div> <div class="col-last odd-row-color"> <div class="block">Get the selected rate of this Shipment.</div> </div> <div class="col-first even-row-color"><code><a href="../Rate.html" title="class in com.easypost.model">Rate</a></code></div> <div class="col-second even-row-color"><span class="type-name-label">Order.</span><code><span class="member-name-link"><a href="../Order.html#lowestRate()">lowestRate</a></span>()</code></div> <div class="col-last even-row-color"> <div class="block">Get the lowest rate for this Order.</div> </div> <div class="col-first odd-row-color"><code><a href="../Rate.html" title="class in com.easypost.model">Rate</a></code></div> <div class="col-second odd-row-color"><span class="type-name-label">Order.</span><code><span class="member-name-link"><a href="../Order.html#lowestRate(java.util.List)">lowestRate</a></span>&#8203;(<a href="https://docs.oracle.com/javase/8/docs/api/java/util/List.html" title="class or interface in java.util" class="external-link">List</a>&lt;<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html" title="class or interface in java.lang" class="external-link">String</a>&gt;&nbsp;carriers)</code></div> <div class="col-last odd-row-color"> <div class="block">Get the lowest rate for this order.</div> </div> <div class="col-first even-row-color"><code><a href="../Rate.html" title="class in com.easypost.model">Rate</a></code></div> <div class="col-second even-row-color"><span class="type-name-label">Order.</span><code><span class="member-name-link"><a href="../Order.html#lowestRate(java.util.List,java.util.List)">lowestRate</a></span>&#8203;(<a href="https://docs.oracle.com/javase/8/docs/api/java/util/List.html" title="class or interface in java.util" class="external-link">List</a>&lt;<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html" title="class or interface in java.lang" class="external-link">String</a>&gt;&nbsp;carriers, <a href="https://docs.oracle.com/javase/8/docs/api/java/util/List.html" title="class or interface in java.util" class="external-link">List</a>&lt;<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html" title="class or interface in java.lang" class="external-link">String</a>&gt;&nbsp;services)</code></div> <div class="col-last even-row-color"> <div class="block">Get the lowest rate for this Order.</div> </div> <div class="col-first odd-row-color"><code><a href="../Rate.html" title="class in com.easypost.model">Rate</a></code></div> <div class="col-second odd-row-color"><span class="type-name-label">Shipment.</span><code><span class="member-name-link"><a href="../Shipment.html#lowestRate()">lowestRate</a></span>()</code></div> <div class="col-last odd-row-color"> <div class="block">Get the lowest rate for this Shipment.</div> </div> <div class="col-first even-row-color"><code><a href="../Rate.html" title="class in com.easypost.model">Rate</a></code></div> <div class="col-second even-row-color"><span class="type-name-label">Shipment.</span><code><span class="member-name-link"><a href="../Shipment.html#lowestRate(java.util.List)">lowestRate</a></span>&#8203;(<a href="https://docs.oracle.com/javase/8/docs/api/java/util/List.html" title="class or interface in java.util" class="external-link">List</a>&lt;<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html" title="class or interface in java.lang" class="external-link">String</a>&gt;&nbsp;carriers)</code></div> <div class="col-last even-row-color"> <div class="block">Get the lowest rate for this shipment.</div> </div> <div class="col-first odd-row-color"><code><a href="../Rate.html" title="class in com.easypost.model">Rate</a></code></div> <div class="col-second odd-row-color"><span class="type-name-label">Shipment.</span><code><span class="member-name-link"><a href="../Shipment.html#lowestRate(java.util.List,java.util.List)">lowestRate</a></span>&#8203;(<a href="https://docs.oracle.com/javase/8/docs/api/java/util/List.html" title="class or interface in java.util" class="external-link">List</a>&lt;<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html" title="class or interface in java.lang" class="external-link">String</a>&gt;&nbsp;carriers, <a href="https://docs.oracle.com/javase/8/docs/api/java/util/List.html" title="class or interface in java.util" class="external-link">List</a>&lt;<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html" title="class or interface in java.lang" class="external-link">String</a>&gt;&nbsp;services)</code></div> <div class="col-last odd-row-color"> <div class="block">Get the lowest rate for this Shipment.</div> </div> <div class="col-first even-row-color"><code>static <a href="../Rate.html" title="class in com.easypost.model">Rate</a></code></div> <div class="col-second even-row-color"><span class="type-name-label">Rate.</span><code><span class="member-name-link"><a href="../Rate.html#retrieve(java.lang.String)">retrieve</a></span>&#8203;(<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html" title="class or interface in java.lang" class="external-link">String</a>&nbsp;id)</code></div> <div class="col-last even-row-color"> <div class="block">Retrieve a Rate from the API.</div> </div> <div class="col-first odd-row-color"><code>static <a href="../Rate.html" title="class in com.easypost.model">Rate</a></code></div> <div class="col-second odd-row-color"><span class="type-name-label">Rate.</span><code><span class="member-name-link"><a href="../Rate.html#retrieve(java.lang.String,java.lang.String)">retrieve</a></span>&#8203;(<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html" title="class or interface in java.lang" class="external-link">String</a>&nbsp;id, <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html" title="class or interface in java.lang" class="external-link">String</a>&nbsp;apiKey)</code></div> <div class="col-last odd-row-color"> <div class="block">Retrieve a Rate from the API.</div> </div> </div> <div class="caption"><span>Methods in <a href="../package-summary.html">com.easypost.model</a> that return types with arguments of type <a href="../Rate.html" title="class in com.easypost.model">Rate</a></span></div> <div class="summary-table three-column-summary"> <div class="table-header col-first">Modifier and Type</div> <div class="table-header col-second">Method</div> <div class="table-header col-last">Description</div> <div class="col-first even-row-color"><code><a href="https://docs.oracle.com/javase/8/docs/api/java/util/List.html" title="class or interface in java.util" class="external-link">List</a>&lt;<a href="../Rate.html" title="class in com.easypost.model">Rate</a>&gt;</code></div> <div class="col-second even-row-color"><span class="type-name-label">Order.</span><code><span class="member-name-link"><a href="../Order.html#getRates()">getRates</a></span>()</code></div> <div class="col-last even-row-color"> <div class="block">Get the rates of the Order.</div> </div> <div class="col-first odd-row-color"><code><a href="https://docs.oracle.com/javase/8/docs/api/java/util/List.html" title="class or interface in java.util" class="external-link">List</a>&lt;<a href="../Rate.html" title="class in com.easypost.model">Rate</a>&gt;</code></div> <div class="col-second odd-row-color"><span class="type-name-label">Shipment.</span><code><span class="member-name-link"><a href="../Shipment.html#getRates()">getRates</a></span>()</code></div> <div class="col-last odd-row-color"> <div class="block">Get all rates of this Shipment.</div> </div> </div> <div class="caption"><span>Methods in <a href="../package-summary.html">com.easypost.model</a> with parameters of type <a href="../Rate.html" title="class in com.easypost.model">Rate</a></span></div> <div class="summary-table three-column-summary"> <div class="table-header col-first">Modifier and Type</div> <div class="table-header col-second">Method</div> <div class="table-header col-last">Description</div> <div class="col-first even-row-color"><code><a href="../Order.html" title="class in com.easypost.model">Order</a></code></div> <div class="col-second even-row-color"><span class="type-name-label">Order.</span><code><span class="member-name-link"><a href="../Order.html#buy(com.easypost.model.Rate)">buy</a></span>&#8203;(<a href="../Rate.html" title="class in com.easypost.model">Rate</a>&nbsp;rate)</code></div> <div class="col-last even-row-color"> <div class="block">Buy this Order.</div> </div> <div class="col-first odd-row-color"><code><a href="../Shipment.html" title="class in com.easypost.model">Shipment</a></code></div> <div class="col-second odd-row-color"><span class="type-name-label">Shipment.</span><code><span class="member-name-link"><a href="../Shipment.html#buy(com.easypost.model.Rate)">buy</a></span>&#8203;(<a href="../Rate.html" title="class in com.easypost.model">Rate</a>&nbsp;rate)</code></div> <div class="col-last odd-row-color"> <div class="block">Buy this Shipment.</div> </div> <div class="col-first even-row-color"><code><a href="../Shipment.html" title="class in com.easypost.model">Shipment</a></code></div> <div class="col-second even-row-color"><span class="type-name-label">Shipment.</span><code><span class="member-name-link"><a href="../Shipment.html#buy(com.easypost.model.Rate,boolean)">buy</a></span>&#8203;(<a href="../Rate.html" title="class in com.easypost.model">Rate</a>&nbsp;rate, boolean&nbsp;withCarbonOffset)</code></div> <div class="col-last even-row-color"> <div class="block">Buy this Shipment.</div> </div> <div class="col-first odd-row-color"><code><a href="../Shipment.html" title="class in com.easypost.model">Shipment</a></code></div> <div class="col-second odd-row-color"><span class="type-name-label">Shipment.</span><code><span class="member-name-link"><a href="../Shipment.html#buy(com.easypost.model.Rate,boolean,java.lang.String,java.lang.String)">buy</a></span>&#8203;(<a href="../Rate.html" title="class in com.easypost.model">Rate</a>&nbsp;rate, boolean&nbsp;withCarbonOffset, <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html" title="class or interface in java.lang" class="external-link">String</a>&nbsp;endShipperId, <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html" title="class or interface in java.lang" class="external-link">String</a>&nbsp;apiKey)</code></div> <div class="col-last odd-row-color"> <div class="block">Buy this Shipment.</div> </div> <div class="col-first even-row-color"><code><a href="../Shipment.html" title="class in com.easypost.model">Shipment</a></code></div> <div class="col-second even-row-color"><span class="type-name-label">Shipment.</span><code><span class="member-name-link"><a href="../Shipment.html#buy(com.easypost.model.Rate,java.lang.String)">buy</a></span>&#8203;(<a href="../Rate.html" title="class in com.easypost.model">Rate</a>&nbsp;rate, <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html" title="class or interface in java.lang" class="external-link">String</a>&nbsp;endShipperId)</code></div> <div class="col-last even-row-color"> <div class="block">Buy this Shipment.</div> </div> <div class="col-first odd-row-color"><code>void</code></div> <div class="col-second odd-row-color"><span class="type-name-label">Shipment.</span><code><span class="member-name-link"><a href="../Shipment.html#setSelectedRate(com.easypost.model.Rate)">setSelectedRate</a></span>&#8203;(<a href="../Rate.html" title="class in com.easypost.model">Rate</a>&nbsp;selectedRate)</code></div> <div class="col-last odd-row-color"> <div class="block">Set the selected rate of this Shipment.</div> </div> </div> <div class="caption"><span>Method parameters in <a href="../package-summary.html">com.easypost.model</a> with type arguments of type <a href="../Rate.html" title="class in com.easypost.model">Rate</a></span></div> <div class="summary-table three-column-summary"> <div class="table-header col-first">Modifier and Type</div> <div class="table-header col-second">Method</div> <div class="table-header col-last">Description</div> <div class="col-first even-row-color"><code>static <a href="../Rate.html" title="class in com.easypost.model">Rate</a></code></div> <div class="col-second even-row-color"><span class="type-name-label">Utilities.</span><code><span class="member-name-link"><a href="../Utilities.html#getLowestObjectRate(java.util.List,java.util.List,java.util.List)">getLowestObjectRate</a></span>&#8203;(<a href="https://docs.oracle.com/javase/8/docs/api/java/util/List.html" title="class or interface in java.util" class="external-link">List</a>&lt;<a href="../Rate.html" title="class in com.easypost.model">Rate</a>&gt;&nbsp;rates, <a href="https://docs.oracle.com/javase/8/docs/api/java/util/List.html" title="class or interface in java.util" class="external-link">List</a>&lt;<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html" title="class or interface in java.lang" class="external-link">String</a>&gt;&nbsp;carriers, <a href="https://docs.oracle.com/javase/8/docs/api/java/util/List.html" title="class or interface in java.util" class="external-link">List</a>&lt;<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html" title="class or interface in java.lang" class="external-link">String</a>&gt;&nbsp;services)</code></div> <div class="col-last even-row-color"> <div class="block">Get the lowest rate from a list of rates.</div> </div> <div class="col-first odd-row-color"><code>void</code></div> <div class="col-second odd-row-color"><span class="type-name-label">Order.</span><code><span class="member-name-link"><a href="../Order.html#setRates(java.util.List)">setRates</a></span>&#8203;(<a href="https://docs.oracle.com/javase/8/docs/api/java/util/List.html" title="class or interface in java.util" class="external-link">List</a>&lt;<a href="../Rate.html" title="class in com.easypost.model">Rate</a>&gt;&nbsp;rates)</code></div> <div class="col-last odd-row-color"> <div class="block">Set the rates of the Order.</div> </div> <div class="col-first even-row-color"><code>void</code></div> <div class="col-second even-row-color"><span class="type-name-label">Shipment.</span><code><span class="member-name-link"><a href="../Shipment.html#setRates(java.util.List)">setRates</a></span>&#8203;(<a href="https://docs.oracle.com/javase/8/docs/api/java/util/List.html" title="class or interface in java.util" class="external-link">List</a>&lt;<a href="../Rate.html" title="class in com.easypost.model">Rate</a>&gt;&nbsp;rates)</code></div> <div class="col-last even-row-color"> <div class="block">Set all rates of this Shipment.</div> </div> </div> </section> </li> </ul> </section> </main> <footer role="contentinfo"> <hr> <p class="legal-copy"><small>Copyright &#169; 2022 <a href="https://easypost.com">EasyPost</a>. All rights reserved.</small></p> </footer> </div> </div> </body> </html>
{ "content_hash": "af240f6eadef2cc26568dd2dac3443ec", "timestamp": "", "source": "github", "line_count": 237, "max_line_length": 530, "avg_line_length": 90.30801687763713, "alnum_prop": 0.7044339578563753, "repo_name": "EasyPost/easypost-java", "id": "a3d69fc3ab53565b7988cdfd72a86787ec40b326", "size": "21403", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/com/easypost/model/class-use/Rate.html", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "338893" }, { "name": "Makefile", "bytes": "2374" } ], "symlink_target": "" }
module Twingly module LiveFeed # A blog post # # @attr_reader [String] id the post ID (Twingly internal identification) # @attr_reader [String] author the author of the blog post # @attr_reader [String] url the post URL # @attr_reader [String] title the post title # @attr_reader [String] text the blog post text # @attr_reader [String] language_code ISO two letter language code for the # language that the post was written in # @attr_reader [String] location_code ISO two letter country code for the # location of the blog # @attr_reader [Hash] coordinates a hash containing :latitude and :longitude # from the post RSS # @attr_reader [Array] links all links from the blog post to other resources # @attr_reader [Array] tags the post tags/categories # @attr_reader [Array] images image URLs from the post (currently not populated) # @attr_reader [Time] indexed_at the time, in UTC, when the post was indexed by Twingly # @attr_reader [Time] published_at the time, in UTC, when the post was published # @attr_reader [Time] reindexed_at timestamp when the post last was changed in our database/index # @attr_reader [String] inlinks_count number of links to this post that was found in other blog posts # @attr_reader [String] blog_id the blog ID (Twingly internal identification) # @attr_reader [String] blog_name the name of the blog # @attr_reader [String] blog_url the blog URL # @attr_reader [Integer] blog_rank the rank of the blog, based on authority and language. # See https://developer.twingly.com/resources/ranking/#blogrank # @attr_reader [Integer] authority the blog's authority/influence. # See https://developer.twingly.com/resources/ranking/#authority class Post attr_reader :id, :author, :url, :title, :text, :location_code, :language_code, :coordinates, :links, :tags, :images, :indexed_at, :published_at, :reindexed_at, :inlinks_count, :blog_id, :blog_name, :blog_url, :blog_rank, :authority EMPTY_ARRAY = [].freeze EMPTY_HASH = {}.freeze # Sets all instance variables for the {Post}, given a Hash. # # @param [Hash] params containing blog post data. def set_values(params) @id = params.fetch('id') @author = params.fetch('author') @url = params.fetch('url') @title = params.fetch('title') @text = params.fetch('text') @language_code = params.fetch('languageCode') @location_code = params.fetch('locationCode') @coordinates = params.fetch('coordinates') { EMPTY_HASH } @links = params.fetch('links') { EMPTY_ARRAY } @tags = params.fetch('tags') { EMPTY_ARRAY } @images = params.fetch('images') { EMPTY_ARRAY } @indexed_at = Time.parse(params.fetch('indexedAt')) @published_at = Time.parse(params.fetch('publishedAt')) @reindexed_at = Time.parse(params.fetch('reindexedAt')) @inlinks_count = params.fetch('inlinksCount').to_i @blog_id = params.fetch('blogId') @blog_name = params.fetch('blogName') @blog_url = params.fetch('blogUrl') @blog_rank = params.fetch('blogRank').to_i @authority = params.fetch('authority').to_i end # @return [Hash] a hash containing all post attributes. def to_h { id: @id, author: @author, url: @url, title: @title, text: @text, language_code: @language_code, location_code: @location_code, coordinates: @coordinates, links: @links, tags: @tags, images: @images, indexed_at: @indexed_at, published_at: @published_at, reindexed_at: @reindexed_at, inlinks_count: @inlinks_count, blog_id: @blog_id, blog_name: @blog_name, blog_url: @blog_url, blog_rank: @blog_rank, authority: @authority, } end end end end
{ "content_hash": "a66b59d8584f873cd80949e324f15627", "timestamp": "", "source": "github", "line_count": 93, "max_line_length": 105, "avg_line_length": 44.61290322580645, "alnum_prop": 0.6097854904796336, "repo_name": "twingly/twingly-search-api-ruby", "id": "518f16a978a14d501fc97b262eb711d583f76d6d", "size": "4198", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "lib/twingly/livefeed/post.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "75490" } ], "symlink_target": "" }
#include <linux/string.h> #include <linux/parser.h> #include <linux/timer.h> #include <linux/blkdev.h> #include <linux/slab.h> #include <linux/spinlock.h> #include <linux/module.h> #include <linux/falloc.h> #include <scsi/scsi.h> #include <scsi/scsi_host.h> #include <asm/unaligned.h> #include <target/target_core_base.h> #include <target/target_core_backend.h> #include "target_core_file.h" static inline struct fd_dev *FD_DEV(struct se_device *dev) { return container_of(dev, struct fd_dev, dev); } /* fd_attach_hba(): (Part of se_subsystem_api_t template) * * */ static int fd_attach_hba(struct se_hba *hba, u32 host_id) { struct fd_host *fd_host; fd_host = kzalloc(sizeof(struct fd_host), GFP_KERNEL); if (!fd_host) { pr_err("Unable to allocate memory for struct fd_host\n"); return -ENOMEM; } fd_host->fd_host_id = host_id; hba->hba_ptr = fd_host; pr_debug("CORE_HBA[%d] - TCM FILEIO HBA Driver %s on Generic" " Target Core Stack %s\n", hba->hba_id, FD_VERSION, TARGET_CORE_MOD_VERSION); pr_debug("CORE_HBA[%d] - Attached FILEIO HBA: %u to Generic\n", hba->hba_id, fd_host->fd_host_id); return 0; } static void fd_detach_hba(struct se_hba *hba) { struct fd_host *fd_host = hba->hba_ptr; pr_debug("CORE_HBA[%d] - Detached FILEIO HBA: %u from Generic" " Target Core\n", hba->hba_id, fd_host->fd_host_id); kfree(fd_host); hba->hba_ptr = NULL; } static struct se_device *fd_alloc_device(struct se_hba *hba, const char *name) { struct fd_dev *fd_dev; struct fd_host *fd_host = hba->hba_ptr; fd_dev = kzalloc(sizeof(struct fd_dev), GFP_KERNEL); if (!fd_dev) { pr_err("Unable to allocate memory for struct fd_dev\n"); return NULL; } fd_dev->fd_host = fd_host; pr_debug("FILEIO: Allocated fd_dev for %p\n", name); return &fd_dev->dev; } static int fd_configure_device(struct se_device *dev) { struct fd_dev *fd_dev = FD_DEV(dev); struct fd_host *fd_host = dev->se_hba->hba_ptr; struct file *file; struct inode *inode = NULL; int flags, ret = -EINVAL; if (!(fd_dev->fbd_flags & FBDF_HAS_PATH)) { pr_err("Missing fd_dev_name=\n"); return -EINVAL; } /* * Use O_DSYNC by default instead of O_SYNC to forgo syncing * of pure timestamp updates. */ flags = O_RDWR | O_CREAT | O_LARGEFILE | O_DSYNC; /* * Optionally allow fd_buffered_io=1 to be enabled for people * who want use the fs buffer cache as an WriteCache mechanism. * * This means that in event of a hard failure, there is a risk * of silent data-loss if the SCSI client has *not* performed a * forced unit access (FUA) write, or issued SYNCHRONIZE_CACHE * to write-out the entire device cache. */ if (fd_dev->fbd_flags & FDBD_HAS_BUFFERED_IO_WCE) { pr_debug("FILEIO: Disabling O_DSYNC, using buffered FILEIO\n"); flags &= ~O_DSYNC; } file = filp_open(fd_dev->fd_dev_name, flags, 0600); if (IS_ERR(file)) { pr_err("filp_open(%s) failed\n", fd_dev->fd_dev_name); ret = PTR_ERR(file); goto fail; } fd_dev->fd_file = file; /* * If using a block backend with this struct file, we extract * fd_dev->fd_[block,dev]_size from struct block_device. * * Otherwise, we use the passed fd_size= from configfs */ inode = file->f_mapping->host; if (S_ISBLK(inode->i_mode)) { struct request_queue *q = bdev_get_queue(inode->i_bdev); unsigned long long dev_size; fd_dev->fd_block_size = bdev_logical_block_size(inode->i_bdev); /* * Determine the number of bytes from i_size_read() minus * one (1) logical sector from underlying struct block_device */ dev_size = (i_size_read(file->f_mapping->host) - fd_dev->fd_block_size); pr_debug("FILEIO: Using size: %llu bytes from struct" " block_device blocks: %llu logical_block_size: %d\n", dev_size, div_u64(dev_size, fd_dev->fd_block_size), fd_dev->fd_block_size); /* * Check if the underlying struct block_device request_queue supports * the QUEUE_FLAG_DISCARD bit for UNMAP/WRITE_SAME in SCSI + TRIM * in ATA and we need to set TPE=1 */ if (blk_queue_discard(q)) { dev->dev_attrib.max_unmap_lba_count = q->limits.max_discard_sectors; /* * Currently hardcoded to 1 in Linux/SCSI code.. */ dev->dev_attrib.max_unmap_block_desc_count = 1; dev->dev_attrib.unmap_granularity = q->limits.discard_granularity >> 9; dev->dev_attrib.unmap_granularity_alignment = q->limits.discard_alignment; pr_debug("IFILE: BLOCK Discard support available," " disabled by default\n"); } /* * Enable write same emulation for IBLOCK and use 0xFFFF as * the smaller WRITE_SAME(10) only has a two-byte block count. */ dev->dev_attrib.max_write_same_len = 0xFFFF; if (blk_queue_nonrot(q)) dev->dev_attrib.is_nonrot = 1; } else { if (!(fd_dev->fbd_flags & FBDF_HAS_SIZE)) { pr_err("FILEIO: Missing fd_dev_size=" " parameter, and no backing struct" " block_device\n"); goto fail; } fd_dev->fd_block_size = FD_BLOCKSIZE; /* * Limit UNMAP emulation to 8k Number of LBAs (NoLB) */ dev->dev_attrib.max_unmap_lba_count = 0x2000; /* * Currently hardcoded to 1 in Linux/SCSI code.. */ dev->dev_attrib.max_unmap_block_desc_count = 1; dev->dev_attrib.unmap_granularity = 1; dev->dev_attrib.unmap_granularity_alignment = 0; /* * Limit WRITE_SAME w/ UNMAP=0 emulation to 8k Number of LBAs (NoLB) * based upon struct iovec limit for vfs_writev() */ dev->dev_attrib.max_write_same_len = 0x1000; } dev->dev_attrib.hw_block_size = fd_dev->fd_block_size; dev->dev_attrib.max_bytes_per_io = FD_MAX_BYTES; dev->dev_attrib.hw_max_sectors = FD_MAX_BYTES / fd_dev->fd_block_size; dev->dev_attrib.hw_queue_depth = FD_MAX_DEVICE_QUEUE_DEPTH; if (fd_dev->fbd_flags & FDBD_HAS_BUFFERED_IO_WCE) { pr_debug("FILEIO: Forcing setting of emulate_write_cache=1" " with FDBD_HAS_BUFFERED_IO_WCE\n"); dev->dev_attrib.emulate_write_cache = 1; } fd_dev->fd_dev_id = fd_host->fd_host_dev_id_count++; fd_dev->fd_queue_depth = dev->queue_depth; pr_debug("CORE_FILE[%u] - Added TCM FILEIO Device ID: %u at %s," " %llu total bytes\n", fd_host->fd_host_id, fd_dev->fd_dev_id, fd_dev->fd_dev_name, fd_dev->fd_dev_size); return 0; fail: if (fd_dev->fd_file) { filp_close(fd_dev->fd_file, NULL); fd_dev->fd_file = NULL; } return ret; } static void fd_free_device(struct se_device *dev) { struct fd_dev *fd_dev = FD_DEV(dev); if (fd_dev->fd_file) { filp_close(fd_dev->fd_file, NULL); fd_dev->fd_file = NULL; } kfree(fd_dev); } static int fd_do_prot_rw(struct se_cmd *cmd, struct fd_prot *fd_prot, int is_write) { struct se_device *se_dev = cmd->se_dev; struct fd_dev *dev = FD_DEV(se_dev); struct file *prot_fd = dev->fd_prot_file; struct scatterlist *sg; loff_t pos = (cmd->t_task_lba * se_dev->prot_length); unsigned char *buf; u32 prot_size, len, size; int rc, ret = 1, i; prot_size = (cmd->data_length / se_dev->dev_attrib.block_size) * se_dev->prot_length; if (!is_write) { fd_prot->prot_buf = vzalloc(prot_size); if (!fd_prot->prot_buf) { pr_err("Unable to allocate fd_prot->prot_buf\n"); return -ENOMEM; } buf = fd_prot->prot_buf; fd_prot->prot_sg_nents = cmd->t_prot_nents; fd_prot->prot_sg = kzalloc(sizeof(struct scatterlist) * fd_prot->prot_sg_nents, GFP_KERNEL); if (!fd_prot->prot_sg) { pr_err("Unable to allocate fd_prot->prot_sg\n"); vfree(fd_prot->prot_buf); return -ENOMEM; } size = prot_size; for_each_sg(fd_prot->prot_sg, sg, fd_prot->prot_sg_nents, i) { len = min_t(u32, PAGE_SIZE, size); sg_set_buf(sg, buf, len); size -= len; buf += len; } } if (is_write) { rc = kernel_write(prot_fd, fd_prot->prot_buf, prot_size, pos); if (rc < 0 || prot_size != rc) { pr_err("kernel_write() for fd_do_prot_rw failed:" " %d\n", rc); ret = -EINVAL; } } else { rc = kernel_read(prot_fd, pos, fd_prot->prot_buf, prot_size); if (rc < 0) { pr_err("kernel_read() for fd_do_prot_rw failed:" " %d\n", rc); ret = -EINVAL; } } if (is_write || ret < 0) { kfree(fd_prot->prot_sg); vfree(fd_prot->prot_buf); } return ret; } static int fd_do_rw(struct se_cmd *cmd, struct scatterlist *sgl, u32 sgl_nents, int is_write) { struct se_device *se_dev = cmd->se_dev; struct fd_dev *dev = FD_DEV(se_dev); struct file *fd = dev->fd_file; struct scatterlist *sg; struct iovec *iov; mm_segment_t old_fs; loff_t pos = (cmd->t_task_lba * se_dev->dev_attrib.block_size); int ret = 0, i; iov = kzalloc(sizeof(struct iovec) * sgl_nents, GFP_KERNEL); if (!iov) { pr_err("Unable to allocate fd_do_readv iov[]\n"); return -ENOMEM; } for_each_sg(sgl, sg, sgl_nents, i) { iov[i].iov_len = sg->length; iov[i].iov_base = kmap(sg_page(sg)) + sg->offset; } old_fs = get_fs(); set_fs(get_ds()); if (is_write) ret = vfs_writev(fd, &iov[0], sgl_nents, &pos); else ret = vfs_readv(fd, &iov[0], sgl_nents, &pos); set_fs(old_fs); for_each_sg(sgl, sg, sgl_nents, i) kunmap(sg_page(sg)); kfree(iov); if (is_write) { if (ret < 0 || ret != cmd->data_length) { pr_err("%s() write returned %d\n", __func__, ret); return (ret < 0 ? ret : -EINVAL); } } else { /* * Return zeros and GOOD status even if the READ did not return * the expected virt_size for struct file w/o a backing struct * block_device. */ if (S_ISBLK(file_inode(fd)->i_mode)) { if (ret < 0 || ret != cmd->data_length) { pr_err("%s() returned %d, expecting %u for " "S_ISBLK\n", __func__, ret, cmd->data_length); return (ret < 0 ? ret : -EINVAL); } } else { if (ret < 0) { pr_err("%s() returned %d for non S_ISBLK\n", __func__, ret); return ret; } } } return 1; } static sense_reason_t fd_execute_sync_cache(struct se_cmd *cmd) { struct se_device *dev = cmd->se_dev; struct fd_dev *fd_dev = FD_DEV(dev); int immed = (cmd->t_task_cdb[1] & 0x2); loff_t start, end; int ret; /* * If the Immediate bit is set, queue up the GOOD response * for this SYNCHRONIZE_CACHE op */ if (immed) target_complete_cmd(cmd, SAM_STAT_GOOD); /* * Determine if we will be flushing the entire device. */ if (cmd->t_task_lba == 0 && cmd->data_length == 0) { start = 0; end = LLONG_MAX; } else { start = cmd->t_task_lba * dev->dev_attrib.block_size; if (cmd->data_length) end = start + cmd->data_length; else end = LLONG_MAX; } ret = vfs_fsync_range(fd_dev->fd_file, start, end, 1); if (ret != 0) pr_err("FILEIO: vfs_fsync_range() failed: %d\n", ret); if (immed) return 0; if (ret) target_complete_cmd(cmd, SAM_STAT_CHECK_CONDITION); else target_complete_cmd(cmd, SAM_STAT_GOOD); return 0; } static unsigned char * fd_setup_write_same_buf(struct se_cmd *cmd, struct scatterlist *sg, unsigned int len) { struct se_device *se_dev = cmd->se_dev; unsigned int block_size = se_dev->dev_attrib.block_size; unsigned int i = 0, end; unsigned char *buf, *p, *kmap_buf; buf = kzalloc(min_t(unsigned int, len, PAGE_SIZE), GFP_KERNEL); if (!buf) { pr_err("Unable to allocate fd_execute_write_same buf\n"); return NULL; } kmap_buf = kmap(sg_page(sg)) + sg->offset; if (!kmap_buf) { pr_err("kmap() failed in fd_setup_write_same\n"); kfree(buf); return NULL; } /* * Fill local *buf to contain multiple WRITE_SAME blocks up to * min(len, PAGE_SIZE) */ p = buf; end = min_t(unsigned int, len, PAGE_SIZE); while (i < end) { memcpy(p, kmap_buf, block_size); i += block_size; p += block_size; } kunmap(sg_page(sg)); return buf; } static sense_reason_t fd_execute_write_same(struct se_cmd *cmd) { struct se_device *se_dev = cmd->se_dev; struct fd_dev *fd_dev = FD_DEV(se_dev); struct file *f = fd_dev->fd_file; struct scatterlist *sg; struct iovec *iov; mm_segment_t old_fs; sector_t nolb = sbc_get_write_same_sectors(cmd); loff_t pos = cmd->t_task_lba * se_dev->dev_attrib.block_size; unsigned int len, len_tmp, iov_num; int i, rc; unsigned char *buf; if (!nolb) { target_complete_cmd(cmd, SAM_STAT_GOOD); return 0; } sg = &cmd->t_data_sg[0]; if (cmd->t_data_nents > 1 || sg->length != cmd->se_dev->dev_attrib.block_size) { pr_err("WRITE_SAME: Illegal SGL t_data_nents: %u length: %u" " block_size: %u\n", cmd->t_data_nents, sg->length, cmd->se_dev->dev_attrib.block_size); return TCM_INVALID_CDB_FIELD; } len = len_tmp = nolb * se_dev->dev_attrib.block_size; iov_num = DIV_ROUND_UP(len, PAGE_SIZE); buf = fd_setup_write_same_buf(cmd, sg, len); if (!buf) return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE; iov = vzalloc(sizeof(struct iovec) * iov_num); if (!iov) { pr_err("Unable to allocate fd_execute_write_same iovecs\n"); kfree(buf); return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE; } /* * Map the single fabric received scatterlist block now populated * in *buf into each iovec for I/O submission. */ for (i = 0; i < iov_num; i++) { iov[i].iov_base = buf; iov[i].iov_len = min_t(unsigned int, len_tmp, PAGE_SIZE); len_tmp -= iov[i].iov_len; } old_fs = get_fs(); set_fs(get_ds()); rc = vfs_writev(f, &iov[0], iov_num, &pos); set_fs(old_fs); vfree(iov); kfree(buf); if (rc < 0 || rc != len) { pr_err("vfs_writev() returned %d for write same\n", rc); return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE; } target_complete_cmd(cmd, SAM_STAT_GOOD); return 0; } static sense_reason_t fd_do_unmap(struct se_cmd *cmd, void *priv, sector_t lba, sector_t nolb) { struct file *file = priv; struct inode *inode = file->f_mapping->host; int ret; if (S_ISBLK(inode->i_mode)) { /* The backend is block device, use discard */ struct block_device *bdev = inode->i_bdev; ret = blkdev_issue_discard(bdev, lba, nolb, GFP_KERNEL, 0); if (ret < 0) { pr_warn("FILEIO: blkdev_issue_discard() failed: %d\n", ret); return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE; } } else { /* The backend is normal file, use fallocate */ struct se_device *se_dev = cmd->se_dev; loff_t pos = lba * se_dev->dev_attrib.block_size; unsigned int len = nolb * se_dev->dev_attrib.block_size; int mode = FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE; if (!file->f_op->fallocate) return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE; ret = file->f_op->fallocate(file, mode, pos, len); if (ret < 0) { pr_warn("FILEIO: fallocate() failed: %d\n", ret); return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE; } } return 0; } static sense_reason_t fd_execute_write_same_unmap(struct se_cmd *cmd) { struct se_device *se_dev = cmd->se_dev; struct fd_dev *fd_dev = FD_DEV(se_dev); struct file *file = fd_dev->fd_file; sector_t lba = cmd->t_task_lba; sector_t nolb = sbc_get_write_same_sectors(cmd); int ret; if (!nolb) { target_complete_cmd(cmd, SAM_STAT_GOOD); return 0; } ret = fd_do_unmap(cmd, file, lba, nolb); if (ret) return ret; target_complete_cmd(cmd, GOOD); return 0; } static sense_reason_t fd_execute_unmap(struct se_cmd *cmd) { struct file *file = FD_DEV(cmd->se_dev)->fd_file; return sbc_execute_unmap(cmd, fd_do_unmap, file); } static sense_reason_t fd_execute_rw(struct se_cmd *cmd, struct scatterlist *sgl, u32 sgl_nents, enum dma_data_direction data_direction) { struct se_device *dev = cmd->se_dev; struct fd_prot fd_prot; sense_reason_t rc; int ret = 0; /* * Call vectorized fileio functions to map struct scatterlist * physical memory addresses to struct iovec virtual memory. */ if (data_direction == DMA_FROM_DEVICE) { memset(&fd_prot, 0, sizeof(struct fd_prot)); if (cmd->prot_type) { ret = fd_do_prot_rw(cmd, &fd_prot, false); if (ret < 0) return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE; } ret = fd_do_rw(cmd, sgl, sgl_nents, 0); if (ret > 0 && cmd->prot_type) { u32 sectors = cmd->data_length / dev->dev_attrib.block_size; rc = sbc_dif_verify_read(cmd, cmd->t_task_lba, sectors, 0, fd_prot.prot_sg, 0); if (rc) { kfree(fd_prot.prot_sg); vfree(fd_prot.prot_buf); return rc; } kfree(fd_prot.prot_sg); vfree(fd_prot.prot_buf); } } else { memset(&fd_prot, 0, sizeof(struct fd_prot)); if (cmd->prot_type) { u32 sectors = cmd->data_length / dev->dev_attrib.block_size; ret = fd_do_prot_rw(cmd, &fd_prot, false); if (ret < 0) return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE; rc = sbc_dif_verify_write(cmd, cmd->t_task_lba, sectors, 0, fd_prot.prot_sg, 0); if (rc) { kfree(fd_prot.prot_sg); vfree(fd_prot.prot_buf); return rc; } } ret = fd_do_rw(cmd, sgl, sgl_nents, 1); /* * Perform implicit vfs_fsync_range() for fd_do_writev() ops * for SCSI WRITEs with Forced Unit Access (FUA) set. * Allow this to happen independent of WCE=0 setting. */ if (ret > 0 && dev->dev_attrib.emulate_fua_write > 0 && (cmd->se_cmd_flags & SCF_FUA)) { struct fd_dev *fd_dev = FD_DEV(dev); loff_t start = cmd->t_task_lba * dev->dev_attrib.block_size; loff_t end = start + cmd->data_length; vfs_fsync_range(fd_dev->fd_file, start, end, 1); } if (ret > 0 && cmd->prot_type) { ret = fd_do_prot_rw(cmd, &fd_prot, true); if (ret < 0) return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE; } } if (ret < 0) { kfree(fd_prot.prot_sg); vfree(fd_prot.prot_buf); return TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE; } if (ret) target_complete_cmd(cmd, SAM_STAT_GOOD); return 0; } enum { Opt_fd_dev_name, Opt_fd_dev_size, Opt_fd_buffered_io, Opt_err }; static match_table_t tokens = { {Opt_fd_dev_name, "fd_dev_name=%s"}, {Opt_fd_dev_size, "fd_dev_size=%s"}, {Opt_fd_buffered_io, "fd_buffered_io=%d"}, {Opt_err, NULL} }; static ssize_t fd_set_configfs_dev_params(struct se_device *dev, const char *page, ssize_t count) { struct fd_dev *fd_dev = FD_DEV(dev); char *orig, *ptr, *arg_p, *opts; substring_t args[MAX_OPT_ARGS]; int ret = 0, arg, token; opts = kstrdup(page, GFP_KERNEL); if (!opts) return -ENOMEM; orig = opts; while ((ptr = strsep(&opts, ",\n")) != NULL) { if (!*ptr) continue; token = match_token(ptr, tokens, args); switch (token) { case Opt_fd_dev_name: if (match_strlcpy(fd_dev->fd_dev_name, &args[0], FD_MAX_DEV_NAME) == 0) { ret = -EINVAL; break; } pr_debug("FILEIO: Referencing Path: %s\n", fd_dev->fd_dev_name); fd_dev->fbd_flags |= FBDF_HAS_PATH; break; case Opt_fd_dev_size: arg_p = match_strdup(&args[0]); if (!arg_p) { ret = -ENOMEM; break; } ret = kstrtoull(arg_p, 0, &fd_dev->fd_dev_size); kfree(arg_p); if (ret < 0) { pr_err("kstrtoull() failed for" " fd_dev_size=\n"); goto out; } pr_debug("FILEIO: Referencing Size: %llu" " bytes\n", fd_dev->fd_dev_size); fd_dev->fbd_flags |= FBDF_HAS_SIZE; break; case Opt_fd_buffered_io: match_int(args, &arg); if (arg != 1) { pr_err("bogus fd_buffered_io=%d value\n", arg); ret = -EINVAL; goto out; } pr_debug("FILEIO: Using buffered I/O" " operations for struct fd_dev\n"); fd_dev->fbd_flags |= FDBD_HAS_BUFFERED_IO_WCE; break; default: break; } } out: kfree(orig); return (!ret) ? count : ret; } static ssize_t fd_show_configfs_dev_params(struct se_device *dev, char *b) { struct fd_dev *fd_dev = FD_DEV(dev); ssize_t bl = 0; bl = sprintf(b + bl, "TCM FILEIO ID: %u", fd_dev->fd_dev_id); bl += sprintf(b + bl, " File: %s Size: %llu Mode: %s\n", fd_dev->fd_dev_name, fd_dev->fd_dev_size, (fd_dev->fbd_flags & FDBD_HAS_BUFFERED_IO_WCE) ? "Buffered-WCE" : "O_DSYNC"); return bl; } static sector_t fd_get_blocks(struct se_device *dev) { struct fd_dev *fd_dev = FD_DEV(dev); struct file *f = fd_dev->fd_file; struct inode *i = f->f_mapping->host; unsigned long long dev_size; /* * When using a file that references an underlying struct block_device, * ensure dev_size is always based on the current inode size in order * to handle underlying block_device resize operations. */ if (S_ISBLK(i->i_mode)) dev_size = i_size_read(i); else dev_size = fd_dev->fd_dev_size; return div_u64(dev_size - dev->dev_attrib.block_size, dev->dev_attrib.block_size); } static int fd_init_prot(struct se_device *dev) { struct fd_dev *fd_dev = FD_DEV(dev); struct file *prot_file, *file = fd_dev->fd_file; struct inode *inode; int ret, flags = O_RDWR | O_CREAT | O_LARGEFILE | O_DSYNC; char buf[FD_MAX_DEV_PROT_NAME]; if (!file) { pr_err("Unable to locate fd_dev->fd_file\n"); return -ENODEV; } inode = file->f_mapping->host; if (S_ISBLK(inode->i_mode)) { pr_err("FILEIO Protection emulation only supported on" " !S_ISBLK\n"); return -ENOSYS; } if (fd_dev->fbd_flags & FDBD_HAS_BUFFERED_IO_WCE) flags &= ~O_DSYNC; snprintf(buf, FD_MAX_DEV_PROT_NAME, "%s.protection", fd_dev->fd_dev_name); prot_file = filp_open(buf, flags, 0600); if (IS_ERR(prot_file)) { pr_err("filp_open(%s) failed\n", buf); ret = PTR_ERR(prot_file); return ret; } fd_dev->fd_prot_file = prot_file; return 0; } static void fd_init_format_buf(struct se_device *dev, unsigned char *buf, u32 unit_size, u32 *ref_tag, u16 app_tag, bool inc_reftag) { unsigned char *p = buf; int i; for (i = 0; i < unit_size; i += dev->prot_length) { *((u16 *)&p[0]) = 0xffff; *((__be16 *)&p[2]) = cpu_to_be16(app_tag); *((__be32 *)&p[4]) = cpu_to_be32(*ref_tag); if (inc_reftag) (*ref_tag)++; p += dev->prot_length; } } static int fd_format_prot(struct se_device *dev) { struct fd_dev *fd_dev = FD_DEV(dev); struct file *prot_fd = fd_dev->fd_prot_file; sector_t prot_length, prot; unsigned char *buf; loff_t pos = 0; u32 ref_tag = 0; int unit_size = FDBD_FORMAT_UNIT_SIZE * dev->dev_attrib.block_size; int rc, ret = 0, size, len; bool inc_reftag = false; if (!dev->dev_attrib.pi_prot_type) { pr_err("Unable to format_prot while pi_prot_type == 0\n"); return -ENODEV; } if (!prot_fd) { pr_err("Unable to locate fd_dev->fd_prot_file\n"); return -ENODEV; } switch (dev->dev_attrib.pi_prot_type) { case TARGET_DIF_TYPE3_PROT: ref_tag = 0xffffffff; break; case TARGET_DIF_TYPE2_PROT: case TARGET_DIF_TYPE1_PROT: inc_reftag = true; break; default: break; } buf = vzalloc(unit_size); if (!buf) { pr_err("Unable to allocate FILEIO prot buf\n"); return -ENOMEM; } prot_length = (dev->transport->get_blocks(dev) + 1) * dev->prot_length; size = prot_length; pr_debug("Using FILEIO prot_length: %llu\n", (unsigned long long)prot_length); for (prot = 0; prot < prot_length; prot += unit_size) { fd_init_format_buf(dev, buf, unit_size, &ref_tag, 0xffff, inc_reftag); len = min(unit_size, size); rc = kernel_write(prot_fd, buf, len, pos); if (rc != len) { pr_err("vfs_write to prot file failed: %d\n", rc); ret = -ENODEV; goto out; } pos += len; size -= len; } out: vfree(buf); return ret; } static void fd_free_prot(struct se_device *dev) { struct fd_dev *fd_dev = FD_DEV(dev); if (!fd_dev->fd_prot_file) return; filp_close(fd_dev->fd_prot_file, NULL); fd_dev->fd_prot_file = NULL; } static struct sbc_ops fd_sbc_ops = { .execute_rw = fd_execute_rw, .execute_sync_cache = fd_execute_sync_cache, .execute_write_same = fd_execute_write_same, .execute_write_same_unmap = fd_execute_write_same_unmap, .execute_unmap = fd_execute_unmap, }; static sense_reason_t fd_parse_cdb(struct se_cmd *cmd) { return sbc_parse_cdb(cmd, &fd_sbc_ops); } static struct se_subsystem_api fileio_template = { .name = "fileio", .inquiry_prod = "FILEIO", .inquiry_rev = FD_VERSION, .owner = THIS_MODULE, .transport_type = TRANSPORT_PLUGIN_VHBA_PDEV, .attach_hba = fd_attach_hba, .detach_hba = fd_detach_hba, .alloc_device = fd_alloc_device, .configure_device = fd_configure_device, .free_device = fd_free_device, .parse_cdb = fd_parse_cdb, .set_configfs_dev_params = fd_set_configfs_dev_params, .show_configfs_dev_params = fd_show_configfs_dev_params, .get_device_type = sbc_get_device_type, .get_blocks = fd_get_blocks, .init_prot = fd_init_prot, .format_prot = fd_format_prot, .free_prot = fd_free_prot, }; static int __init fileio_module_init(void) { return transport_subsystem_register(&fileio_template); } static void __exit fileio_module_exit(void) { transport_subsystem_release(&fileio_template); } MODULE_DESCRIPTION("TCM FILEIO subsystem plugin"); MODULE_AUTHOR("nab@Linux-iSCSI.org"); MODULE_LICENSE("GPL"); module_init(fileio_module_init); module_exit(fileio_module_exit);
{ "content_hash": "a84abc0f4aeee76e0f77882a2582ad8d", "timestamp": "", "source": "github", "line_count": 981, "max_line_length": 78, "avg_line_length": 24.978593272171253, "alnum_prop": 0.6351207966046359, "repo_name": "lokeshjindal15/pd-gem5", "id": "cf991a91a8a9699f655fd325f654cb16ed3046d5", "size": "25590", "binary": false, "copies": "179", "ref": "refs/heads/master", "path": "kernel_dvfs/linux-linaro-tracking-gem5/drivers/target/target_core_file.c", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "10138943" }, { "name": "Awk", "bytes": "19269" }, { "name": "C", "bytes": "469972635" }, { "name": "C++", "bytes": "18163034" }, { "name": "CMake", "bytes": "2202" }, { "name": "Clojure", "bytes": "333" }, { "name": "Emacs Lisp", "bytes": "1969" }, { "name": "Groff", "bytes": "63956" }, { "name": "HTML", "bytes": "136898" }, { "name": "Hack", "bytes": "2489" }, { "name": "Java", "bytes": "3096" }, { "name": "Jupyter Notebook", "bytes": "1231954" }, { "name": "Lex", "bytes": "59257" }, { "name": "M4", "bytes": "52982" }, { "name": "Makefile", "bytes": "1453704" }, { "name": "Objective-C", "bytes": "1315749" }, { "name": "Perl", "bytes": "716374" }, { "name": "Perl6", "bytes": "3727" }, { "name": "Protocol Buffer", "bytes": "3246" }, { "name": "Python", "bytes": "4102365" }, { "name": "Scilab", "bytes": "21433" }, { "name": "Shell", "bytes": "512873" }, { "name": "SourcePawn", "bytes": "4687" }, { "name": "UnrealScript", "bytes": "10556" }, { "name": "Visual Basic", "bytes": "2884" }, { "name": "XS", "bytes": "1239" }, { "name": "Yacc", "bytes": "121715" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>schroeder: Not compatible</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.10.1 / schroeder - 8.6.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> schroeder <small> 8.6.0 <span class="label label-info">Not compatible</span> </small> </h1> <p><em><script>document.write(moment("2020-08-05 02:20:17 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2020-08-05 02:20:17 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-num base Num library distributed with the OCaml compiler base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils conf-m4 1 Virtual package relying on m4 coq 8.10.1 Formal proof management system num 0 The Num library for arbitrary-precision integer and rational arithmetic ocaml 4.05.0 The OCaml compiler (virtual package) ocaml-base-compiler 4.05.0 Official 4.05.0 release ocaml-config 1 OCaml Switch Configuration ocamlfind 1.8.1 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;Hugo.Herbelin@inria.fr&quot; homepage: &quot;https://github.com/coq-contribs/schroeder&quot; license: &quot;LGPL 2.1&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/Schroeder&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.6&quot; &amp; &lt; &quot;8.7~&quot;} ] tags: [ &quot;keyword: Schroeder-Bernstein&quot; &quot;keyword: Set Theory&quot; &quot;category: Mathematics/Logic/Set theory&quot; ] authors: [ &quot;Hugo herbelin&quot; ] bug-reports: &quot;https://github.com/coq-contribs/schroeder/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/schroeder.git&quot; synopsis: &quot;The Theorem of Schroeder-Bernstein&quot; description: &quot;&quot;&quot; Fraenkel&#39;s proof of Schroeder-Bernstein theorem on decidable sets is formalized in a constructive variant of set theory based on stratified universes (the one defined in the Ensemble library). The informal proof can be found for instance in &quot;Axiomatic Set Theory&quot; from P. Suppes.&quot;&quot;&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/schroeder/archive/v8.6.0.tar.gz&quot; checksum: &quot;md5=ddca334912fb99be950a0adc39a09c2d&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-schroeder.8.6.0 coq.8.10.1</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.10.1). The following dependencies couldn&#39;t be met: - coq-schroeder -&gt; coq &lt; 8.7~ -&gt; ocaml &lt; 4.03.0 base of this switch (use `--unlock-base&#39; to force) Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-schroeder.8.6.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> <small>Sources are on <a href="https://github.com/coq-bench">GitHub</a>. © Guillaume Claret.</small> </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{ "content_hash": "ad212cd25bc825ae55e1e59101f7fcbe", "timestamp": "", "source": "github", "line_count": 169, "max_line_length": 157, "avg_line_length": 41.994082840236686, "alnum_prop": 0.5496688741721855, "repo_name": "coq-bench/coq-bench.github.io", "id": "26ca3a05f49b78cd8469e6a1286249334e24c4e9", "size": "7099", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.05.0-2.0.6/released/8.10.1/schroeder/8.6.0.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
package immibis.core; import net.minecraft.server.EntityHuman; import net.minecraft.server.TileEntity; public abstract class TileCombined extends TileEntity { public boolean redstone_output = false; public void onBlockNeighbourChange() {} public boolean onBlockActivated(EntityHuman var1) { return false; } public void onBlockRemoval() {} public void notifyNeighbouringBlocks() { this.world.applyPhysics(this.x, this.y, this.z, this.world.getTypeId(this.x, this.y, this.z)); } }
{ "content_hash": "e686fcc0eb6d91851ba1c550875da56d", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 102, "avg_line_length": 23.347826086956523, "alnum_prop": 0.7094972067039106, "repo_name": "mushroomhostage/TubeStuff", "id": "f13be6a89a993c48733bcc107e70e3d9b0a39b97", "size": "537", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "immibis/core/TileCombined.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "146701" }, { "name": "Shell", "bytes": "253" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Login Page - Photon Admin Panel Theme</title> <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0"> <link rel="shortcut icon" href="http://photonui.orangehilldev.com/images/photon/plugins/elrte/js/bootstrap/css/css_compiled/js/js/plugins/favicon.ico"/> <link rel="apple-touch-icon" href="http://photonui.orangehilldev.com/images/photon/plugins/elrte/js/bootstrap/css/css_compiled/js/js/plugins/iosicon.png"/> <link rel="stylesheet" href="http://photonui.orangehilldev.com/images/photon/plugins/elrte/js/bootstrap/css/css_compiled/js/js/plugins/css/css_compiled/photon-min.css?v1.1" media="all"/> <link rel="stylesheet" href="http://photonui.orangehilldev.com/images/photon/plugins/elrte/js/bootstrap/css/css_compiled/js/js/plugins/css/css_compiled/photon-min-part2.css?v1.1" media="all"/> <link rel="stylesheet" href="http://photonui.orangehilldev.com/images/photon/plugins/elrte/js/bootstrap/css/css_compiled/js/js/plugins/css/css_compiled/photon-responsive-min.css?v1.1" media="all"/> <!--[if IE]> <link rel="stylesheet" type="text/css" href="css/css_compiled/ie-only-min.css?v1.1" /> <![endif]--> <!--[if lt IE 9]> <link rel="stylesheet" type="text/css" href="css/css_compiled/ie8-only-min.css?v1.1" /> <script type="text/javascript" src="js/plugins/excanvas.js"></script> <script type="text/javascript" src="js/plugins/html5shiv.js"></script> <script type="text/javascript" src="js/plugins/respond.min.js"></script> <script type="text/javascript" src="js/plugins/fixFontIcons.js"></script> <![endif]--> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.0/jquery-ui.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/js/bootstrap/css/css_compiled/js/js/plugins/js/bootstrap/bootstrap.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/js/bootstrap/css/css_compiled/js/js/plugins/js/plugins/modernizr.custom.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/js/bootstrap/css/css_compiled/js/js/plugins/js/plugins/jquery.pnotify.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/js/bootstrap/css/css_compiled/js/js/plugins/js/plugins/less-1.3.1.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/js/bootstrap/css/css_compiled/js/js/plugins/js/plugins/xbreadcrumbs.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/js/bootstrap/css/css_compiled/js/js/plugins/js/plugins/jquery.maskedinput-1.3.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/js/bootstrap/css/css_compiled/js/js/plugins/js/plugins/jquery.autotab-1.1b.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/js/bootstrap/css/css_compiled/js/js/plugins/js/plugins/charCount.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/js/bootstrap/css/css_compiled/js/js/plugins/js/plugins/jquery.textareaCounter.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/js/bootstrap/css/css_compiled/js/js/plugins/js/plugins/elrte.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/js/bootstrap/css/css_compiled/js/js/plugins/js/plugins/elrte.en.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/js/bootstrap/css/css_compiled/js/js/plugins/js/plugins/select2.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/js/bootstrap/css/css_compiled/js/js/plugins/js/plugins/jquery-picklist.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/js/bootstrap/css/css_compiled/js/js/plugins/js/plugins/jquery.validate.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/js/bootstrap/css/css_compiled/js/js/plugins/js/plugins/additional-methods.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/js/bootstrap/css/css_compiled/js/js/plugins/js/plugins/jquery.form.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/js/bootstrap/css/css_compiled/js/js/plugins/js/plugins/jquery.metadata.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/js/bootstrap/css/css_compiled/js/js/plugins/js/plugins/jquery.mockjax.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/js/bootstrap/css/css_compiled/js/js/plugins/js/plugins/jquery.uniform.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/js/bootstrap/css/css_compiled/js/js/plugins/js/plugins/jquery.tagsinput.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/js/bootstrap/css/css_compiled/js/js/plugins/js/plugins/jquery.rating.pack.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/js/bootstrap/css/css_compiled/js/js/plugins/js/plugins/farbtastic.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/js/bootstrap/css/css_compiled/js/js/plugins/js/plugins/jquery.timeentry.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/js/bootstrap/css/css_compiled/js/js/plugins/js/plugins/jquery.dataTables.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/js/bootstrap/css/css_compiled/js/js/plugins/js/plugins/jquery.jstree.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/js/bootstrap/css/css_compiled/js/js/plugins/js/plugins/dataTables.bootstrap.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/js/bootstrap/css/css_compiled/js/js/plugins/js/plugins/jquery.mousewheel.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/js/bootstrap/css/css_compiled/js/js/plugins/js/plugins/jquery.mCustomScrollbar.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/js/bootstrap/css/css_compiled/js/js/plugins/js/plugins/jquery.flot.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/js/bootstrap/css/css_compiled/js/js/plugins/js/plugins/jquery.flot.stack.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/js/bootstrap/css/css_compiled/js/js/plugins/js/plugins/jquery.flot.pie.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/js/bootstrap/css/css_compiled/js/js/plugins/js/plugins/jquery.flot.resize.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/js/bootstrap/css/css_compiled/js/js/plugins/js/plugins/raphael.2.1.0.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/js/bootstrap/css/css_compiled/js/js/plugins/js/plugins/justgage.1.0.1.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/js/bootstrap/css/css_compiled/js/js/plugins/js/plugins/jquery.qrcode.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/js/bootstrap/css/css_compiled/js/js/plugins/js/plugins/jquery.clock.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/js/bootstrap/css/css_compiled/js/js/plugins/js/plugins/jquery.countdown.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/js/bootstrap/css/css_compiled/js/js/plugins/js/plugins/jquery.jqtweet.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/js/bootstrap/css/css_compiled/js/js/plugins/js/plugins/jquery.cookie.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/js/bootstrap/css/css_compiled/js/js/plugins/js/plugins/bootstrap-fileupload.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/js/bootstrap/css/css_compiled/js/js/plugins/js/plugins/prettify/prettify.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/js/bootstrap/css/css_compiled/js/js/plugins/js/plugins/bootstrapSwitch.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/js/bootstrap/css/css_compiled/js/js/plugins/js/plugins/mfupload.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/js/bootstrap/css/css_compiled/js/js/plugins/js/common.js"></script> </head> <body class="body-login"> <div class="nav-fixed-topright" style="visibility: hidden"> <ul class="nav nav-user-menu"> <li class="user-sub-menu-container"> <a href="javascript:;"> <i class="user-icon"></i><span class="nav-user-selection">Theme Options</span><i class="icon-menu-arrow"></i> </a> <ul class="nav user-sub-menu"> <li class="light"> <a href="javascript:;"> <i class='icon-photon stop'></i>Light Version </a> </li> <li class="dark"> <a href="javascript:;"> <i class='icon-photon stop'></i>Dark Version </a> </li> </ul> </li> <li> <a href="javascript:;"> <i class="icon-photon mail"></i> </a> </li> <li> <a href="javascript:;"> <i class="icon-photon comment_alt2_stroke"></i> <div class="notification-count">12</div> </a> </li> </ul> </div> <script> $(function(){ setTimeout(function(){ $('.nav-fixed-topright').removeAttr('style'); }, 300); $(window).scroll(function(){ if($('.breadcrumb-container').length){ var scrollState = $(window).scrollTop(); if (scrollState > 0) $('.nav-fixed-topright').addClass('nav-released'); else $('.nav-fixed-topright').removeClass('nav-released') } }); $('.user-sub-menu-container').on('click', function(){ $(this).toggleClass('active-user-menu'); }); $('.user-sub-menu .light').on('click', function(){ if ($('body').is('.light-version')) return; $('body').addClass('light-version'); setTimeout(function() { $.cookie('themeColor', 'light', { expires: 7, path: '/' }); }, 500); }); $('.user-sub-menu .dark').on('click', function(){ if ($('body').is('.light-version')) { $('body').removeClass('light-version'); $.cookie('themeColor', 'dark', { expires: 7, path: '/' }); } }); }); </script> <div class="container-login"> <div class="form-centering-wrapper"> <div class="form-window-login"> <div class="form-window-login-logo"> <div class="login-logo"> <img src="http://photonui.orangehilldev.com/images/photon/plugins/elrte/js/bootstrap/css/css_compiled/js/js/plugins/images/photon/login-logo@2x.png" alt="Photon UI"/> </div> <h2 class="login-title">Welcome to Photon UI!</h2> <div class="login-member">Not a Member?&nbsp;<a href="jquery.cookie.js.html#">Sign Up &#187;</a> <a href="jquery.cookie.js.html#" class="btn btn-facebook"><i class="icon-fb"></i>Login with Facebook<i class="icon-fb-arrow"></i></a> </div> <div class="login-or">Or</div> <div class="login-input-area"> <form method="POST" action="dashboard.php"> <span class="help-block">Login With Your Photon Account</span> <input type="text" name="email" placeholder="Email"> <input type="password" name="password" placeholder="Password"> <button type="submit" class="btn btn-large btn-success btn-login">Login</button> </form> <a href="jquery.cookie.js.html#" class="forgot-pass">Forgot Your Password?</a> </div> </div> </div> </div> </div> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-1936460-27']); _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>
{ "content_hash": "8de3bce103d57b4387437475f30a7d64", "timestamp": "", "source": "github", "line_count": 182, "max_line_length": 197, "avg_line_length": 75.20879120879121, "alnum_prop": 0.7274985388661601, "repo_name": "user-tony/photon-rails", "id": "195f40f2e739f533f8e92881acb5a40478ad7fb4", "size": "13688", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/assets/images/photon/plugins/elrte/js/bootstrap/css/css_compiled/js/js/plugins/jquery.cookie.js.html", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "291750913" }, { "name": "JavaScript", "bytes": "59305" }, { "name": "Ruby", "bytes": "203" }, { "name": "Shell", "bytes": "99" } ], "symlink_target": "" }
package ahcming.kit.gc.parse; import ahcming.kit.gc.kit.XmlUtil; import ahcming.kit.gc.model.Domain; import ahcming.kit.gc.model.GC; import ahcming.kit.gc.model.Project; import ahcming.kit.gc.model.Storage; import ahcming.kit.gc.xml.ParserEntityResolver; import ahcming.kit.gc.xml.ParserErrorHandler; import org.apache.maven.plugin.logging.Log; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import java.io.FileInputStream; import java.io.InputStream; import java.util.ArrayList; import java.util.List; public class ConfigParser { private String configPath; private List<String> warnings = new ArrayList<String>(); private List<String> parseErrors = new ArrayList<String>(); private Project project; private Storage storage; private Domain domain; private GC gc; public ConfigParser(String configPath) { this.configPath = configPath; } public void parse(Log log) { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(true); try { DocumentBuilder builder = factory.newDocumentBuilder(); builder.setEntityResolver(new ParserEntityResolver()); builder.setErrorHandler(new ParserErrorHandler(warnings, parseErrors)); InputStream is = new FileInputStream(configPath); InputSource inputSource = new InputSource(is); Document document = builder.parse(inputSource); Element rootNode = document.getDocumentElement(); _parseProject(rootNode); _parseStorage(rootNode); _parseDomain(rootNode); _parseGc(rootNode); if (warnings.size() > 0) { for (String warn : warnings) { log.warn(warn); } } if (parseErrors.size() > 0) { for (String error : parseErrors) { log.error(error); } } } catch (Exception e) { e.printStackTrace(); log.error("parse gc config exception:", e); } } void _parseProject(Element root) { NodeList projectHead = root.getElementsByTagName("project"); if(projectHead.getLength() > 0) { Project config = new Project(); NodeList childNodes = projectHead.item(0).getChildNodes(); for (int index = 0; index < childNodes.getLength(); index++) { Node node = childNodes.item(index); if (node.getNodeName().equalsIgnoreCase("mapper.interface.path")) { config.setMapperInterfacePath(node.getTextContent()); } else if (node.getNodeName().equalsIgnoreCase("mapper.xml.path")) { config.setMapperXmlPath(node.getTextContent()); } } this.setProject(config); } } void _parseStorage(Element root) { NodeList storageRoot = root.getElementsByTagName("storage"); if (storageRoot.getLength() > 0) { this.storage = XmlUtil.parseNode(storageRoot.item(0), Storage.class); } } void _parseDomain(Element root) { NodeList domainRoot = root.getElementsByTagName("domain"); if (domainRoot.getLength() > 0) { this.domain = new Domain(); List<Domain.Entity> entities = new ArrayList<Domain.Entity>(); NodeList entityNodes = domainRoot.item(0).getChildNodes(); for (int idx = 0; idx < entityNodes.getLength(); idx++) { Node entityNode = entityNodes.item(idx); if(entityNode.getNodeType() == Node.ELEMENT_NODE) { Domain.Entity entity = XmlUtil.parseNode(entityNode, Domain.Entity.class); entities.add(entity); } } this.domain.entities = entities; } } void _parseGc(Element root) { NodeList gcRoot = root.getElementsByTagName("gc"); if(gcRoot.getLength() > 0) { this.gc = XmlUtil.parseNode(gcRoot.item(0), GC.class); } } public Project getProject() { return project; } public void setProject(Project project) { this.project = project; } public Storage getStorage() { return storage; } public void setStorage(Storage storage) { this.storage = storage; } public Domain getDomain() { return domain; } public void setDomain(Domain domain) { this.domain = domain; } public GC getGc() { return gc; } public void setGc(GC gc) { this.gc = gc; } }
{ "content_hash": "c23885e47c84d2a06760fbf743fb90e0", "timestamp": "", "source": "github", "line_count": 161, "max_line_length": 94, "avg_line_length": 30.267080745341616, "alnum_prop": 0.6031192284013954, "repo_name": "tesla-cm/codeRobot", "id": "61cf7804d462c098a9aaa752e42ed7bcf3cc330d", "size": "4873", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "gc/src/main/java/ahcming/kit/gc/parse/ConfigParser.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "27294" } ], "symlink_target": "" }
package com.thoughtworks.go.apiv1.webhook.request; import com.thoughtworks.go.apiv1.webhook.request.payload.Payload; import com.thoughtworks.go.config.exceptions.BadRequestException; import org.junit.jupiter.api.Test; import spark.QueryParamsMap; import spark.Request; import java.util.Set; import static com.thoughtworks.go.apiv1.webhook.request.WebhookRequest.KEY_SCM_NAME; import static java.util.Collections.singletonList; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.springframework.http.MediaType.*; class WebhookRequestTest { @Test void onlySupportsJsonPayload() { assertEquals(Set.of(APPLICATION_JSON, APPLICATION_JSON_UTF8), webhook(mockRequest("")).supportedContentTypes()); } @Test void rejectsNonGitPayloads() { assertEquals("GoCD currently only supports webhooks on `git` repositories; `repo` is a `svn` repository", assertThrows(BadRequestException.class, () -> webhook(mockRequest("{}")).parsePayload(NonGitPayload.class)).getMessage() ); } @Test void returnsEmptyScmNamesWhenNoneProvided() { assertTrue(webhook(new Request() { @Override public QueryParamsMap queryMap() { return new QueryParamsMap() { }; } }).scmNamesQuery().isEmpty()); } @Test void returnsScmNamesWhenProvided() { assertEquals(singletonList("scm1"), webhook(new Request() { @Override public QueryParamsMap queryMap() { return new QueryParamsMap(KEY_SCM_NAME, "scm1") { }; } }).scmNamesQuery()); } private WebhookRequest webhook(Request req) { return new WebhookRequest(req) { @Override public String authToken() { return "auth"; } @Override public String event() { return "event"; } }; } private Request mockRequest(String body) { final Request req = mock(Request.class); when(req.body()).thenReturn(body); when(req.contentType()).thenReturn(APPLICATION_JSON_VALUE); return req; } private static class NonGitPayload implements Payload { @Override public String hostname() { return "host"; } @Override public String fullName() { return "repo"; } @Override public String scmType() { return "svn"; } @Override public String descriptor() { return getClass().getSimpleName(); } } }
{ "content_hash": "828c12192ddc0a38b09ee1d470924daa", "timestamp": "", "source": "github", "line_count": 99, "max_line_length": 120, "avg_line_length": 28.09090909090909, "alnum_prop": 0.6040992448759439, "repo_name": "Skarlso/gocd", "id": "7d2ab6d3a7026aecd39fcc5adc03e04da6baa57e", "size": "3382", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "api/api-webhook-v1/src/test/groovy/com/thoughtworks/go/apiv1/webhook/request/WebhookRequestTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "474" }, { "name": "CSS", "bytes": "1578" }, { "name": "EJS", "bytes": "1626" }, { "name": "FreeMarker", "bytes": "48379" }, { "name": "Groovy", "bytes": "2439752" }, { "name": "HTML", "bytes": "275640" }, { "name": "Java", "bytes": "21175732" }, { "name": "JavaScript", "bytes": "837258" }, { "name": "NSIS", "bytes": "24216" }, { "name": "Ruby", "bytes": "426376" }, { "name": "SCSS", "bytes": "661872" }, { "name": "Shell", "bytes": "13847" }, { "name": "TypeScript", "bytes": "4435018" }, { "name": "XSLT", "bytes": "206746" } ], "symlink_target": "" }
title: Release 0.49 short-description: Release notes for 0.49 ... # New features ## Libgcrypt dependency now supports libgcrypt-config Earlier, `dependency('libgcrypt')` could only detect the library with pkg-config files. Now, if pkg-config files are not found, Meson will look for `libgcrypt-config` and if it's found, will use that to find the library. ## New `section` key for the buildoptions introspection Meson now has a new `section` key in each build option. This allows IDEs to group these options similar to `meson configure`. The possible values for `section` are: - core - backend - base - compiler - directory - user - test ## CC-RX compiler for C and CPP Cross-compilation is now supported for Renesas RX targets with the CC-RX compiler. The environment path should be set properly for the CC-RX compiler executables. The `-cpu` option with the appropriate value should be mentioned in the cross-file as shown in the snippet below. ```ini [properties] c_args = ['-cpu=rx600'] cpp_args = ['-cpu=rx600'] ``` The default extension of the executable output is `.abs`. Other target specific arguments to the compiler and linker will need to be added explicitly from the cross-file(`c_args`/`c_link_args`/`cpp_args`/`cpp_link_args`) or some other way. Refer to the CC-RX User's manual for additional compiler and linker options. ## CMake `find_package` dependency backend Meson can now use the CMake `find_package` ecosystem to detect dependencies. Both the old-style `<NAME>_LIBRARIES` variables as well as imported targets are supported. Meson can automatically guess the correct CMake target in most cases but it is also possible to manually specify a target with the `modules` property. ```meson # Implicitly uses CMake as a fallback and guesses a target dep1 = dependency('KF5TextEditor') # Manually specify one or more CMake targets to use dep2 = dependency('ZLIB', method : 'cmake', modules : ['ZLIB::ZLIB']) ``` CMake is automatically used after `pkg-config` fails when no `method` (or `auto`) was provided in the dependency options. ## New compiler method `get_argument_syntax` The compiler object now has `get_argument_syntax` method, which returns a string value of `gcc`, `msvc`, or an undefined value string value. This can be used to determine if a compiler uses gcc syntax (`-Wfoo`), msvc syntax (`/w1234`), or some other kind of arguments. ```meson cc = meson.get_compiler('c') if cc.get_argument_syntax() == 'msvc' if cc.has_argument('/w1235') add_project_arguments('/w1235', language : ['c']) endif elif cc.get_argument_syntax() == 'gcc' if cc.has_argument('-Wfoo') add_project_arguments('-Wfoo', language : ['c']) endif elif cc.get_id() == 'some other compiler' add_project_arguments('--error-on-foo', language : ['c']) endif ``` ## Return `Disabler()` instead of not-found object Functions such as `dependency()`, `find_library()`, `find_program()`, and `python.find_installation()` have a new keyword argument: `disabler`. When set to `true` those functions return `Disabler()` objects instead of not-found objects. ## `introspect --projectinfo` can now be used without configured build directory This allows IDE integration to get information about the project before the user has configured a build directory. Before you could use `meson.py introspect --projectinfo build-directory`. Now you also can use `meson.py introspect --projectinfo project-dir/meson.build`. The output is similiar to the output with a build directory but additionally also includes information from `introspect --buildsystem-files`. For example `meson.py introspect --projectinfo test\ cases/common/47\ subproject\ options/meson.build` This outputs (pretty printed for readability): ``` { "buildsystem_files": [ "meson_options.txt", "meson.build" ], "name": "suboptions", "version": null, "descriptive_name": "suboptions", "subprojects": [ { "buildsystem_files": [ "subprojects/subproject/meson_options.txt", "subprojects/subproject/meson.build" ], "name": "subproject", "version": "undefined", "descriptive_name": "subproject" } ] } ``` Both usages now include a new `descriptive_name` property which always shows the name set in the project. ## Can specify keyword arguments with a dictionary You can now specify keyword arguments for any function and method call with the `kwargs` keyword argument. This is perhaps best described with an example: ```meson options = {'include_directories': include_directories('inc')} ... executable(... kwargs: options) ``` The above code is identical to this: ```meson executable(... include_directories: include_directories('inc')) ``` That is, Meson will expand the dictionary given to `kwargs` as if the entries in it had been given as keyword arguments directly. Note that any individual argument can be specified either directly or with the `kwarg` dict but not both. If a key is specified twice, it is a hard error. ## Manpages are no longer compressed implicitly Earlier, the `install_man` command has automatically compressed installed manpages into `.gz` format. This collided with manpage compression hooks already used by various distributions. Now, manpages are installed uncompressed and distributors are expected to handle compressing them according to their own compression preferences. ## Native config files Native files (`--native-file`) are the counterpart to cross files (`--cross-file`), and allow specifying information about the build machine, both when cross compiling and when not. Currently the native files only allow specifying the names of binaries, similar to the cross file, for example: ```ini [binaries] llvm-config = "/opt/llvm-custom/bin/llvm-config" ``` Will override the llvm-config used for *native* binaries. Targets for the host machine will continue to use the cross file. ## Foreach `break` and `continue` `break` and `continue` keywords can be used inside foreach loops. ```meson items = ['a', 'continue', 'b', 'break', 'c'] result = [] foreach i : items if i == 'continue' continue elif i == 'break' break endif result += i endforeach # result is ['a', 'b'] ``` You can check if an array contains an element like this: ```meson my_array = [1, 2] if 1 in my_array # This condition is true endif if 1 not in my_array # This condition is false endif ``` You can check if a dictionary contains a key like this: ```meson my_dict = {'foo': 42, 'foo': 43} if 'foo' in my_dict # This condition is true endif if 42 in my_dict # This condition is false endif if 'foo' not in my_dict # This condition is false endif ``` ## Joining paths with / For clarity and conciseness, we recommend using the `/` operator to separate path elements: ```meson joined = 'foo' / 'bar' ``` Before Meson 0.49, joining path elements was done with the legacy `join_paths` function, but the `/` syntax above is now recommended. ```meson joined = join_paths('foo', 'bar') ``` This only works for strings. ## Position-independent executables When `b_pie` option, or `executable()`'s `pie` keyword argument is set to `true`, position-independent executables are built. All their objects are built with `-fPIE` and the executable is linked with `-pie`. Any static library they link must be built with `pic` set to `true` (see `b_staticpic` option). ## Deprecation warning in pkg-config generator All libraries passed to the `libraries` keyword argument of the `generate()` method used to be associated with that generated pkg-config file. That means that any subsequent call to `generate()` where those libraries appear would add the filebase of the `generate()` that first contained them into `Requires:` or `Requires.private:` field instead of adding an `-l` to `Libs:` or `Libs.private:`. This behaviour is now deprecated. The library that should be associated with the generated pkg-config file should be passed as first positional argument instead of in the `libraries` keyword argument. The previous behaviour is maintained but prints a deprecation warning and support for this will be removed in a future Meson release. If you can not create the needed pkg-config file without this warning, please file an issue with as much details as possible about the situation. For example this sample will write `Requires: liba` into `libb.pc` but print a deprecation warning: ```meson liba = library(...) pkg.generate(libraries : liba) libb = library(...) pkg.generate(libraries : [liba, libb]) ``` It can be fixed by passing `liba` as first positional argument:: ```meson liba = library(...) pkg.generate(liba) libb = library(...) pkg.generate(libb, libraries : [liba]) ``` ## Subprojects download, checkout, update command-line New command-line tool has been added to manage subprojects: - `meson subprojects download` to download all subprojects that have a wrap file. - `meson subprojects update` to update all subprojects to latest version. - `meson subprojects checkout` to checkout or create a branch in all git subprojects. ## New keyword argument `is_default` to `add_test_setup()` The keyword argument `is_default` may be used to set whether the test setup should be used by default whenever `meson test` is run without the `--setup` option. ```meson add_test_setup('default', is_default: true, env: 'G_SLICE=debug-blocks') add_test_setup('valgrind', env: 'G_SLICE=always-malloc', ...) test('mytest', exe) ``` For the example above, running `meson test` and `meson test --setup=default` is now equivalent.
{ "content_hash": "5fbde28ab2c3a33546c8a2b0a06c41f7", "timestamp": "", "source": "github", "line_count": 315, "max_line_length": 141, "avg_line_length": 30.61904761904762, "alnum_prop": 0.7301192327630897, "repo_name": "becm/meson", "id": "9a5e5f53b9309bae025f04e95c2b67c30dab8174", "size": "9649", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/markdown/Release-notes-for-0.49.0.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "4190" }, { "name": "Batchfile", "bytes": "131" }, { "name": "C", "bytes": "167971" }, { "name": "C#", "bytes": "1130" }, { "name": "C++", "bytes": "51171" }, { "name": "CMake", "bytes": "27103" }, { "name": "Cuda", "bytes": "7454" }, { "name": "D", "bytes": "5313" }, { "name": "Dockerfile", "bytes": "1960" }, { "name": "Emacs Lisp", "bytes": "919" }, { "name": "Fortran", "bytes": "11539" }, { "name": "Genie", "bytes": "341" }, { "name": "HTML", "bytes": "117" }, { "name": "Inno Setup", "bytes": "354" }, { "name": "Java", "bytes": "2570" }, { "name": "JavaScript", "bytes": "136" }, { "name": "LLVM", "bytes": "75" }, { "name": "Lex", "bytes": "139" }, { "name": "Meson", "bytes": "454262" }, { "name": "Objective-C", "bytes": "1235" }, { "name": "Objective-C++", "bytes": "381" }, { "name": "PowerShell", "bytes": "2242" }, { "name": "Python", "bytes": "2912935" }, { "name": "Roff", "bytes": "569" }, { "name": "Rust", "bytes": "1079" }, { "name": "Shell", "bytes": "6800" }, { "name": "Swift", "bytes": "1152" }, { "name": "Vala", "bytes": "10025" }, { "name": "Verilog", "bytes": "709" }, { "name": "Vim script", "bytes": "9919" }, { "name": "Yacc", "bytes": "50" } ], "symlink_target": "" }
 using Finsa.CodeServices.Common.Text; using NUnit.Framework; using System; using System.Collections.Generic; using System.Text; namespace Finsa.CodeServices.UnitTests.Common.Text { [TestFixture] public class diff_match_patchTest : diff_match_patch { [Test] public void diff_commonPrefixTest() { diff_match_patchTest dmp = new diff_match_patchTest(); // Detect and remove any common suffix. Assert.AreEqual(0, dmp.diff_commonPrefix("abc", "xyz")); Assert.AreEqual(4, dmp.diff_commonPrefix("1234abcdef", "1234xyz")); Assert.AreEqual(4, dmp.diff_commonPrefix("1234", "1234xyz")); } [Test] public void diff_commonSuffixTest() { diff_match_patchTest dmp = new diff_match_patchTest(); // Detect and remove any common suffix. Assert.AreEqual(0, dmp.diff_commonSuffix("abc", "xyz")); Assert.AreEqual(4, dmp.diff_commonSuffix("abcdef1234", "xyz1234")); Assert.AreEqual(4, dmp.diff_commonSuffix("1234", "xyz1234")); } [Test] public void diff_halfmatchTest() { diff_match_patchTest dmp = new diff_match_patchTest(); Assert.IsNull(dmp.diff_halfMatch("1234567890", "abcdef")); CollectionAssert.AreEqual(new string[] { "12", "90", "a", "z", "345678" }, dmp.diff_halfMatch("1234567890", "a345678z")); CollectionAssert.AreEqual(new string[] { "a", "z", "12", "90", "345678" }, dmp.diff_halfMatch("a345678z", "1234567890")); CollectionAssert.AreEqual(new string[] { "12123", "123121", "a", "z", "1234123451234" }, dmp.diff_halfMatch("121231234123451234123121", "a1234123451234z")); CollectionAssert.AreEqual(new string[] { "", "-=-=-=-=-=", "x", "", "x-=-=-=-=-=-=-=" }, dmp.diff_halfMatch("x-=-=-=-=-=-=-=-=-=-=-=-=", "xx-=-=-=-=-=-=-=")); CollectionAssert.AreEqual(new string[] { "-=-=-=-=-=", "", "", "y", "-=-=-=-=-=-=-=y" }, dmp.diff_halfMatch("-=-=-=-=-=-=-=-=-=-=-=-=y", "-=-=-=-=-=-=-=yy")); } [Test] public void diff_linesToCharsTest() { diff_match_patchTest dmp = new diff_match_patchTest(); // Convert lines down to characters. List<string> tmpVector = new List<string>(); tmpVector.Add(""); tmpVector.Add("alpha\n"); tmpVector.Add("beta\n"); var result = dmp.diff_linesToChars("alpha\nbeta\nalpha\n", "beta\nalpha\nbeta\n"); Assert.AreEqual("\u0001\u0002\u0001", result[0]); Assert.AreEqual("\u0002\u0001\u0002", result[1]); CollectionAssert.AreEqual(tmpVector, (List<string>) result[2]); tmpVector.Clear(); tmpVector.Add(""); tmpVector.Add("alpha\r\n"); tmpVector.Add("beta\r\n"); tmpVector.Add("\r\n"); result = dmp.diff_linesToChars("", "alpha\r\nbeta\r\n\r\n\r\n"); Assert.AreEqual("", result[0]); Assert.AreEqual("\u0001\u0002\u0003\u0003", result[1]); CollectionAssert.AreEqual(tmpVector, (List<string>) result[2]); tmpVector.Clear(); tmpVector.Add(""); tmpVector.Add("a"); tmpVector.Add("b"); result = dmp.diff_linesToChars("a", "b"); Assert.AreEqual("\u0001", result[0]); Assert.AreEqual("\u0002", result[1]); CollectionAssert.AreEqual(tmpVector, (List<string>) result[2]); // More than 256 to reveal any 8-bit limitations. int n = 300; tmpVector.Clear(); StringBuilder lineList = new StringBuilder(); StringBuilder charList = new StringBuilder(); for (int x = 1; x < n + 1; x++) { tmpVector.Add(x + "\n"); lineList.Append(x + "\n"); charList.Append(Convert.ToChar(x)); } Assert.AreEqual(n, tmpVector.Count); string lines = lineList.ToString(); string chars = charList.ToString(); Assert.AreEqual(n, chars.Length); tmpVector.Insert(0, ""); result = dmp.diff_linesToChars(lines, ""); Assert.AreEqual(chars, result[0]); Assert.AreEqual("", result[1]); CollectionAssert.AreEqual(tmpVector, (List<string>) result[2]); } [Test] public void diff_charsToLinesTest() { diff_match_patchTest dmp = new diff_match_patchTest(); Assert.AreEqual(new Diff(Operation.EQUAL, "a"), new Diff(Operation.EQUAL, "a")); // Convert chars up to lines. List<Diff> diffs = new List<Diff>{ new Diff(Operation.EQUAL, "\u0001\u0002\u0001"), new Diff(Operation.INSERT, "\u0002\u0001\u0002")}; List<string> tmpVector = new List<string>(); tmpVector.Add(""); tmpVector.Add("alpha\n"); tmpVector.Add("beta\n"); dmp.diff_charsToLines(diffs, tmpVector); CollectionAssert.AreEqual(new List<Diff> { new Diff(Operation.EQUAL, "alpha\nbeta\nalpha\n"), new Diff(Operation.INSERT, "beta\nalpha\nbeta\n")}, diffs); // More than 256 to reveal any 8-bit limitations. int n = 300; tmpVector.Clear(); StringBuilder lineList = new StringBuilder(); StringBuilder charList = new StringBuilder(); for (int x = 1; x < n + 1; x++) { tmpVector.Add(x + "\n"); lineList.Append(x + "\n"); charList.Append(Convert.ToChar(x)); } Assert.AreEqual(n, tmpVector.Count); string lines = lineList.ToString(); string chars = charList.ToString(); Assert.AreEqual(n, chars.Length); tmpVector.Insert(0, ""); diffs = new List<Diff> { new Diff(Operation.DELETE, chars) }; dmp.diff_charsToLines(diffs, tmpVector); CollectionAssert.AreEqual(new List<Diff> {new Diff(Operation.DELETE, lines)}, diffs); } [Test] public void diff_cleanupMergeTest() { diff_match_patchTest dmp = new diff_match_patchTest(); // Cleanup a messy diff. List<Diff> diffs = new List<Diff>(); dmp.diff_cleanupMerge(diffs); CollectionAssert.AreEqual(new List<Diff>(), diffs); diffs = new List<Diff> { new Diff(Operation.EQUAL, "a"), new Diff(Operation.DELETE, "b"), new Diff(Operation.INSERT, "c") }; dmp.diff_cleanupMerge(diffs); CollectionAssert.AreEqual(new List<Diff> { new Diff(Operation.EQUAL, "a"), new Diff(Operation.DELETE, "b"), new Diff(Operation.INSERT, "c") }, diffs); diffs = new List<Diff> { new Diff(Operation.EQUAL, "a"), new Diff(Operation.EQUAL, "b"), new Diff(Operation.EQUAL, "c") }; dmp.diff_cleanupMerge(diffs); CollectionAssert.AreEqual(new List<Diff> { new Diff(Operation.EQUAL, "abc") }, diffs); diffs = new List<Diff> { new Diff(Operation.DELETE, "a"), new Diff(Operation.DELETE, "b"), new Diff(Operation.DELETE, "c") }; dmp.diff_cleanupMerge(diffs); CollectionAssert.AreEqual(new List<Diff> { new Diff(Operation.DELETE, "abc") }, diffs); diffs = new List<Diff> { new Diff(Operation.INSERT, "a"), new Diff(Operation.INSERT, "b"), new Diff(Operation.INSERT, "c") }; dmp.diff_cleanupMerge(diffs); CollectionAssert.AreEqual(new List<Diff> { new Diff(Operation.INSERT, "abc") }, diffs); diffs = new List<Diff> { new Diff(Operation.DELETE, "a"), new Diff(Operation.INSERT, "b"), new Diff(Operation.DELETE, "c"), new Diff(Operation.INSERT, "d"), new Diff(Operation.EQUAL, "e"), new Diff(Operation.EQUAL, "f") }; dmp.diff_cleanupMerge(diffs); CollectionAssert.AreEqual(new List<Diff> { new Diff(Operation.DELETE, "ac"), new Diff(Operation.INSERT, "bd"), new Diff(Operation.EQUAL, "ef") }, diffs); diffs = new List<Diff> { new Diff(Operation.DELETE, "a"), new Diff(Operation.INSERT, "abc"), new Diff(Operation.DELETE, "dc") }; dmp.diff_cleanupMerge(diffs); CollectionAssert.AreEqual(new List<Diff> { new Diff(Operation.EQUAL, "a"), new Diff(Operation.DELETE, "d"), new Diff(Operation.INSERT, "b"), new Diff(Operation.EQUAL, "c") }, diffs); diffs = new List<Diff> { new Diff(Operation.EQUAL, "a"), new Diff(Operation.INSERT, "ba"), new Diff(Operation.EQUAL, "c") }; dmp.diff_cleanupMerge(diffs); CollectionAssert.AreEqual(new List<Diff> { new Diff(Operation.INSERT, "ab"), new Diff(Operation.EQUAL, "ac") }, diffs); diffs = new List<Diff> { new Diff(Operation.EQUAL, "c"), new Diff(Operation.INSERT, "ab"), new Diff(Operation.EQUAL, "a") }; dmp.diff_cleanupMerge(diffs); CollectionAssert.AreEqual(new List<Diff> { new Diff(Operation.EQUAL, "ca"), new Diff(Operation.INSERT, "ba") }, diffs); diffs = new List<Diff> { new Diff(Operation.EQUAL, "a"), new Diff(Operation.DELETE, "b"), new Diff(Operation.EQUAL, "c"), new Diff(Operation.DELETE, "ac"), new Diff(Operation.EQUAL, "x") }; dmp.diff_cleanupMerge(diffs); CollectionAssert.AreEqual(new List<Diff> { new Diff(Operation.DELETE, "abc"), new Diff(Operation.EQUAL, "acx") }, diffs); diffs = new List<Diff> { new Diff(Operation.EQUAL, "x"), new Diff(Operation.DELETE, "ca"), new Diff(Operation.EQUAL, "c"), new Diff(Operation.DELETE, "b"), new Diff(Operation.EQUAL, "a") }; dmp.diff_cleanupMerge(diffs); CollectionAssert.AreEqual(new List<Diff> { new Diff(Operation.EQUAL, "xca"), new Diff(Operation.DELETE, "cba") }, diffs); } [Test] public void diff_cleanupSemanticLosslessTest() { diff_match_patchTest dmp = new diff_match_patchTest(); // Slide diffs to match logical boundaries. List<Diff> diffs = new List<Diff>(); dmp.diff_cleanupSemanticLossless(diffs); CollectionAssert.AreEqual(new List<Diff>(), diffs); diffs = new List<Diff> { new Diff(Operation.EQUAL, "AAA\r\n\r\nBBB"), new Diff(Operation.INSERT, "\r\nDDD\r\n\r\nBBB"), new Diff(Operation.EQUAL, "\r\nEEE") }; dmp.diff_cleanupSemanticLossless(diffs); CollectionAssert.AreEqual( new List<Diff>{ new Diff(Operation.EQUAL, "AAA\r\n\r\n"), new Diff(Operation.INSERT, "BBB\r\nDDD\r\n\r\n"), new Diff(Operation.EQUAL, "BBB\r\nEEE")}, diffs); diffs = new List<Diff>{ new Diff(Operation.EQUAL, "AAA\r\nBBB"), new Diff(Operation.INSERT, " DDD\r\nBBB"), new Diff(Operation.EQUAL, " EEE")}; dmp.diff_cleanupSemanticLossless(diffs); CollectionAssert.AreEqual( new List<Diff>{ new Diff(Operation.EQUAL, "AAA\r\n"), new Diff(Operation.INSERT, "BBB DDD\r\n"), new Diff(Operation.EQUAL, "BBB EEE")}, diffs); diffs = new List<Diff>{ new Diff(Operation.EQUAL, "The c"), new Diff(Operation.INSERT, "ow and the c"), new Diff(Operation.EQUAL, "at.")}; dmp.diff_cleanupSemanticLossless(diffs); CollectionAssert.AreEqual(new List<Diff>{ new Diff(Operation.EQUAL, "The "), new Diff(Operation.INSERT, "cow and the "), new Diff(Operation.EQUAL, "cat.")}, diffs); diffs = new List<Diff>{ new Diff(Operation.EQUAL, "The-c"), new Diff(Operation.INSERT, "ow-and-the-c"), new Diff(Operation.EQUAL, "at.")}; dmp.diff_cleanupSemanticLossless(diffs); CollectionAssert.AreEqual(new List<Diff>{ new Diff(Operation.EQUAL, "The-"), new Diff(Operation.INSERT, "cow-and-the-"), new Diff(Operation.EQUAL, "cat.")}, diffs); diffs = new List<Diff>{ new Diff(Operation.EQUAL, "a"), new Diff(Operation.DELETE, "a"), new Diff(Operation.EQUAL, "ax")}; dmp.diff_cleanupSemanticLossless(diffs); CollectionAssert.AreEqual(new List<Diff>{ new Diff(Operation.DELETE, "a"), new Diff(Operation.EQUAL, "aax")}, diffs); diffs = new List<Diff>{ new Diff(Operation.EQUAL, "xa"), new Diff(Operation.DELETE, "a"), new Diff(Operation.EQUAL, "a")}; dmp.diff_cleanupSemanticLossless(diffs); CollectionAssert.AreEqual(new List<Diff>{ new Diff(Operation.EQUAL, "xaa"), new Diff(Operation.DELETE, "a")}, diffs); } [Test] public void diff_cleanupSemanticTest() { diff_match_patchTest dmp = new diff_match_patchTest(); // Cleanup semantically trivial equalities. List<Diff> diffs = new List<Diff>(); dmp.diff_cleanupSemantic(diffs); CollectionAssert.AreEqual(new List<Diff>(), diffs); diffs = new List<Diff>{ new Diff(Operation.DELETE, "a"), new Diff(Operation.INSERT, "b"), new Diff(Operation.EQUAL, "cd"), new Diff(Operation.DELETE, "e")}; dmp.diff_cleanupSemantic(diffs); CollectionAssert.AreEqual( new List<Diff>{ new Diff(Operation.DELETE, "a"), new Diff(Operation.INSERT, "b"), new Diff(Operation.EQUAL, "cd"), new Diff(Operation.DELETE, "e")}, diffs); diffs = new List<Diff>{ new Diff(Operation.DELETE, "a"), new Diff(Operation.EQUAL, "b"), new Diff(Operation.DELETE, "c")}; dmp.diff_cleanupSemantic(diffs); CollectionAssert.AreEqual( new List<Diff>{ new Diff(Operation.DELETE, "abc"), new Diff(Operation.INSERT, "b")}, diffs); diffs = new List<Diff>{ new Diff(Operation.DELETE, "ab"), new Diff(Operation.EQUAL, "cd"), new Diff(Operation.DELETE, "e"), new Diff(Operation.EQUAL, "f"), new Diff(Operation.INSERT, "g")}; dmp.diff_cleanupSemantic(diffs); CollectionAssert.AreEqual(new List<Diff>{ new Diff(Operation.DELETE, "abcdef"), new Diff(Operation.INSERT, "cdfg")}, diffs); diffs = new List<Diff>{ new Diff(Operation.INSERT, "1"), new Diff(Operation.EQUAL, "A"), new Diff(Operation.DELETE, "B"), new Diff(Operation.INSERT, "2"), new Diff(Operation.EQUAL, "_"), new Diff(Operation.INSERT, "1"), new Diff(Operation.EQUAL, "A"), new Diff(Operation.DELETE, "B"), new Diff(Operation.INSERT, "2")}; dmp.diff_cleanupSemantic(diffs); CollectionAssert.AreEqual(new List<Diff>{ new Diff(Operation.DELETE, "AB_AB"), new Diff(Operation.INSERT, "1A2_1A2")}, diffs); diffs = new List<Diff>{ new Diff(Operation.EQUAL, "The c"), new Diff(Operation.DELETE, "ow and the c"), new Diff(Operation.EQUAL, "at.")}; dmp.diff_cleanupSemantic(diffs); CollectionAssert.AreEqual(new List<Diff>{ new Diff(Operation.EQUAL, "The "), new Diff(Operation.DELETE, "cow and the "), new Diff(Operation.EQUAL, "cat.")}, diffs); } [Test] public void diff_cleanupEfficiencyTest() { diff_match_patchTest dmp = new diff_match_patchTest(); dmp.Diff_EditCost = 4; List<Diff> diffs = new List<Diff>(); dmp.diff_cleanupEfficiency(diffs); CollectionAssert.AreEqual(new List<Diff>(), diffs); diffs = new List<Diff>{ new Diff(Operation.DELETE, "ab"), new Diff(Operation.INSERT, "12"), new Diff(Operation.EQUAL, "wxyz"), new Diff(Operation.DELETE, "cd"), new Diff(Operation.INSERT, "34")}; dmp.diff_cleanupEfficiency(diffs); CollectionAssert.AreEqual(new List<Diff>{ new Diff(Operation.DELETE, "ab"), new Diff(Operation.INSERT, "12"), new Diff(Operation.EQUAL, "wxyz"), new Diff(Operation.DELETE, "cd"), new Diff(Operation.INSERT, "34")}, diffs); diffs = new List<Diff>{ new Diff(Operation.DELETE, "ab"), new Diff(Operation.INSERT, "12"), new Diff(Operation.EQUAL, "xyz"), new Diff(Operation.DELETE, "cd"), new Diff(Operation.INSERT, "34")}; dmp.diff_cleanupEfficiency(diffs); CollectionAssert.AreEqual(new List<Diff>{ new Diff(Operation.DELETE, "abxyzcd"), new Diff(Operation.INSERT, "12xyz34")}, diffs); diffs = new List<Diff>{ new Diff(Operation.INSERT, "12"), new Diff(Operation.EQUAL, "x"), new Diff(Operation.DELETE, "cd"), new Diff(Operation.INSERT, "34")}; dmp.diff_cleanupEfficiency(diffs); CollectionAssert.AreEqual(new List<Diff>{ new Diff(Operation.DELETE, "xcd"), new Diff(Operation.INSERT, "12x34")}, diffs); diffs = new List<Diff>{ new Diff(Operation.DELETE, "ab"), new Diff(Operation.INSERT, "12"), new Diff(Operation.EQUAL, "xy"), new Diff(Operation.INSERT, "34"), new Diff(Operation.EQUAL, "z"), new Diff(Operation.DELETE, "cd"), new Diff(Operation.INSERT, "56")}; dmp.diff_cleanupEfficiency(diffs); CollectionAssert.AreEqual(new List<Diff>{ new Diff(Operation.DELETE, "abxyzcd"), new Diff(Operation.INSERT, "12xy34z56")}, diffs); dmp.Diff_EditCost = 5; diffs = new List<Diff>{ new Diff(Operation.DELETE, "ab"), new Diff(Operation.INSERT, "12"), new Diff(Operation.EQUAL, "wxyz"), new Diff(Operation.DELETE, "cd"), new Diff(Operation.INSERT, "34")}; dmp.diff_cleanupEfficiency(diffs); CollectionAssert.AreEqual(new List<Diff>{ new Diff(Operation.DELETE, "abwxyzcd"), new Diff(Operation.INSERT, "12wxyz34")}, diffs); dmp.Diff_EditCost = 4; } [Test] public void diff_prettyHtmlTest() { diff_match_patchTest dmp = new diff_match_patchTest(); // Pretty print. List<Diff> diffs = new List<Diff>{ new Diff(Operation.EQUAL, "a\n"), new Diff(Operation.DELETE, "<B>b</B>"), new Diff(Operation.INSERT, "c&d")}; Assert.AreEqual("<SPAN TITLE=\"i=0\">a&para;<BR></SPAN><DEL STYLE=\"background:#FFE6E6;\" TITLE=\"i=2\">&lt;B&gt;b&lt;/B&gt;</DEL><INS STYLE=\"background:#E6FFE6;\" TITLE=\"i=2\">c&amp;d</INS>", dmp.diff_prettyHtml(diffs)); } [Test] public void diff_textTest() { diff_match_patchTest dmp = new diff_match_patchTest(); List<Diff> diffs = new List<Diff> { new Diff(Operation.EQUAL, "jump"), new Diff(Operation.DELETE, "s"), new Diff(Operation.INSERT, "ed"), new Diff(Operation.EQUAL, " over "), new Diff(Operation.DELETE, "the"), new Diff(Operation.INSERT, "a"), new Diff(Operation.EQUAL, " lazy") }; Assert.AreEqual("jumps over the lazy", dmp.diff_text1(diffs)); Assert.AreEqual("jumped over a lazy", dmp.diff_text2(diffs)); } [Test, Ignore("It does not work without System.Web... Or so it seems")] public void diff_deltaTest() { diff_match_patchTest dmp = new diff_match_patchTest(); // Convert a diff into delta string. List<Diff> diffs = new List<Diff> { new Diff(Operation.EQUAL, "jump"), new Diff(Operation.DELETE, "s"), new Diff(Operation.INSERT, "ed"), new Diff(Operation.EQUAL, " over "), new Diff(Operation.DELETE, "the"), new Diff(Operation.INSERT, "a"), new Diff(Operation.EQUAL, " lazy"), new Diff(Operation.INSERT, "old dog")}; string text1 = dmp.diff_text1(diffs); Assert.AreEqual("jumps over the lazy", text1); string delta = dmp.diff_toDelta(diffs); Assert.AreEqual("=4\t-1\t+ed\t=6\t-3\t+a\t=5\t+old dog", delta); // Convert delta string into a diff. CollectionAssert.AreEqual(diffs, dmp.diff_fromDelta(text1, delta)); // Generates error (19 < 20). try { dmp.diff_fromDelta(text1 + "x", delta); Assert.Fail("diff_fromDelta: Too long."); } catch (ArgumentException) { // Exception expected. } // Generates error (19 > 18). try { dmp.diff_fromDelta(text1.Substring(1), delta); Assert.Fail("diff_fromDelta: Too short."); } catch (ArgumentException) { // Exception expected. } // Generates error (%c3%xy invalid Unicode). try { dmp.diff_fromDelta("", "+%c3%xy"); Assert.Fail("diff_fromDelta: Invalid character."); } catch (ArgumentException) { // Exception expected. } // Test deltas with special characters. char zero = (char) 0; char one = (char) 1; char two = (char) 2; diffs = new List<Diff> { new Diff(Operation.EQUAL, "\u0680 " + zero + " \t %"), new Diff(Operation.DELETE, "\u0681 " + one + " \n ^"), new Diff(Operation.INSERT, "\u0682 " + two + " \\ |")}; text1 = dmp.diff_text1(diffs); Assert.AreEqual("\u0680 " + zero + " \t %\u0681 " + one + " \n ^", text1); delta = dmp.diff_toDelta(diffs); // Lowercase, due to UrlEncode uses lower. Assert.AreEqual("=7\t-7\t+%da%82 %02 %5c %7c", delta, "diff_toDelta: Unicode."); CollectionAssert.AreEqual(diffs, dmp.diff_fromDelta(text1, delta), "diff_fromDelta: Unicode."); // Verify pool of unchanged characters. diffs = new List<Diff> { new Diff(Operation.INSERT, "A-Z a-z 0-9 - _ . ! ~ * ' ( ) ; / ? : @ & = + $ , # ")}; string text2 = dmp.diff_text2(diffs); Assert.AreEqual("A-Z a-z 0-9 - _ . ! ~ * \' ( ) ; / ? : @ & = + $ , # ", text2, "diff_text2: Unchanged characters."); delta = dmp.diff_toDelta(diffs); Assert.AreEqual("+A-Z a-z 0-9 - _ . ! ~ * \' ( ) ; / ? : @ & = + $ , # ", delta, "diff_toDelta: Unchanged characters."); // Convert delta string into a diff. CollectionAssert.AreEqual(diffs, dmp.diff_fromDelta("", delta), "diff_fromDelta: Unchanged characters."); } [Test] public void diff_xIndexTest() { diff_match_patchTest dmp = new diff_match_patchTest(); // Translate a location in text1 to text2. List<Diff> diffs = new List<Diff> { new Diff(Operation.DELETE, "a"), new Diff(Operation.INSERT, "1234"), new Diff(Operation.EQUAL, "xyz")}; Assert.AreEqual(5, dmp.diff_xIndex(diffs, 2), "diff_xIndex: Translation on equality."); diffs = new List<Diff> { new Diff(Operation.EQUAL, "a"), new Diff(Operation.DELETE, "1234"), new Diff(Operation.EQUAL, "xyz")}; Assert.AreEqual(1, dmp.diff_xIndex(diffs, 3), "diff_xIndex: Translation on deletion."); } [Test] public void diff_levenshteinTest() { diff_match_patchTest dmp = new diff_match_patchTest(); List<Diff> diffs = new List<Diff> { new Diff(Operation.DELETE, "abc"), new Diff(Operation.INSERT, "1234"), new Diff(Operation.EQUAL, "xyz")}; Assert.AreEqual(4, dmp.diff_levenshtein(diffs), "diff_levenshtein: Levenshtein with trailing equality."); diffs = new List<Diff> { new Diff(Operation.EQUAL, "xyz"), new Diff(Operation.DELETE, "abc"), new Diff(Operation.INSERT, "1234")}; Assert.AreEqual(4, dmp.diff_levenshtein(diffs), "diff_levenshtein: Levenshtein with leading equality."); diffs = new List<Diff> { new Diff(Operation.DELETE, "abc"), new Diff(Operation.EQUAL, "xyz"), new Diff(Operation.INSERT, "1234")}; Assert.AreEqual(7, dmp.diff_levenshtein(diffs), "diff_levenshtein: Levenshtein with middle equality."); } [Test] public void diff_pathTest() { diff_match_patchTest dmp = new diff_match_patchTest(); // First, check footprints are different. Assert.IsTrue(dmp.diff_footprint(1, 10) != dmp.diff_footprint(10, 1), "diff_footprint:"); // Single letters. Trace a path from back to front. List<HashSet<long>> v_map; HashSet<long> row_set; v_map = new List<HashSet<long>>(); { row_set = new HashSet<long>(); row_set.Add(dmp.diff_footprint(0, 0)); v_map.Add(row_set); row_set = new HashSet<long>(); row_set.Add(dmp.diff_footprint(0, 1)); row_set.Add(dmp.diff_footprint(1, 0)); v_map.Add(row_set); row_set = new HashSet<long>(); row_set.Add(dmp.diff_footprint(0, 2)); row_set.Add(dmp.diff_footprint(2, 0)); row_set.Add(dmp.diff_footprint(2, 2)); v_map.Add(row_set); row_set = new HashSet<long>(); row_set.Add(dmp.diff_footprint(0, 3)); row_set.Add(dmp.diff_footprint(2, 3)); row_set.Add(dmp.diff_footprint(3, 0)); row_set.Add(dmp.diff_footprint(4, 3)); v_map.Add(row_set); row_set = new HashSet<long>(); row_set.Add(dmp.diff_footprint(0, 4)); row_set.Add(dmp.diff_footprint(2, 4)); row_set.Add(dmp.diff_footprint(4, 0)); row_set.Add(dmp.diff_footprint(4, 4)); row_set.Add(dmp.diff_footprint(5, 3)); v_map.Add(row_set); row_set = new HashSet<long>(); row_set.Add(dmp.diff_footprint(0, 5)); row_set.Add(dmp.diff_footprint(2, 5)); row_set.Add(dmp.diff_footprint(4, 5)); row_set.Add(dmp.diff_footprint(5, 0)); row_set.Add(dmp.diff_footprint(6, 3)); row_set.Add(dmp.diff_footprint(6, 5)); v_map.Add(row_set); row_set = new HashSet<long>(); row_set.Add(dmp.diff_footprint(0, 6)); row_set.Add(dmp.diff_footprint(2, 6)); row_set.Add(dmp.diff_footprint(4, 6)); row_set.Add(dmp.diff_footprint(6, 6)); row_set.Add(dmp.diff_footprint(7, 5)); v_map.Add(row_set); } List<Diff> diffs = new List<Diff>{ new Diff(Operation.INSERT, "W"), new Diff(Operation.DELETE, "A"), new Diff(Operation.EQUAL, "1"), new Diff(Operation.DELETE, "B"), new Diff(Operation.EQUAL, "2"), new Diff(Operation.INSERT, "X"), new Diff(Operation.DELETE, "C"), new Diff(Operation.EQUAL, "3"), new Diff(Operation.DELETE, "D")}; CollectionAssert.AreEqual(diffs, dmp.diff_path1(v_map, "A1B2C3D", "W12X3"), "diff_path1: Single letters."); // Trace a path from front to back. v_map.RemoveAt(v_map.Count - 1); diffs = new List<Diff>{ new Diff(Operation.EQUAL, "4"), new Diff(Operation.DELETE, "E"), new Diff(Operation.INSERT, "Y"), new Diff(Operation.EQUAL, "5"), new Diff(Operation.DELETE, "F"), new Diff(Operation.EQUAL, "6"), new Diff(Operation.DELETE, "G"), new Diff(Operation.INSERT, "Z")}; CollectionAssert.AreEqual(diffs, dmp.diff_path2(v_map, "4E5F6G", "4Y56Z"), "diff_path2: Single letters."); // Double letters. Trace a path from back to front. v_map = new List<HashSet<long>>(); { row_set = new HashSet<long>(); row_set.Add(dmp.diff_footprint(0, 0)); v_map.Add(row_set); row_set = new HashSet<long>(); row_set.Add(dmp.diff_footprint(0, 1)); row_set.Add(dmp.diff_footprint(1, 0)); v_map.Add(row_set); row_set = new HashSet<long>(); row_set.Add(dmp.diff_footprint(0, 2)); row_set.Add(dmp.diff_footprint(1, 1)); row_set.Add(dmp.diff_footprint(2, 0)); v_map.Add(row_set); row_set = new HashSet<long>(); row_set.Add(dmp.diff_footprint(0, 3)); row_set.Add(dmp.diff_footprint(1, 2)); row_set.Add(dmp.diff_footprint(2, 1)); row_set.Add(dmp.diff_footprint(3, 0)); v_map.Add(row_set); row_set = new HashSet<long>(); row_set.Add(dmp.diff_footprint(0, 4)); row_set.Add(dmp.diff_footprint(1, 3)); row_set.Add(dmp.diff_footprint(3, 1)); row_set.Add(dmp.diff_footprint(4, 0)); row_set.Add(dmp.diff_footprint(4, 4)); v_map.Add(row_set); } diffs = new List<Diff>{ new Diff(Operation.INSERT, "WX"), new Diff(Operation.DELETE, "AB"), new Diff(Operation.EQUAL, "12")}; CollectionAssert.AreEqual(diffs, dmp.diff_path1(v_map, "AB12", "WX12"), "diff_path1: Double letters."); // Trace a path from front to back. v_map = new List<HashSet<long>>(); { row_set = new HashSet<long>(); row_set.Add(dmp.diff_footprint(0, 0)); v_map.Add(row_set); row_set = new HashSet<long>(); row_set.Add(dmp.diff_footprint(0, 1)); row_set.Add(dmp.diff_footprint(1, 0)); v_map.Add(row_set); row_set = new HashSet<long>(); row_set.Add(dmp.diff_footprint(1, 1)); row_set.Add(dmp.diff_footprint(2, 0)); row_set.Add(dmp.diff_footprint(2, 4)); v_map.Add(row_set); row_set = new HashSet<long>(); row_set.Add(dmp.diff_footprint(2, 1)); row_set.Add(dmp.diff_footprint(2, 5)); row_set.Add(dmp.diff_footprint(3, 0)); row_set.Add(dmp.diff_footprint(3, 4)); v_map.Add(row_set); row_set = new HashSet<long>(); row_set.Add(dmp.diff_footprint(2, 6)); row_set.Add(dmp.diff_footprint(3, 5)); row_set.Add(dmp.diff_footprint(4, 4)); v_map.Add(row_set); } diffs = new List<Diff>{ new Diff(Operation.DELETE, "CD"), new Diff(Operation.EQUAL, "34"), new Diff(Operation.INSERT, "YZ")}; CollectionAssert.AreEqual(diffs, dmp.diff_path2(v_map, "CD34", "34YZ"), "diff_path2: Double letters."); } [Test] public void diff_mainTest() { diff_match_patchTest dmp = new diff_match_patchTest(); // Perform a trivial diff. List<Diff> diffs = new List<Diff> { new Diff(Operation.EQUAL, "abc") }; CollectionAssert.AreEqual(diffs, dmp.diff_main("abc", "abc", false), "diff_main: Null case."); diffs = new List<Diff> { new Diff(Operation.EQUAL, "ab"), new Diff(Operation.INSERT, "123"), new Diff(Operation.EQUAL, "c") }; CollectionAssert.AreEqual(diffs, dmp.diff_main("abc", "ab123c", false), "diff_main: Simple insertion."); diffs = new List<Diff> { new Diff(Operation.EQUAL, "a"), new Diff(Operation.DELETE, "123"), new Diff(Operation.EQUAL, "bc") }; CollectionAssert.AreEqual(diffs, dmp.diff_main("a123bc", "abc", false), "diff_main: Simple deletion."); diffs = new List<Diff> { new Diff(Operation.EQUAL, "a"), new Diff(Operation.INSERT, "123"), new Diff(Operation.EQUAL, "b"), new Diff(Operation.INSERT, "456"), new Diff(Operation.EQUAL, "c") }; CollectionAssert.AreEqual(diffs, dmp.diff_main("abc", "a123b456c", false), "diff_main: Two insertions."); diffs = new List<Diff> { new Diff(Operation.EQUAL, "a"), new Diff(Operation.DELETE, "123"), new Diff(Operation.EQUAL, "b"), new Diff(Operation.DELETE, "456"), new Diff(Operation.EQUAL, "c") }; CollectionAssert.AreEqual(diffs, dmp.diff_main("a123b456c", "abc", false), "diff_main: Two deletions."); // Perform a real diff. Switch off the timeout. dmp.Diff_Timeout = 0; dmp.Diff_DualThreshold = 32; diffs = new List<Diff> { new Diff(Operation.DELETE, "a"), new Diff(Operation.INSERT, "b") }; CollectionAssert.AreEqual(diffs, dmp.diff_main("a", "b", false), "diff_main: Simple case #1."); diffs = new List<Diff> { new Diff(Operation.DELETE, "Apple"), new Diff(Operation.INSERT, "Banana"), new Diff(Operation.EQUAL, "s are a"), new Diff(Operation.INSERT, "lso"), new Diff(Operation.EQUAL, " fruit.") }; CollectionAssert.AreEqual(diffs, dmp.diff_main("Apples are a fruit.", "Bananas are also fruit.", false), "diff_main: Simple case #2."); diffs = new List<Diff> { new Diff(Operation.DELETE, "a"), new Diff(Operation.INSERT, "\u0680"), new Diff(Operation.EQUAL, "x"), new Diff(Operation.DELETE, "\t"), new Diff(Operation.INSERT, new string(new char[] { (char) 0 })) }; CollectionAssert.AreEqual(diffs, dmp.diff_main("ax\t", "\u0680x" + (char) 0, false), "diff_main: Simple case #3."); diffs = new List<Diff> { new Diff(Operation.DELETE, "1"), new Diff(Operation.EQUAL, "a"), new Diff(Operation.DELETE, "y"), new Diff(Operation.EQUAL, "b"), new Diff(Operation.DELETE, "2"), new Diff(Operation.INSERT, "xab") }; CollectionAssert.AreEqual(diffs, dmp.diff_main("1ayb2", "abxab", false), "diff_main: Overlap #1."); diffs = new List<Diff> { new Diff(Operation.INSERT, "xaxcx"), new Diff(Operation.EQUAL, "abc"), new Diff(Operation.DELETE, "y") }; CollectionAssert.AreEqual(diffs, dmp.diff_main("abcy", "xaxcxabc", false), "diff_main: Overlap #2."); // Sub-optimal double-ended diff. dmp.Diff_DualThreshold = 2; diffs = new List<Diff> { new Diff(Operation.INSERT, "x"), new Diff(Operation.EQUAL, "a"), new Diff(Operation.DELETE, "b"), new Diff(Operation.INSERT, "x"), new Diff(Operation.EQUAL, "c"), new Diff(Operation.DELETE, "y"), new Diff(Operation.INSERT, "xabc") }; CollectionAssert.AreEqual(diffs, dmp.diff_main("abcy", "xaxcxabc", false), "diff_main: Overlap #3."); dmp.Diff_DualThreshold = 32; dmp.Diff_Timeout = 0.001f; // 1ms string a = "`Twas brillig, and the slithy toves\nDid gyre and gimble in the wabe:\nAll mimsy were the borogoves,\nAnd the mome raths outgrabe.\n"; string b = "I am the very model of a modern major general,\nI've information vegetable, animal, and mineral,\nI know the kings of England, and I quote the fights historical,\nFrom Marathon to Waterloo, in order categorical.\n"; // Increase the text lengths by 1024 times to ensure a timeout. for (int x = 0; x < 10; x++) { a = a + a; b = b + b; } Assert.IsNull(dmp.diff_map(a, b), "diff_main: Timeout."); dmp.Diff_Timeout = 0; // Test the linemode speedup. Must be long to pass the 200 char cutoff. a = "1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n"; b = "abcdefghij\nabcdefghij\nabcdefghij\nabcdefghij\nabcdefghij\nabcdefghij\nabcdefghij\nabcdefghij\nabcdefghij\nabcdefghij\nabcdefghij\nabcdefghij\nabcdefghij\n"; CollectionAssert.AreEqual(dmp.diff_main(a, b, true), dmp.diff_main(a, b, false), "diff_main: Simple."); a = "1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n1234567890\n"; b = "abcdefghij\n1234567890\n1234567890\n1234567890\nabcdefghij\n1234567890\n1234567890\n1234567890\nabcdefghij\n1234567890\n1234567890\n1234567890\nabcdefghij\n"; string[] texts_linemode = diff_rebuildtexts(dmp.diff_main(a, b, true)); string[] texts_textmode = diff_rebuildtexts(dmp.diff_main(a, b, false)); CollectionAssert.AreEqual(texts_textmode, texts_linemode, "diff_main: Overlap."); } [Test] public void match_alphabetTest() { diff_match_patchTest dmp = new diff_match_patchTest(); // Initialise the bitmasks for Bitap. Dictionary<char, int> bitmask = new Dictionary<char, int>(); bitmask.Add('a', 4); bitmask.Add('b', 2); bitmask.Add('c', 1); CollectionAssert.AreEqual(bitmask, dmp.match_alphabet("abc"), "match_alphabet: Unique."); bitmask.Clear(); bitmask.Add('a', 37); bitmask.Add('b', 18); bitmask.Add('c', 8); CollectionAssert.AreEqual(bitmask, dmp.match_alphabet("abcaba"), "match_alphabet: Duplicates."); } [Test] public void match_bitapTest() { diff_match_patchTest dmp = new diff_match_patchTest(); // Bitap algorithm. dmp.Match_Distance = 100; dmp.Match_Threshold = 0.5f; Assert.AreEqual(5, dmp.match_bitap("abcdefghijk", "fgh", 5), "match_bitap: Exact match #1."); Assert.AreEqual(5, dmp.match_bitap("abcdefghijk", "fgh", 0), "match_bitap: Exact match #2."); Assert.AreEqual(4, dmp.match_bitap("abcdefghijk", "efxhi", 0), "match_bitap: Fuzzy match #1."); Assert.AreEqual(2, dmp.match_bitap("abcdefghijk", "cdefxyhijk", 5), "match_bitap: Fuzzy match #2."); Assert.AreEqual(-1, dmp.match_bitap("abcdefghijk", "bxy", 1), "match_bitap: Fuzzy match #3."); Assert.AreEqual(2, dmp.match_bitap("123456789xx0", "3456789x0", 2), "match_bitap: Overflow."); Assert.AreEqual(0, dmp.match_bitap("abcdef", "xxabc", 4), "match_bitap: Before start match."); Assert.AreEqual(3, dmp.match_bitap("abcdef", "defyy", 4), "match_bitap: Beyond end match."); Assert.AreEqual(0, dmp.match_bitap("abcdef", "xabcdefy", 0), "match_bitap: Oversized pattern."); dmp.Match_Threshold = 0.4f; Assert.AreEqual(4, dmp.match_bitap("abcdefghijk", "efxyhi", 1), "match_bitap: Threshold #1."); dmp.Match_Threshold = 0.3f; Assert.AreEqual(-1, dmp.match_bitap("abcdefghijk", "efxyhi", 1), "match_bitap: Threshold #2."); dmp.Match_Threshold = 0.0f; Assert.AreEqual(1, dmp.match_bitap("abcdefghijk", "bcdef", 1), "match_bitap: Threshold #3."); dmp.Match_Threshold = 0.5f; Assert.AreEqual(0, dmp.match_bitap("abcdexyzabcde", "abccde", 3), "match_bitap: Multiple select #1."); Assert.AreEqual(8, dmp.match_bitap("abcdexyzabcde", "abccde", 5), "match_bitap: Multiple select #2."); dmp.Match_Distance = 10; // Strict location. Assert.AreEqual(-1, dmp.match_bitap("abcdefghijklmnopqrstuvwxyz", "abcdefg", 24), "match_bitap: Distance test #1."); Assert.AreEqual(0, dmp.match_bitap("abcdefghijklmnopqrstuvwxyz", "abcdxxefg", 1), "match_bitap: Distance test #2."); dmp.Match_Distance = 1000; // Loose location. Assert.AreEqual(0, dmp.match_bitap("abcdefghijklmnopqrstuvwxyz", "abcdefg", 24), "match_bitap: Distance test #3."); } [Test] public void match_mainTest() { diff_match_patchTest dmp = new diff_match_patchTest(); // Full match. Assert.AreEqual(0, dmp.match_main("abcdef", "abcdef", 1000), "match_main: Equality."); Assert.AreEqual(-1, dmp.match_main("", "abcdef", 1), "match_main: Null text."); Assert.AreEqual(3, dmp.match_main("abcdef", "", 3), "match_main: Null pattern."); Assert.AreEqual(3, dmp.match_main("abcdef", "de", 3), "match_main: Exact match."); Assert.AreEqual(3, dmp.match_main("abcdef", "defy", 4), "match_main: Beyond end match."); Assert.AreEqual(0, dmp.match_main("abcdef", "abcdefy", 0), "match_main: Oversized pattern."); dmp.Match_Threshold = 0.7f; Assert.AreEqual(4, dmp.match_main("I am the very model of a modern major general.", " that berry ", 5), "match_main: Complex match."); dmp.Match_Threshold = 0.5f; } [Test] public void patch_patchObjTest() { // Patch Object. Patch p = new Patch(); p.start1 = 20; p.start2 = 21; p.length1 = 18; p.length2 = 17; p.diffs = new List<Diff> { new Diff(Operation.EQUAL, "jump"), new Diff(Operation.DELETE, "s"), new Diff(Operation.INSERT, "ed"), new Diff(Operation.EQUAL, " over "), new Diff(Operation.DELETE, "the"), new Diff(Operation.INSERT, "a"), new Diff(Operation.EQUAL, "\nlaz")}; string strp = "@@ -21,18 +22,17 @@\n jump\n-s\n+ed\n over \n-the\n+a\n %0alaz\n"; Assert.AreEqual(strp, p.ToString(), "Patch: toString."); } [Test] public void patch_fromTextTest() { diff_match_patchTest dmp = new diff_match_patchTest(); Assert.IsTrue(dmp.patch_fromText("").Count == 0, "patch_fromText: #0."); string strp = "@@ -21,18 +22,17 @@\n jump\n-s\n+ed\n over \n-the\n+a\n %0alaz\n"; Assert.AreEqual(strp, dmp.patch_fromText(strp)[0].ToString(), "patch_fromText: #1."); Assert.AreEqual("@@ -1 +1 @@\n-a\n+b\n", dmp.patch_fromText("@@ -1 +1 @@\n-a\n+b\n")[0].ToString(), "patch_fromText: #2."); Assert.AreEqual("@@ -1,3 +0,0 @@\n-abc\n", dmp.patch_fromText("@@ -1,3 +0,0 @@\n-abc\n")[0].ToString(), "patch_fromText: #3."); Assert.AreEqual("@@ -0,0 +1,3 @@\n+abc\n", dmp.patch_fromText("@@ -0,0 +1,3 @@\n+abc\n")[0].ToString(), "patch_fromText: #4."); // Generates error. try { dmp.patch_fromText("Bad\nPatch\n"); Assert.Fail("patch_fromText: #5."); } catch (ArgumentException) { // Exception expected. } } [Test] public void patch_toTextTest() { diff_match_patchTest dmp = new diff_match_patchTest(); string strp = "@@ -21,18 +22,17 @@\n jump\n-s\n+ed\n over \n-the\n+a\n laz\n"; List<Patch> patches; patches = dmp.patch_fromText(strp); string result = dmp.patch_toText(patches); Assert.AreEqual(strp, result); strp = "@@ -1,9 +1,9 @@\n-f\n+F\n oo+fooba\n@@ -7,9 +7,9 @@\n obar\n-,\n+.\n tes\n"; patches = dmp.patch_fromText(strp); result = dmp.patch_toText(patches); Assert.AreEqual(strp, result); } [Test] public void patch_addContextTest() { diff_match_patchTest dmp = new diff_match_patchTest(); dmp.Patch_Margin = 4; Patch p; p = dmp.patch_fromText("@@ -21,4 +21,10 @@\n-jump\n+somersault\n")[0]; dmp.patch_addContext(p, "The quick brown fox jumps over the lazy dog."); Assert.AreEqual("@@ -17,12 +17,18 @@\n fox \n-jump\n+somersault\n s ov\n", p.ToString(), "patch_addContext: Simple case."); p = dmp.patch_fromText("@@ -21,4 +21,10 @@\n-jump\n+somersault\n")[0]; dmp.patch_addContext(p, "The quick brown fox jumps."); Assert.AreEqual("@@ -17,10 +17,16 @@\n fox \n-jump\n+somersault\n s.\n", p.ToString(), "patch_addContext: Not enough trailing context."); p = dmp.patch_fromText("@@ -3 +3,2 @@\n-e\n+at\n")[0]; dmp.patch_addContext(p, "The quick brown fox jumps."); Assert.AreEqual("@@ -1,7 +1,8 @@\n Th\n-e\n+at\n qui\n", p.ToString(), "patch_addContext: Not enough leading context."); p = dmp.patch_fromText("@@ -3 +3,2 @@\n-e\n+at\n")[0]; dmp.patch_addContext(p, "The quick brown fox jumps. The quick brown fox crashes."); Assert.AreEqual("@@ -1,27 +1,28 @@\n Th\n-e\n+at\n quick brown fox jumps. \n", p.ToString(), "patch_addContext: Ambiguity."); } [Test] public void patch_makeTest() { diff_match_patchTest dmp = new diff_match_patchTest(); List<Patch> patches; string text1 = "The quick brown fox jumps over the lazy dog."; string text2 = "That quick brown fox jumped over a lazy dog."; string expectedPatch = "@@ -1,8 +1,7 @@\n Th\n-at\n+e\n qui\n@@ -21,17 +21,18 @@\n jump\n-ed\n+s\n over \n-a\n+the\n laz\n"; // The second patch must be "-21,17 +21,18", not "-22,17 +21,18" due to rolling context. patches = dmp.patch_make(text2, text1); Assert.AreEqual(expectedPatch, dmp.patch_toText(patches), "patch_make: Text2+Text1 inputs."); expectedPatch = "@@ -1,11 +1,12 @@\n Th\n-e\n+at\n quick b\n@@ -22,18 +22,17 @@\n jump\n-s\n+ed\n over \n-the\n+a\n laz\n"; patches = dmp.patch_make(text1, text2); Assert.AreEqual(expectedPatch, dmp.patch_toText(patches), "patch_make: Text1+Text2 inputs."); List<Diff> diffs = dmp.diff_main(text1, text2, false); patches = dmp.patch_make(diffs); Assert.AreEqual(expectedPatch, dmp.patch_toText(patches), "patch_make: Diff input."); patches = dmp.patch_make(text1, diffs); Assert.AreEqual(expectedPatch, dmp.patch_toText(patches), "patch_make: Text1+Diff inputs."); patches = dmp.patch_make(text1, text2, diffs); Assert.AreEqual(expectedPatch, dmp.patch_toText(patches), "patch_make: Text1+Text2+Diff inputs (deprecated)."); patches = dmp.patch_make("`1234567890-=[]\\;',./", "~!@#$%^&*()_+{}|:\"<>?"); Assert.AreEqual("@@ -1,21 +1,21 @@\n-%601234567890-=%5b%5d%5c;',./\n+~!@#$%25%5e&*()_+%7b%7d%7c:%22%3c%3e?\n", dmp.patch_toText(patches), "patch_toText: Character encoding."); diffs = new List<Diff>{ new Diff(Operation.DELETE, "`1234567890-=[]\\;',./"), new Diff(Operation.INSERT, "~!@#$%^&*()_+{}|:\"<>?")}; CollectionAssert.AreEqual(diffs, dmp.patch_fromText("@@ -1,21 +1,21 @@\n-%601234567890-=%5B%5D%5C;',./\n+~!@#$%25%5E&*()_+%7B%7D%7C:%22%3C%3E?\n")[0].diffs, "patch_fromText: Character decoding."); text1 = ""; for (int x = 0; x < 100; x++) { text1 += "abcdef"; } text2 = text1 + "123"; expectedPatch = "@@ -573,28 +573,31 @@\n cdefabcdefabcdefabcdefabcdef\n+123\n"; patches = dmp.patch_make(text1, text2); Assert.AreEqual(expectedPatch, dmp.patch_toText(patches), "patch_make: Long string with repeats."); } [Test] public void patch_splitMaxTest() { // Assumes that Match_MaxBits is 32. diff_match_patchTest dmp = new diff_match_patchTest(); List<Patch> patches; patches = dmp.patch_make("abcdefghijklmnopqrstuvwxyz01234567890", "XabXcdXefXghXijXklXmnXopXqrXstXuvXwxXyzX01X23X45X67X89X0"); dmp.patch_splitMax(patches); Assert.AreEqual("@@ -1,32 +1,46 @@\n+X\n ab\n+X\n cd\n+X\n ef\n+X\n gh\n+X\n ij\n+X\n kl\n+X\n mn\n+X\n op\n+X\n qr\n+X\n st\n+X\n uv\n+X\n wx\n+X\n yz\n+X\n 012345\n@@ -25,13 +39,18 @@\n zX01\n+X\n 23\n+X\n 45\n+X\n 67\n+X\n 89\n+X\n 0\n", dmp.patch_toText(patches)); patches = dmp.patch_make("abcdef1234567890123456789012345678901234567890123456789012345678901234567890uvwxyz", "abcdefuvwxyz"); string oldToText = dmp.patch_toText(patches); dmp.patch_splitMax(patches); Assert.AreEqual(oldToText, dmp.patch_toText(patches)); patches = dmp.patch_make("1234567890123456789012345678901234567890123456789012345678901234567890", "abc"); dmp.patch_splitMax(patches); Assert.AreEqual("@@ -1,32 +1,4 @@\n-1234567890123456789012345678\n 9012\n@@ -29,32 +1,4 @@\n-9012345678901234567890123456\n 7890\n@@ -57,14 +1,3 @@\n-78901234567890\n+abc\n", dmp.patch_toText(patches)); patches = dmp.patch_make("abcdefghij , h : 0 , t : 1 abcdefghij , h : 0 , t : 1 abcdefghij , h : 0 , t : 1", "abcdefghij , h : 1 , t : 1 abcdefghij , h : 1 , t : 1 abcdefghij , h : 0 , t : 1"); dmp.patch_splitMax(patches); Assert.AreEqual("@@ -2,32 +2,32 @@\n bcdefghij , h : \n-0\n+1\n , t : 1 abcdef\n@@ -29,32 +29,32 @@\n bcdefghij , h : \n-0\n+1\n , t : 1 abcdef\n", dmp.patch_toText(patches)); } [Test] public void patch_addPaddingTest() { diff_match_patchTest dmp = new diff_match_patchTest(); List<Patch> patches; patches = dmp.patch_make("", "test"); Assert.AreEqual("@@ -0,0 +1,4 @@\n+test\n", dmp.patch_toText(patches), "patch_addPadding: Both edges full."); dmp.patch_addPadding(patches); Assert.AreEqual("@@ -1,8 +1,12 @@\n %01%02%03%04\n+test\n %01%02%03%04\n", dmp.patch_toText(patches), "patch_addPadding: Both edges full."); patches = dmp.patch_make("XY", "XtestY"); Assert.AreEqual("@@ -1,2 +1,6 @@\n X\n+test\n Y\n", dmp.patch_toText(patches), "patch_addPadding: Both edges partial."); dmp.patch_addPadding(patches); Assert.AreEqual("@@ -2,8 +2,12 @@\n %02%03%04X\n+test\n Y%01%02%03\n", dmp.patch_toText(patches), "patch_addPadding: Both edges partial."); patches = dmp.patch_make("XXXXYYYY", "XXXXtestYYYY"); Assert.AreEqual("@@ -1,8 +1,12 @@\n XXXX\n+test\n YYYY\n", dmp.patch_toText(patches), "patch_addPadding: Both edges none."); dmp.patch_addPadding(patches); Assert.AreEqual("@@ -5,8 +5,12 @@\n XXXX\n+test\n YYYY\n", dmp.patch_toText(patches), "patch_addPadding: Both edges none."); } [Test] public void patch_applyTest() { diff_match_patchTest dmp = new diff_match_patchTest(); dmp.Match_Distance = 1000; dmp.Match_Threshold = 0.5f; dmp.Patch_DeleteThreshold = 0.5f; List<Patch> patches; patches = dmp.patch_make("The quick brown fox jumps over the lazy dog.", "That quick brown fox jumped over a lazy dog."); Object[] results = dmp.patch_apply(patches, "The quick brown fox jumps over the lazy dog."); bool[] boolArray = (bool[]) results[1]; string resultStr = results[0] + "\t" + boolArray[0] + "\t" + boolArray[1]; Assert.AreEqual("That quick brown fox jumped over a lazy dog.\tTrue\tTrue", resultStr, "patch_apply: Exact match."); results = dmp.patch_apply(patches, "The quick red rabbit jumps over the tired tiger."); boolArray = (bool[]) results[1]; resultStr = results[0] + "\t" + boolArray[0] + "\t" + boolArray[1]; Assert.AreEqual("That quick red rabbit jumped over a tired tiger.\tTrue\tTrue", resultStr, "patch_apply: Partial match."); results = dmp.patch_apply(patches, "I am the very model of a modern major general."); boolArray = (bool[]) results[1]; resultStr = results[0] + "\t" + boolArray[0] + "\t" + boolArray[1]; Assert.AreEqual("I am the very model of a modern major general.\tFalse\tFalse", resultStr, "patch_apply: Failed match."); patches = dmp.patch_make("x1234567890123456789012345678901234567890123456789012345678901234567890y", "xabcy"); results = dmp.patch_apply(patches, "x123456789012345678901234567890-----++++++++++-----123456789012345678901234567890y"); boolArray = (bool[]) results[1]; resultStr = results[0] + "\t" + boolArray[0] + "\t" + boolArray[1]; Assert.AreEqual("xabcy\tTrue\tTrue", resultStr, "patch_apply: Big delete, small change."); patches = dmp.patch_make("x1234567890123456789012345678901234567890123456789012345678901234567890y", "xabcy"); results = dmp.patch_apply(patches, "x12345678901234567890---------------++++++++++---------------12345678901234567890y"); boolArray = (bool[]) results[1]; resultStr = results[0] + "\t" + boolArray[0] + "\t" + boolArray[1]; Assert.AreEqual("xabc12345678901234567890---------------++++++++++---------------12345678901234567890y\tFalse\tTrue", resultStr, "patch_apply: Big delete, big change 1."); dmp.Patch_DeleteThreshold = 0.6f; patches = dmp.patch_make("x1234567890123456789012345678901234567890123456789012345678901234567890y", "xabcy"); results = dmp.patch_apply(patches, "x12345678901234567890---------------++++++++++---------------12345678901234567890y"); boolArray = (bool[]) results[1]; resultStr = results[0] + "\t" + boolArray[0] + "\t" + boolArray[1]; Assert.AreEqual("xabcy\tTrue\tTrue", resultStr, "patch_apply: Big delete, big change 2."); dmp.Patch_DeleteThreshold = 0.5f; dmp.Match_Threshold = 0.0f; dmp.Match_Distance = 0; patches = dmp.patch_make("abcdefghijklmnopqrstuvwxyz--------------------1234567890", "abcXXXXXXXXXXdefghijklmnopqrstuvwxyz--------------------1234567YYYYYYYYYY890"); results = dmp.patch_apply(patches, "ABCDEFGHIJKLMNOPQRSTUVWXYZ--------------------1234567890"); boolArray = (bool[]) results[1]; resultStr = results[0] + "\t" + boolArray[0] + "\t" + boolArray[1]; Assert.AreEqual("ABCDEFGHIJKLMNOPQRSTUVWXYZ--------------------1234567YYYYYYYYYY890\tFalse\tTrue", resultStr, "Compensate for failed patch."); dmp.Match_Threshold = 0.5f; dmp.Match_Distance = 1000; patches = dmp.patch_make("", "test"); string patchStr = dmp.patch_toText(patches); dmp.patch_apply(patches, ""); Assert.AreEqual(patchStr, dmp.patch_toText(patches), "patch_apply: No side effects."); patches = dmp.patch_make("The quick brown fox jumps over the lazy dog.", "Woof"); patchStr = dmp.patch_toText(patches); dmp.patch_apply(patches, "The quick brown fox jumps over the lazy dog."); Assert.AreEqual(patchStr, dmp.patch_toText(patches), "patch_apply: No side effects with major delete."); patches = dmp.patch_make("", "test"); results = dmp.patch_apply(patches, ""); boolArray = (bool[]) results[1]; resultStr = results[0] + "\t" + boolArray[0]; Assert.AreEqual("test\tTrue", resultStr, "patch_apply: Edge exact match."); patches = dmp.patch_make("XY", "XtestY"); results = dmp.patch_apply(patches, "XY"); boolArray = (bool[]) results[1]; resultStr = results[0] + "\t" + boolArray[0]; Assert.AreEqual("XtestY\tTrue", resultStr, "patch_apply: Near edge exact match."); patches = dmp.patch_make("y", "y123"); results = dmp.patch_apply(patches, "x"); boolArray = (bool[]) results[1]; resultStr = results[0] + "\t" + boolArray[0]; Assert.AreEqual("x123\tTrue", resultStr, "patch_apply: Edge partial match."); } private static string[] diff_rebuildtexts(List<Diff> diffs) { string[] text = { "", "" }; foreach (Diff myDiff in diffs) { if (myDiff.operation != Operation.INSERT) { text[0] += myDiff.text; } if (myDiff.operation != Operation.DELETE) { text[1] += myDiff.text; } } return text; } } }
{ "content_hash": "b7449320f2d91aec3db79f77f6e82413", "timestamp": "", "source": "github", "line_count": 1162, "max_line_length": 280, "avg_line_length": 50.561101549053355, "alnum_prop": 0.5435559640522876, "repo_name": "finsaspa/CodeServices", "id": "a401925b1eea4fb597dca2f3df92669284e3cf4c", "size": "59571", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "CodeServices.UnitTests/Common/Text/DiffMatchPatchTests.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "204" }, { "name": "C", "bytes": "11150" }, { "name": "C#", "bytes": "744557" }, { "name": "Common Lisp", "bytes": "3721" }, { "name": "F#", "bytes": "2402" }, { "name": "HTML", "bytes": "24603" }, { "name": "Liquid", "bytes": "437" }, { "name": "PowerShell", "bytes": "82248" }, { "name": "Roff", "bytes": "4227" } ], "symlink_target": "" }
package com.lightbend.lagom.sbt.scripted import java.io.BufferedReader import java.io.InputStreamReader import java.net.HttpURLConnection import com.lightbend.lagom.sbt.Internal import com.lightbend.lagom.sbt.LagomPlugin import com.lightbend.lagom.sbt.NonBlockingInteractionMode import com.lightbend.lagom.core.LagomVersion import sbt.Keys._ import sbt._ import sbt.complete.Parser import scala.concurrent.duration._ import scala.util.Try import scala.util.control.NonFatal object ScriptedTools extends AutoPlugin { private val ConnectTimeout = 10000 private val ReadTimeout = 10000 override def trigger = allRequirements override def requires = LagomPlugin object autoImport { val validateRequest = inputKey[Response]("Validate the given request") val validateFile = inputKey[File]("Validate a file") val lagomSbtScriptedLibrary = "com.lightbend.lagom" %% "lagom-sbt-scripted-library" % LagomVersion.current } import autoImport._ override def buildSettings: Seq[Setting[_]] = Seq( validateRequest := validateRequestImpl.evaluated, aggregate in validateRequest := false, validateFile := validateFileImpl.evaluated, aggregate in validateFile := false, Internal.Keys.interactionMode := NonBlockingInteractionMode, // This is copy & pasted from project/AkkaSnapshotRepositories so that scripted tests // can use Akka snapshot repositories as well. If you change it here, remember to keep // project/AkkaSnapshotRepositories in sync. resolvers ++= (sys.props.get("lagom.build.akka.version") match { case Some(_) => Seq( "akka-snapshot-repository".at("https://repo.akka.io/snapshots"), // TODO: obtain the Akka snapshots from sonatype (when available) "akka-http-snapshot-repository".at("https://dl.bintray.com/akka/snapshots/") ) case None => Seq.empty }), scalaVersion := sys.props.get("scala.version").getOrElse("2.12.13") ) private def validateRequestImpl = Def.inputTask { val log = streams.value.log val validateRequest = validateRequestParser.parsed val uri = validateRequest.uri.get val seenStackTraces = scala.collection.mutable.Set.empty[Int] def attempt(): Response = { log.info(s"Making request on $uri") val conn = uri.toURL.openConnection().asInstanceOf[HttpURLConnection] try { conn.setConnectTimeout(ConnectTimeout) conn.setReadTimeout(ReadTimeout) val status = conn.getResponseCode if (validateRequest.shouldBeDown) { throw ShouldBeDownException(status) } validateRequest.statusAssertion(status) // HttpURLConnection throws FileNotFoundException on getInputStream when the status is 404 // HttpURLConnection throws IOException on getInputStream when the status is 500 val body = Try { val br = new BufferedReader(new InputStreamReader(conn.getInputStream)) Stream.continually(br.readLine()).takeWhile(_ != null).mkString("\n") }.recover { case _ => "" }.get validateRequest.bodyAssertion(body) Response(status, body) } catch { case NonFatal(ShouldBeDownException(status)) => val msg = s"Expected server to be down but request completed with status $status." log.error(msg) sys.error(msg) case NonFatal(_) if validateRequest.shouldBeDown => Response(0, "") case NonFatal(t) => val msg = s"Failed to make a request on $uri; cause: ${t.getMessage} (${t.getClass})" if (seenStackTraces.add(t.##)) { log.error(t.getStackTrace.map(_.toString).mkString(s"$msg; stack:\n ", "\n ", "")) } else { log.error(msg) } sys.error(msg) } finally { conn.disconnect() } } if (validateRequest.retry) { repeatUntilSuccessful(log, attempt()) } else { attempt() } } private def validateFileImpl = Def.inputTask { val validateFile = validateFileParser.parsed val file = baseDirectory.value / validateFile.file.get val log = streams.value.log def attempt() = { log.info(s"Validating file $file") val contents = IO.read(file) validateFile.assertions(contents) } if (validateFile.retry) { repeatUntilSuccessful(log, attempt()) } else { attempt() } file } private def repeatUntilSuccessful[T](log: Logger, operation: => T, times: Int = 30): T = { try operation catch { case NonFatal(t) => if (times <= 1) { throw t } else { log.warn(s"Operation failed, ${times - 1} attempts left") SECONDS.sleep(1) repeatUntilSuccessful(log, operation, times - 1) } } } case class ShouldBeDownException(actualStatus: Int) extends RuntimeException case class Response(status: Int, body: String) private case class ValidateRequest( uri: Option[URI] = None, retry: Boolean = false, shouldBeDown: Boolean = false, statusAssertion: Int => Unit = _ => (), bodyAssertion: String => Unit = _ => () ) private val validateRequestParser: Parser[ValidateRequest] = { import complete.DefaultParsers._ type ApplyOption = ValidateRequest => ValidateRequest def optionArg[A](opt: String, parser: Parser[A])(applyOption: A => ApplyOption): Parser[ApplyOption] = { (literal(opt) ~> Space ~> parser).map(applyOption) } def option(opt: String)(applyOption: ApplyOption): Parser[ApplyOption] = { literal(opt).map(_ => applyOption) } def bodyAssertionOption(opt: String, description: String)( assertion: (String, String) => Boolean ): Parser[ApplyOption] = { optionArg(opt, StringBasic)(expected => v => { val oldAssertion = v.bodyAssertion v.copy(bodyAssertion = body => { // First run the existing assertion oldAssertion(body) // Now run this assertion if (!assertion(body, expected)) sys.error(s"Expected body to $description '$expected' but got '$body'") }) } ) } def statusAssertionOption(opt: String, description: String)( assertion: (Int, Int) => Boolean ): Parser[ApplyOption] = { optionArg(opt, NatBasic)(expected => v => { val oldAssertion = v.statusAssertion v.copy(statusAssertion = status => { oldAssertion(status) if (!assertion(status, expected)) sys.error(s"Expected status to $description $expected but got $status") }) } ) } val retry = option("retry-until-success")(_.copy(retry = true)) val shouldBeDown = option("should-be-down")(_.copy(shouldBeDown = true)) val status = statusAssertionOption("status", "equal")(_ == _) val notStatus = statusAssertionOption("not-status", "not equal")(_ != _) val contains = bodyAssertionOption("body-contains", "contain")(_.contains(_)) val notContains = bodyAssertionOption("body-not-contains", "not contain")(!_.contains(_)) val equals = bodyAssertionOption("body-equals", "equal")(_ == _) val notEquals = bodyAssertionOption("body-not-equals", "not equal")(_ != _) val matches = bodyAssertionOption("body-matches", "match")((body, regexp) => regexp.r.pattern.matcher(body).matches()) val notMatches = bodyAssertionOption("body-not-matches", "not match")((body, regexp) => !regexp.r.pattern.matcher(body).matches()) val uri = basicUri.map(uri => (validateRequest: ValidateRequest) => validateRequest.copy(uri = Some(uri))) Space ~> repsep( retry | shouldBeDown | status | notStatus | contains | notContains | matches | notMatches | equals | notEquals | uri, Space ).map { options => options.foldLeft(ValidateRequest())((validateRequest, applyOption) => applyOption(validateRequest)) } .filter(_.uri.isDefined, _ => "No URI supplied") } private case class ValidateFile( file: Option[String] = None, retry: Boolean = false, assertions: String => Unit = _ => () ) private val validateFileParser: Parser[ValidateFile] = { import complete.DefaultParsers._ def assertionOption[A](opt: String, parser: Parser[A])( assertion: (String, A) => Unit ): Parser[ValidateFile => ValidateFile] = { (literal(opt) ~> Space ~> parser).map(expected => (v: ValidateFile) => { val oldAssertions = v.assertions v.copy(assertions = contents => { // First run the existing assertion oldAssertions(contents) // Now run this assertion assertion(contents, expected) }) } ) } val retry = literal("retry-until-success").map(_ => (v: ValidateFile) => v.copy(retry = true)) val lineCount = assertionOption("line-count", NatBasic) { (contents, expected) => val count = contents.linesIterator.size if (count != expected) sys.error(s"Expected line count of $expected but got $count") } val contains = assertionOption("contains", StringBasic)((contents, expected) => if (!contents.contains(expected)) sys.error(s"Expected file to contain '$expected' but got '$contents'") ) val notContains = assertionOption("not-contains", StringBasic)((contents, expected) => if (contents.contains(expected)) sys.error(s"Expected file to not contain '$expected' but got '$contents'") ) val file = StringBasic.map(fileName => (v: ValidateFile) => v.copy(file = Some(fileName))) Space ~> repsep(retry | lineCount | contains | notContains | file, Space) .map { options => options.foldLeft(ValidateFile())((v, applyOption) => applyOption(v)) } .filter(_.file.isDefined, _ => "No file supplied") } }
{ "content_hash": "bfc6b85297f372b583e0d1e91f3ff572", "timestamp": "", "source": "github", "line_count": 279, "max_line_length": 123, "avg_line_length": 35.81362007168459, "alnum_prop": 0.6384107285828663, "repo_name": "lagom/lagom", "id": "4dd8e3f998132ed76ef172a752c105b40b725a04", "size": "10058", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "dev/sbt-scripted-tools/src/main/scala/com/lightbend/lagom/sbt/scripted/ScriptedTools.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "559" }, { "name": "Java", "bytes": "1037365" }, { "name": "JavaScript", "bytes": "48" }, { "name": "Less", "bytes": "348" }, { "name": "Perl", "bytes": "1102" }, { "name": "Roff", "bytes": "6976" }, { "name": "Scala", "bytes": "1961298" }, { "name": "Shell", "bytes": "8238" } ], "symlink_target": "" }
import unittest import os from test.aiml_tests.client import TestClient from programy.config.brain import BrainFileConfiguration # TODO make sure topic star and that star match for set # TODO <that><topic> can take single "1" and double "1,2" indexes class TopicStarTestClient(TestClient): def __init__(self): TestClient.__init__(self) def load_configuration(self, arguments): super(TopicStarTestClient, self).load_configuration(arguments) self.configuration.brain_configuration._aiml_files = BrainFileConfiguration(files=os.path.dirname(__file__)) class TopicStarAIMLTests(unittest.TestCase): @classmethod def setUpClass(cls): TopicStarAIMLTests.test_client = TopicStarTestClient() def test_single_topicstar_word(self): response = TopicStarAIMLTests.test_client.bot.ask_question("test", "HELLO") self.assertIsNotNone(response) self.assertEqual(response, 'HELLO STAR TOPIC')
{ "content_hash": "7a470c7b0c48b8eca93c61869132c5fc", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 116, "avg_line_length": 33.10344827586207, "alnum_prop": 0.7333333333333333, "repo_name": "dkamotsky/program-y", "id": "8a3218d86c6a771088eca58b603719e1c5c3ecc6", "size": "960", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/aiml_tests/topicstar_tests/test_topicstar_aiml.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "937" }, { "name": "HTML", "bytes": "1583" }, { "name": "Python", "bytes": "1131157" }, { "name": "Shell", "bytes": "3481" } ], "symlink_target": "" }
<?php namespace php_active_record; require_once(DOC_ROOT . 'vendor/simpletest/autorun.php'); require_once(DOC_ROOT . 'vendor/simpletest/web_tester.php'); class SimpletestWebBase extends \WebTestCase { function setUp() { Cache::flush(); $this->fixtures = load_fixtures('test'); } function tearDown() { Cache::flush(); $GLOBALS['db_connection']->truncate_tables('test'); unset($this->fixtures); //shell_exec("rm -fdr ".DOC_ROOT."temp/*"); $called_class = get_called_class(); $called_class_name = $called_class; if(preg_match("/\\\([^\\\]*)$/", $called_class, $arr)) $called_class_name = $arr[1]; echo "WebTest => ".$called_class_name."<br>\n"; flush(); } } ?>
{ "content_hash": "e2f2982e87f28874984f418ed7c97c40", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 92, "avg_line_length": 25.125, "alnum_prop": 0.5497512437810945, "repo_name": "EOL/eol_php_code", "id": "e0f336bfac9abc9af095f68963d9fd6d4b4cf066", "size": "804", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "vendor/php_active_record/simpletest_extended/simpletest_web_base.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "113" }, { "name": "HTML", "bytes": "2060" }, { "name": "JavaScript", "bytes": "2526" }, { "name": "PHP", "bytes": "5234387" }, { "name": "Ruby", "bytes": "470" }, { "name": "Shell", "bytes": "1145" }, { "name": "XSLT", "bytes": "38609" } ], "symlink_target": "" }
'use strict'; angular .module('softvApp') .factory('encuestasFactory', function ($http, $q, globalService, $localStorage) { var paths = { GetAddPregunta: '/Preguntas/GetAddPregunta', GetEncuestasList: '/Encuestas/GetEncuestasList', GetAddEncuesta: '/Encuestas/GetAddEncuesta', GetEditEncuesta: '/Encuestas/GetEditEncuesta', GetPreguntasList: '/Preguntas/GetPreguntasList', GetMuestraPreguntas_EncuestasList: '/MuestraPreguntas_Encuestas/GetMuestraPreguntas_EncuestasList', MuestraRespuestas_Encuestas: '/MuestraRespuestas_Encuestas/GetMuestraRespuestas_EncuestasList', ImprimeEncuesta: '/Encuestas/GetImprimeEncuesta', GetRelPreguntaEncuesta: '/Encuestas/GetEncuestaDetalle', GetMuestra_DistribuidoresEncList: '/Muestra_DistribuidoresEnc/GetMuestra_DistribuidoresEncList', Muestra_PlazaEnc: '/Muestra_PlazaEnc/GetMuestra_PlazaEncList', GetTipSerEncList: '/Muestra_PlazaEnc/GetTipSerEncList', GetUniversoEncuestaAplicarList: '/UniversoEncuesta/GetUniversoEncuestaAplicarList', ProcesosEncuestas: '/ProcesosEncuestas/GetProcesosEncuestasList', GetDeepProcesosEncuestas: '/ProcesosEncuestas/GetDeepProcesosEncuestas', GetGet_UniversoEncuestaList: '/Get_UniversoEncuesta/GetGet_UniversoEncuestaList', GetRelEncuestaCli: '/RelEncuestaClientes/GetRelEncuestaCli', TerminarProceso: '/UniversoEncuesta/UpdateUniversoEncuesta', GetGraficasPreguntasList: '/GraficasPreguntas/GetGraficasPreguntasList', GetResOpcMultsList:'/ResOpcMults/GetResOpcMultsList', DeleteEncuestas:'/Encuestas/DeleteEncuestas' }; var factory = {}; factory.GetResOpcMultsList = function () { var deferred = $q.defer(); var config = { headers: { 'Authorization': $localStorage.currentUser.token } }; $http.get(globalService.getUrl() + paths.GetResOpcMultsList, config).then(function (response) { deferred.resolve(response.data); }).catch(function (response) { deferred.reject(response.data); }); return deferred.promise; }; factory.DeleteEncuestas = function (IdEncuesta) { var deferred = $q.defer(); var Parametros = { 'IdEncuesta': IdEncuesta }; var config = { headers: { 'Authorization': $localStorage.currentUser.token } }; $http.post(globalService.getUrl() + paths.DeleteEncuestas, JSON.stringify(Parametros), config).then(function (response) { deferred.resolve(response.data); }).catch(function (response) { deferred.reject(response.data); }); return deferred.promise; }; factory.GetGraficasPreguntasList = function (idproceso) { var deferred = $q.defer(); var Parametros = { 'IdEncuesta': 0, 'IdUniverso': idproceso, 'FechaI': '', 'FechaF': '' }; console.log(JSON.stringify(Parametros)); var config = { headers: { 'Authorization': $localStorage.currentUser.token } }; $http.post(globalService.getUrl() + paths.GetGraficasPreguntasList, JSON.stringify(Parametros), config).then(function (response) { deferred.resolve(response.data); }).catch(function (response) { deferred.reject(response.data); }); return deferred.promise; }; factory.TerminarProceso = function (idproceso) { var deferred = $q.defer(); var Parametros = { 'objUniversoEncuesta': { 'IdProcesoEnc': idproceso } }; console.log(JSON.stringify(Parametros)); var config = { headers: { 'Authorization': $localStorage.currentUser.token } }; $http.post(globalService.getUrl() + paths.TerminarProceso, JSON.stringify(Parametros), config).then(function (response) { deferred.resolve(response.data); }).catch(function (response) { deferred.reject(response.data); }); return deferred.promise; }; factory.GetRelEncuestaCli = function (idproceso, idencuesta, contrato, respuestas) { var deferred = $q.defer(); var Parametros = { 'objEncCli': { 'IdProcesoEnc': idproceso, 'IdEncuesta': idencuesta, 'Contrato': contrato }, 'LstRelEnProcesos': respuestas }; console.log(JSON.stringify(Parametros)); var config = { headers: { 'Authorization': $localStorage.currentUser.token } }; $http.post(globalService.getUrl() + paths.GetRelEncuestaCli, JSON.stringify(Parametros), config).then(function (response) { deferred.resolve(response.data); }).catch(function (response) { deferred.reject(response.data); }); return deferred.promise; }; factory.GetGet_UniversoEncuestaList = function (object) { var deferred = $q.defer(); var Parametros = { 'IdPlaza': object.IdPlaza, 'IdTipSer': object.IdTipSer, 'IdTipBusq': object.IdTipBusq, 'Desconectado': object.Desconectado, 'Instalado': object.Instalado, 'Suspendido': object.Suspendido, 'Baja':object.Baja, 'Contratado': object.Contratado, 'Temporales': object.Temporales, 'Fuera': object.Fuera, 'IdTipFecha': object.IdTipFecha, 'FechaI': object.FechaI, 'FechaF': object.FechaF, 'IdUsuario': $localStorage.currentUser.idUsuario, 'IdEncuesta': object.IdEncuesta, 'NombreProceso': object.NombreProceso }; console.log(JSON.stringify(Parametros)); var config = { headers: { 'Authorization': $localStorage.currentUser.token } }; $http.post(globalService.getUrl() + paths.GetGet_UniversoEncuestaList, JSON.stringify(Parametros), config).then(function (response) { deferred.resolve(response.data); }).catch(function (response) { deferred.reject(response.data); }); return deferred.promise; }; factory.GetDeepProcesosEncuestas = function (idproceso) { var deferred = $q.defer(); var Parametros = { 'IdProcesoEnc': idproceso }; var config = { headers: { 'Authorization': $localStorage.currentUser.token } }; $http.post(globalService.getUrl() + paths.GetDeepProcesosEncuestas, JSON.stringify(Parametros), config).then(function (response) { deferred.resolve(response.data); }).catch(function (response) { deferred.reject(response.data); }); return deferred.promise; }; factory.GetUniversoEncuestaAplicarList = function (idproceso) { var deferred = $q.defer(); var Parametros = { 'IdProcesoEnc': idproceso }; var config = { headers: { 'Authorization': $localStorage.currentUser.token } }; $http.post(globalService.getUrl() + paths.GetUniversoEncuestaAplicarList, JSON.stringify(Parametros), config).then(function (response) { deferred.resolve(response.data); }).catch(function (response) { deferred.reject(response.data); }); return deferred.promise; }; factory.ProcesosEncuestas = function () { var deferred = $q.defer(); var config = { headers: { 'Authorization': $localStorage.currentUser.token } }; $http.get(globalService.getUrl() + paths.ProcesosEncuestas, config).then(function (response) { deferred.resolve(response.data); }).catch(function (response) { deferred.reject(response.data); }); return deferred.promise; }; factory.GetTipSerEncList = function () { var deferred = $q.defer(); var config = { headers: { 'Authorization': $localStorage.currentUser.token } }; $http.get(globalService.getUrl() + paths.GetTipSerEncList, config).then(function (response) { deferred.resolve(response.data); }).catch(function (response) { deferred.reject(response.data); }); return deferred.promise; }; factory.GetMuestra_DistribuidoresEncList = function () { var deferred = $q.defer(); var config = { headers: { 'Authorization': $localStorage.currentUser.token } }; $http.get(globalService.getUrl() + paths.GetMuestra_DistribuidoresEncList, config).then(function (response) { deferred.resolve(response.data); }).catch(function (response) { deferred.reject(response.data); }); return deferred.promise; }; factory.Muestra_PlazaEnc = function (idcompania) { var deferred = $q.defer(); var Parametros = { 'Clv_Plaza': idcompania }; var config = { headers: { 'Authorization': $localStorage.currentUser.token } }; $http.post(globalService.getUrl() + paths.Muestra_PlazaEnc, JSON.stringify(Parametros), config).then(function (response) { deferred.resolve(response.data); }).catch(function (response) { deferred.reject(response.data); }); return deferred.promise; }; factory.GetRelPreguntaEncuesta = function (idencuesta) { var deferred = $q.defer(); var Parametros = { 'idencuesta': idencuesta }; var config = { headers: { 'Authorization': $localStorage.currentUser.token } }; $http.post(globalService.getUrl() + paths.GetRelPreguntaEncuesta, JSON.stringify(Parametros), config).then(function (response) { deferred.resolve(response.data); }).catch(function (response) { deferred.reject(response.data); }); return deferred.promise; }; factory.ImprimeEncuesta = function (idencuesta) { var deferred = $q.defer(); var Parametros = { 'idencuesta': idencuesta }; var config = { headers: { 'Authorization': $localStorage.currentUser.token } }; $http.post(globalService.getUrl() + paths.ImprimeEncuesta, JSON.stringify(Parametros), config).then(function (response) { deferred.resolve(response.data); }).catch(function (response) { deferred.reject(response.data); }); return deferred.promise; }; factory.GetPreguntasList = function () { var deferred = $q.defer(); var config = { headers: { 'Authorization': $localStorage.currentUser.token } }; $http.get(globalService.getUrl() + paths.GetPreguntasList, config).then(function (response) { deferred.resolve(response.data); }).catch(function (response) { deferred.reject(response.data); }); return deferred.promise; }; factory.MuestraRespuestas_Encuestas = function (IdPregunta) { var deferred = $q.defer(); var Parametros = { 'IdPregunta': IdPregunta }; var config = { headers: { 'Authorization': $localStorage.currentUser.token } }; $http.post(globalService.getUrl() + paths.MuestraRespuestas_Encuestas, JSON.stringify(Parametros), config).then(function (response) { deferred.resolve(response.data); }).catch(function (response) { deferred.reject(response.data); }); return deferred.promise; }; factory.GetMuestraPreguntas_EncuestasList = function (IdEncuesta) { var deferred = $q.defer(); var Parametros = { 'IdEncuesta': IdEncuesta }; var config = { headers: { 'Authorization': $localStorage.currentUser.token } }; $http.post(globalService.getUrl() + paths.GetMuestraPreguntas_EncuestasList, JSON.stringify(Parametros), config).then(function (response) { deferred.resolve(response.data); }).catch(function (response) { deferred.reject(response.data); }); return deferred.promise; }; factory.GetEditEncuesta = function (objEncuesta, arraypreguntas, arrayrespuestas) { var deferred = $q.defer(); var Parametros = { 'objEncuesta': objEncuesta, 'LstPregunta': arraypreguntas, 'LstRespuestas': arrayrespuestas }; var config = { headers: { 'Authorization': $localStorage.currentUser.token } }; $http.post(globalService.getUrl() + paths.GetEditEncuesta, JSON.stringify(Parametros), config).then(function (response) { deferred.resolve(response.data); }).catch(function (response) { deferred.reject(response.data); }); return deferred.promise; }; factory.GetAddEncuesta = function (IdEncuesta, titulo, descripcion, arraypreguntas, op) { var deferred = $q.defer(); var Parametros = { 'objEncuesta': { 'IdEncuesta': IdEncuesta, 'TituloEncuesta': titulo, 'Descripcion': descripcion, 'FechaCreacion': '', 'IdUsuario': $localStorage.currentUser.IdUsuario, 'Activa': 1, 'Op': op }, 'LstPregunta': arraypreguntas }; var config = { headers: { 'Authorization': $localStorage.currentUser.token } }; $http.post(globalService.getUrl() + paths.GetAddEncuesta, JSON.stringify(Parametros), config).then(function (response) { deferred.resolve(response.data); }).catch(function (response) { deferred.reject(response.data); }); return deferred.promise; }; factory.GetAddPregunta = function (pregunta, tipo, arrayOpcMultiple) { var deferred = $q.defer(); var Parametros = { 'objPregunta': { 'Pregunta': pregunta, 'IdTipoPregunta': tipo }, 'ResOpcMult': arrayOpcMultiple }; var config = { headers: { 'Authorization': $localStorage.currentUser.token } }; $http.post(globalService.getUrl() + paths.GetAddPregunta, JSON.stringify(Parametros), config).then(function (response) { deferred.resolve(response.data); }).catch(function (response) { deferred.reject(response.data); }); return deferred.promise; }; factory.GetEncuestasList = function () { var deferred = $q.defer(); var config = { headers: { 'Authorization': $localStorage.currentUser.token } }; $http.get(globalService.getUrl() + paths.GetEncuestasList, config).then(function (response) { deferred.resolve(response.data); }).catch(function (response) { deferred.reject(response.data); }); return deferred.promise; }; return factory; });
{ "content_hash": "abbdf7391455239ae00a19346b5a7a51", "timestamp": "", "source": "github", "line_count": 520, "max_line_length": 145, "avg_line_length": 28.66730769230769, "alnum_prop": 0.614476420473603, "repo_name": "alesabas/Softv", "id": "9990d81a685db006d33aad8287370893b4281e02", "size": "14907", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "app/scripts/factories/encuestasFactory.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "648182" }, { "name": "HTML", "bytes": "1284759" }, { "name": "JavaScript", "bytes": "2156430" } ], "symlink_target": "" }
<?xml version = '1.0' encoding = 'UTF-8'?> <TableProxyOraclev11g class="oracle.dbtools.crest.model.design.storage.oracle.v11g.TableProxyOraclev11g" name="assay" directorySegmentName="seg_0" id="B6428E30-B00D-1649-C79A-86087AD8FE2F"> <createdBy>rwang</createdBy> <createdTime>2015-02-23 15:38:15 UTC</createdTime> <ownerDesignName>spectra-cluster</ownerDesignName> <logging>YES</logging> <partitionedRowMovement>DISABLE</partitionedRowMovement> <tableSpace>CAC0F871-B420-4A76-2DCF-5DE118D43A23</tableSpace> <columnProxies> <ColumnProxy class="oracle.dbtools.crest.model.design.storage.oracle.v11g.ColumnProxyOraclev11g" name="instrument" id="0CEA3978-C529-6F36-87B8-6411FEF5BE4F"> <createdBy>rwang</createdBy> <createdTime>2015-02-23 15:38:15 UTC</createdTime> <ownerDesignName>spectra-cluster</ownerDesignName> </ColumnProxy> <ColumnProxy class="oracle.dbtools.crest.model.design.storage.oracle.v11g.ColumnProxyOraclev11g" name="project_accession" id="461A6B31-3111-C176-8547-F88BCD0FED23"> <createdBy>rwang</createdBy> <createdTime>2015-02-23 15:38:15 UTC</createdTime> <ownerDesignName>spectra-cluster</ownerDesignName> </ColumnProxy> <ColumnProxy class="oracle.dbtools.crest.model.design.storage.oracle.v11g.ColumnProxyOraclev11g" name="instrument_type" id="519E6E39-76EB-940B-C298-91E5E0036EB7"> <createdBy>rwang</createdBy> <createdTime>2015-02-23 15:38:15 UTC</createdTime> <ownerDesignName>spectra-cluster</ownerDesignName> </ColumnProxy> <ColumnProxy class="oracle.dbtools.crest.model.design.storage.oracle.v11g.ColumnProxyOraclev11g" name="search_engine" id="6E945C36-B87D-8EC7-AFEF-D4C57942F6E0"> <createdBy>rwang</createdBy> <createdTime>2015-02-23 15:38:15 UTC</createdTime> <ownerDesignName>spectra-cluster</ownerDesignName> </ColumnProxy> <ColumnProxy class="oracle.dbtools.crest.model.design.storage.oracle.v11g.ColumnProxyOraclev11g" name="multi_species" id="917F38CC-0866-ADD6-ED19-DB498CB3E8C2"> <createdBy>rwang</createdBy> <createdTime>2015-02-23 15:38:15 UTC</createdTime> <ownerDesignName>spectra-cluster</ownerDesignName> </ColumnProxy> <ColumnProxy class="oracle.dbtools.crest.model.design.storage.oracle.v11g.ColumnProxyOraclev11g" name="assay_title" id="9B1B29E8-7842-4858-8690-DB5955DFCC8C"> <createdBy>rwang</createdBy> <createdTime>2015-02-23 15:38:15 UTC</createdTime> <ownerDesignName>spectra-cluster</ownerDesignName> </ColumnProxy> <ColumnProxy class="oracle.dbtools.crest.model.design.storage.oracle.v11g.ColumnProxyOraclev11g" name="assay_accession" id="9C5CEB77-D4E2-6DD4-9FEB-6D142CC68C2D"> <createdBy>rwang</createdBy> <createdTime>2015-02-23 15:38:15 UTC</createdTime> <ownerDesignName>spectra-cluster</ownerDesignName> </ColumnProxy> <ColumnProxy class="oracle.dbtools.crest.model.design.storage.oracle.v11g.ColumnProxyOraclev11g" name="disease" id="A4166582-A666-AC43-9F1E-AAA49A16F72C"> <createdBy>rwang</createdBy> <createdTime>2015-02-23 15:38:15 UTC</createdTime> <ownerDesignName>spectra-cluster</ownerDesignName> </ColumnProxy> <ColumnProxy class="oracle.dbtools.crest.model.design.storage.oracle.v11g.ColumnProxyOraclev11g" name="assay_pk" id="A6FFD1B6-1BD0-F5D4-A783-1829668AD5B6"> <createdBy>rwang</createdBy> <createdTime>2015-02-23 15:38:15 UTC</createdTime> <ownerDesignName>spectra-cluster</ownerDesignName> </ColumnProxy> <ColumnProxy class="oracle.dbtools.crest.model.design.storage.oracle.v11g.ColumnProxyOraclev11g" name="species" id="C38180C9-FABB-93C6-BDDD-0F2A03A7B2D5"> <createdBy>rwang</createdBy> <createdTime>2015-02-23 15:38:15 UTC</createdTime> <ownerDesignName>spectra-cluster</ownerDesignName> </ColumnProxy> <ColumnProxy class="oracle.dbtools.crest.model.design.storage.oracle.v11g.ColumnProxyOraclev11g" name="biomedical" id="C3AD9FDC-BE71-FC35-E65E-11FDB62813AD"> <createdBy>rwang</createdBy> <createdTime>2015-02-23 15:38:15 UTC</createdTime> <ownerDesignName>spectra-cluster</ownerDesignName> </ColumnProxy> <ColumnProxy class="oracle.dbtools.crest.model.design.storage.oracle.v11g.ColumnProxyOraclev11g" name="taxonomy_id" id="C5F0E55C-A9A9-E62B-64D4-D0FF80C7D4D9"> <createdBy>rwang</createdBy> <createdTime>2015-02-23 15:38:15 UTC</createdTime> <ownerDesignName>spectra-cluster</ownerDesignName> </ColumnProxy> <ColumnProxy class="oracle.dbtools.crest.model.design.storage.oracle.v11g.ColumnProxyOraclev11g" name="project_title" id="DBB49326-A83B-3C93-AA40-B2A5E2BE6D2B"> <createdBy>rwang</createdBy> <createdTime>2015-02-23 15:38:15 UTC</createdTime> <ownerDesignName>spectra-cluster</ownerDesignName> </ColumnProxy> <ColumnProxy class="oracle.dbtools.crest.model.design.storage.oracle.v11g.ColumnProxyOraclev11g" name="tissue" id="FCBC3E90-EE5E-0378-2851-E629611E3398"> <createdBy>rwang</createdBy> <createdTime>2015-02-23 15:38:15 UTC</createdTime> <ownerDesignName>spectra-cluster</ownerDesignName> </ColumnProxy> </columnProxies> <indexProxies> <IndexProxy class="oracle.dbtools.crest.model.design.storage.oracle.v10g.IndexProxyOraclev10g" name="assay_accession_IDX" id="0C8F2ECF-19DE-6524-FE4F-DD34F15F3F5D"> <createdBy>rwang</createdBy> <createdTime>2015-02-23 15:38:15 UTC</createdTime> <ownerDesignName>spectra-cluster</ownerDesignName> <tableSpace>168E818E-A3C5-54B0-AA20-FE54C47AA105</tableSpace> </IndexProxy> <IndexProxy class="oracle.dbtools.crest.model.design.storage.oracle.v10g.IndexProxyOraclev10g" name="assay_instrut_IDX" id="182CB706-D2F2-17BA-1E23-030B988223AC"> <createdBy>rwang</createdBy> <createdTime>2015-02-23 15:38:15 UTC</createdTime> <ownerDesignName>spectra-cluster</ownerDesignName> <tableSpace>168E818E-A3C5-54B0-AA20-FE54C47AA105</tableSpace> </IndexProxy> <IndexProxy class="oracle.dbtools.crest.model.design.storage.oracle.v10g.IndexProxyOraclev10g" name="assay_species_IDX" id="25464971-B021-CCCB-264D-FC10E51F5E28"> <createdBy>rwang</createdBy> <createdTime>2015-02-23 15:38:15 UTC</createdTime> <ownerDesignName>spectra-cluster</ownerDesignName> <tableSpace>168E818E-A3C5-54B0-AA20-FE54C47AA105</tableSpace> </IndexProxy> <IndexProxy class="oracle.dbtools.crest.model.design.storage.oracle.v10g.IndexProxyOraclev10g" name="assay_tax_id_IDX" id="967ECFE3-2ECB-8A25-9FF1-35E4B7EE220F"> <createdBy>rwang</createdBy> <createdTime>2015-02-23 15:38:15 UTC</createdTime> <ownerDesignName>spectra-cluster</ownerDesignName> <tableSpace>168E818E-A3C5-54B0-AA20-FE54C47AA105</tableSpace> </IndexProxy> <IndexProxy class="oracle.dbtools.crest.model.design.storage.oracle.v10g.IndexProxyOraclev10g" name="assay_instrut_type_IDX" id="D9CE7D69-AA3E-6A26-06B2-663A9626CCC2"> <createdBy>rwang</createdBy> <createdTime>2015-02-23 15:38:15 UTC</createdTime> <ownerDesignName>spectra-cluster</ownerDesignName> <tableSpace>168E818E-A3C5-54B0-AA20-FE54C47AA105</tableSpace> </IndexProxy> <IndexProxy class="oracle.dbtools.crest.model.design.storage.oracle.v10g.IndexProxyOraclev10g" name="assay_project_IDX" id="DDC2EBDD-D6E6-6557-36F9-7A927B6C2DC7"> <createdBy>rwang</createdBy> <createdTime>2015-02-23 15:38:15 UTC</createdTime> <ownerDesignName>spectra-cluster</ownerDesignName> <tableSpace>168E818E-A3C5-54B0-AA20-FE54C47AA105</tableSpace> </IndexProxy> <IndexProxy class="oracle.dbtools.crest.model.design.storage.oracle.v10g.IndexProxyOraclev10g" name="assay_search_engine_IDX" id="DEDDE468-1946-05F4-386F-1647542017CE"> <createdBy>rwang</createdBy> <createdTime>2015-02-23 15:38:15 UTC</createdTime> <ownerDesignName>spectra-cluster</ownerDesignName> <tableSpace>168E818E-A3C5-54B0-AA20-FE54C47AA105</tableSpace> </IndexProxy> </indexProxies> <primaryKeys> <PrimaryKey class="oracle.dbtools.crest.model.design.storage.oracle.v10g.PKProxyOraclev10g" name="assay_PK" id="5458CB60-B473-8F34-2A78-A725919F0004"> <createdBy>rwang</createdBy> <createdTime>2015-02-23 15:38:15 UTC</createdTime> <ownerDesignName>spectra-cluster</ownerDesignName> <indexSort>SORTED</indexSort> </PrimaryKey> </primaryKeys> <uniqueKeys> <UniqueKey class="oracle.dbtools.crest.model.design.storage.oracle.v10g.UniqueOraclev10g" name="assay_UN" id="5CA4962A-5AFA-6F6B-7EC9-87624580ABDC"> <createdBy>rwang</createdBy> <createdTime>2015-02-23 15:38:15 UTC</createdTime> <ownerDesignName>spectra-cluster</ownerDesignName> <indexSort>SORTED</indexSort> </UniqueKey> </uniqueKeys> </TableProxyOraclev11g>
{ "content_hash": "941eb7597f21021a18726c1c5ad0d0d0", "timestamp": "", "source": "github", "line_count": 141, "max_line_length": 189, "avg_line_length": 57.95744680851064, "alnum_prop": 0.8131424375917768, "repo_name": "PRIDE-Cluster/cluster-repo", "id": "9e07961e99b189c3dff71d0256de890f2da04fbf", "size": "8172", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "schema/spectra-cluster/rel/8F009BE1-DFB94132C542/phys/32076570-BF29817DFF70/Table/seg_0/B6428E30-B00D-1649-C79A-86087AD8FE2F.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "144143" }, { "name": "PLSQL", "bytes": "11603" } ], "symlink_target": "" }
(function() { 'use strict'; angular .module('openfader') .factory('githubContributor', githubContributor); /** @ngInject */ function githubContributor($log, $http) { var apiHost = 'https://api.github.com/repos/Swiip/generator-gulp-angular'; var service = { apiHost: apiHost, getContributors: getContributors }; return service; function getContributors(limit) { if (!limit) { limit = 30; } return $http.get(apiHost + '/contributors?per_page=' + limit) .then(getContributorsComplete) .catch(getContributorsFailed); function getContributorsComplete(response) { return response.data; } function getContributorsFailed(error) { $log.error('XHR Failed for getContributors.\n' + angular.toJson(error.data, true)); } } } })();
{ "content_hash": "96f0fc20b8acf50808bd189bd8aba6a7", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 91, "avg_line_length": 23.2972972972973, "alnum_prop": 0.6218097447795824, "repo_name": "wab/openfader", "id": "7ecf70683dc3e941a20d42395881a9132b6a394f", "size": "862", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/app/components/githubContributor/githubContributor.service.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "3883" }, { "name": "HTML", "bytes": "4149" }, { "name": "JavaScript", "bytes": "23750" } ], "symlink_target": "" }
#region LICENSE // Copyright (C) 2015 by Sherif Elmetainy (Grendiser@Kazzak-EU) // // 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. #endregion using System.Globalization; using Newtonsoft.Json; namespace WOWSharp.Warcraft { /// <summary> /// Pets stats /// </summary> [JsonObject(MemberSerialization.OptIn)] public class PetStats { /// <summary> /// gets or sets breed id /// </summary> [JsonProperty(PropertyName="breedId")] public int BreedId { get; set; } /// <summary> /// gets or sets health points /// </summary> [JsonProperty(PropertyName="health")] public int Health { get; set; } /// <summary> /// gets or sets level /// </summary> [JsonProperty(PropertyName="level")] public int Level { get; set; } /// <summary> /// gets or sets pet's quality /// </summary> [JsonProperty(PropertyName="petQualityId")] public ItemQuality Quality { get; set; } /// <summary> /// gets or sets power /// </summary> [JsonProperty(PropertyName="power")] public int Power { get; set; } /// <summary> /// gets or sets species id /// </summary> [JsonProperty(PropertyName="speciesId")] public int SpeciesId { get; set; } /// <summary> /// gets or sets pet's speed /// </summary> [JsonProperty(PropertyName="speed")] public int Speed { get; set; } /// <summary> /// String representation for debugging purposes /// </summary> /// <returns> String representation for debugging purposes </returns> public override string ToString() { return "Level " + Level.ToString(CultureInfo.InvariantCulture); } } }
{ "content_hash": "d539e7507e11c1e86bda2440a732d666", "timestamp": "", "source": "github", "line_count": 113, "max_line_length": 80, "avg_line_length": 28.283185840707965, "alnum_prop": 0.5716520650813517, "repo_name": "sherif-elmetainy/wowsharp", "id": "65c94de6e7a7a5e3de51cec58f899d4816fdf98a", "size": "3198", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/WOWSharp.Warcraft/PetStats.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "647768" } ], "symlink_target": "" }
layout: page title: About the Jekyll Theme image: feature: abstract-5.jpg comments: false modified: 2016-02-01 --- They say three times the charm, so here is another free responsive Jekyll blog theme for you. I've learned a ton since open sourcing my first two themes [on Github](http://github.com/mmistakes), and wanted to try a few new things this time around. If you've used any of [my other themes](http://mademistakes.com/work/jekyll-themes/) most of this should be familiar territory... ## HPSTR Features: * Compatible with Jekyll 3 and GitHub Pages. * Responsive templates for post, page, and post index `_layouts`. Looks great on mobile, tablet, and desktop devices. * Gracefully degrades in older browsers. Compatible with Internet Explorer 8+ and all modern browsers. * Sweet animated menu. * Background image support. * Support for large images to call out your favorite posts. * Optional [Disqus](http://disqus.com) comments. * Simple and clear permalink structure[^1]. * [Open Graph](https://developers.facebook.com/docs/opengraph/) and [Twitter Cards](https://dev.twitter.com/docs/cards) support for a better social sharing experience. * [Custom 404 page]({{ site.url }}/404.html) to get you started. * [Syntax highlighting]({{ site.url }}/code-highlighting-post/) stylesheets to make your code examples look snazzy. <div markdown="0"><a href="{{ site.url }}/theme-setup/" class="btn btn-info">Theme Setup</a> <a href="https://github.com/mmistakes/hpstr-jekyll-theme" class="btn btn-success">Download HPSTR</a></div> [^1]: Example: *domain.com/category-name/post-title*
{ "content_hash": "968eeaf316dcb40a30371c301338a6a8", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 247, "avg_line_length": 54.96551724137931, "alnum_prop": 0.7478042659974906, "repo_name": "hellosilence/secondblog", "id": "3fcbffaa60b47922ec8ffdd2f0c3d7321a4bbae3", "size": "1598", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "about/index.md", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "49795" }, { "name": "HTML", "bytes": "26341" }, { "name": "JavaScript", "bytes": "67913" }, { "name": "Ruby", "bytes": "2796" } ], "symlink_target": "" }
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.codeInspection.miscGenerics; import com.intellij.codeInspection.ProblemDescriptor; import com.intellij.codeInspection.ui.MultipleCheckboxOptionsPanel; import com.intellij.codeInspection.util.IntentionName; import com.intellij.java.JavaBundle; import com.intellij.openapi.project.Project; import com.intellij.psi.*; import com.intellij.psi.codeStyle.CodeStyleManager; import com.intellij.psi.search.PsiSearchHelper; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.util.PsiTypesUtil; import com.intellij.psi.util.PsiUtil; import com.intellij.psi.util.TypeConversionUtil; import com.intellij.refactoring.typeMigration.TypeMigrationProcessor; import com.intellij.refactoring.typeMigration.TypeMigrationRules; import com.intellij.util.ObjectUtils; import com.siyeh.ig.BaseInspection; import com.siyeh.ig.BaseInspectionVisitor; import com.siyeh.ig.InspectionGadgetsFix; import com.siyeh.ig.psiutils.*; import one.util.streamex.StreamEx; import org.intellij.lang.annotations.Pattern; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.Set; /** * @author dsl */ public class RawUseOfParameterizedTypeInspection extends BaseInspection { @SuppressWarnings("PublicField") public boolean ignoreObjectConstruction = false; @SuppressWarnings("PublicField") public boolean ignoreTypeCasts = false; @SuppressWarnings("PublicField") public boolean ignoreUncompilable = true; @SuppressWarnings("PublicField") public boolean ignoreParametersOfOverridingMethods = false; @SuppressWarnings("PublicField") public boolean ignoreWhenQuickFixNotAvailable = false; @Pattern(VALID_ID_PATTERN) @NotNull @Override public String getID() { return "rawtypes"; } @Nullable @Override public String getAlternativeID() { return "RawUseOfParameterized"; } @Override @NotNull protected String buildErrorString(Object... infos) { return JavaBundle.message("inspection.raw.use.of.parameterized.type.problem.descriptor"); } @Override @Nullable public JComponent createOptionsPanel() { final MultipleCheckboxOptionsPanel optionsPanel = new MultipleCheckboxOptionsPanel(this); optionsPanel.addCheckbox(JavaBundle.message("raw.use.of.parameterized.type.ignore.new.objects.option"), "ignoreObjectConstruction"); optionsPanel.addCheckbox(JavaBundle.message("raw.use.of.parameterized.type.ignore.type.casts.option"), "ignoreTypeCasts"); optionsPanel.addCheckbox(JavaBundle.message("raw.use.of.parameterized.type.ignore.uncompilable.option"), "ignoreUncompilable"); optionsPanel.addCheckbox(JavaBundle.message("raw.use.of.parameterized.type.ignore.overridden.parameter.option"), "ignoreParametersOfOverridingMethods"); optionsPanel.addCheckbox(JavaBundle.message("raw.use.of.parameterized.type.ignore.quickfix.not.available.option"), "ignoreWhenQuickFixNotAvailable"); return optionsPanel; } @Override public boolean shouldInspect(@NotNull PsiFile file) { return PsiUtil.isLanguageLevel5OrHigher(file); } @Override protected InspectionGadgetsFix buildFix(Object... infos) { return (InspectionGadgetsFix)infos[0]; } @Nullable private static InspectionGadgetsFix createFix(PsiElement target) { if (target instanceof PsiTypeElement && target.getParent() instanceof PsiVariable) { PsiVariable variable = (PsiVariable)target.getParent(); final PsiType type = getSuggestedType(variable); if (type != null) { final String typeText = GenericsUtil.getVariableTypeByExpressionType(type).getPresentableText(); final String message = JavaBundle.message("raw.variable.type.can.be.generic.quickfix", variable.getName(), typeText); return new RawTypeCanBeGenericFix(message); } } if (target instanceof PsiJavaCodeReferenceElement) { PsiTypeElement typeElement = ObjectUtils.tryCast(target.getParent(), PsiTypeElement.class); if (typeElement == null) return null; PsiTypeCastExpression cast = ObjectUtils.tryCast(typeElement.getParent(), PsiTypeCastExpression.class); if (cast == null) return null; if (!canUseUpperBound(cast)) return null; PsiClass psiClass = PsiUtil.resolveClassInClassTypeOnly(cast.getType()); if (psiClass == null) return null; int count = psiClass.getTypeParameters().length; return new CastQuickFix(typeElement.getText() + StreamEx.constant("?", count).joining(",", "<", ">")); } return null; } private static boolean canUseUpperBound(PsiTypeCastExpression cast) { PsiClass psiClass = PsiUtil.resolveClassInClassTypeOnly(cast.getType()); if (psiClass == null) return false; Set<PsiTypeParameter> parameters = Set.of(psiClass.getTypeParameters()); if (parameters.isEmpty()) return false; PsiElement parent = PsiUtil.skipParenthesizedExprUp(cast.getParent()); if (parent instanceof PsiReferenceExpression) { PsiReferenceExpression ref = (PsiReferenceExpression)parent; PsiElement target = ref.resolve(); if (!(target instanceof PsiMember)) return false; PsiClass containingClass = ((PsiMember)target).getContainingClass(); if (containingClass == null) return false; PsiSubstitutor substitutor = TypeConversionUtil.getSuperClassSubstitutor(containingClass, psiClass, PsiSubstitutor.EMPTY); if (target instanceof PsiField) { PsiType type = substitutor.substitute(((PsiField)target).getType()); PsiClass varType = PsiUtil.resolveClassInClassTypeOnly(type); return (varType instanceof PsiTypeParameter && parameters.contains(varType) && !PsiUtil.isAccessedForWriting(ref)) || !PsiTypesUtil.mentionsTypeParameters(type, parameters); } if (target instanceof PsiMethod) { PsiMethodCallExpression call = ObjectUtils.tryCast(ref.getParent(), PsiMethodCallExpression.class); if (call == null) return false; if (!ExpressionUtils.isVoidContext(call)) { PsiType type = substitutor.substitute(((PsiMethod)target).getReturnType()); PsiClass varType = PsiUtil.resolveClassInClassTypeOnly(type); if (!(varType instanceof PsiTypeParameter && parameters.contains(varType)) && PsiTypesUtil.mentionsTypeParameters(type, parameters)) { return false; } } PsiParameterList parameterList = ((PsiMethod)target).getParameterList(); for (PsiParameter parameter : parameterList.getParameters()) { if (parameter.isVarArgs() && call.getArgumentList().getExpressionCount() == parameterList.getParametersCount() - 1) { // No vararg parameters specified continue; } PsiType parameterType = parameter.getType(); if (PsiTypesUtil.mentionsTypeParameters(parameterType, tp -> true)) return false; } return true; } } return false; } @Override public BaseInspectionVisitor buildVisitor() { return new RawUseOfParameterizedTypeVisitor(); } private class RawUseOfParameterizedTypeVisitor extends BaseInspectionVisitor { @Override public void visitNewExpression(@NotNull PsiNewExpression expression) { super.visitNewExpression(expression); if (ignoreObjectConstruction) { return; } if (ignoreUncompilable && expression.isArrayCreation()) { //array creation can (almost) never be generic return; } final PsiJavaCodeReferenceElement classReference = expression.getClassOrAnonymousClassReference(); checkReferenceElement(classReference); } @Override public void visitTypeElement(@NotNull PsiTypeElement typeElement) { PsiElement directParent = typeElement.getParent(); if (directParent instanceof PsiVariable) { if (directParent instanceof PsiPatternVariable) return; if (getSuggestedType((PsiVariable)directParent) != null) { reportProblem(typeElement); return; } } final PsiType type = typeElement.getType(); if (!(type instanceof PsiClassType)) { return; } super.visitTypeElement(typeElement); if (ignoreUncompilable && directParent instanceof PsiTypeElement) { PsiType parentType = ((PsiTypeElement)directParent).getType(); if (parentType instanceof PsiArrayType) { if (PsiTreeUtil.skipParentsOfType(directParent, PsiTypeElement.class) instanceof PsiMethodReferenceExpression) { return; } } } final PsiElement parent = PsiTreeUtil.skipParentsOfType( typeElement, PsiTypeElement.class, PsiReferenceParameterList.class, PsiJavaCodeReferenceElement.class); if (parent instanceof PsiInstanceOfExpression || parent instanceof PsiClassObjectAccessExpression) { return; } if (ignoreTypeCasts && parent instanceof PsiTypeCastExpression) { return; } if (PsiTreeUtil.getParentOfType(typeElement, PsiComment.class) != null) { return; } if (ignoreUncompilable && parent instanceof PsiAnnotationMethod) { // type of class type parameter cannot be parameterized if annotation method has default value final PsiAnnotationMemberValue defaultValue = ((PsiAnnotationMethod)parent).getDefaultValue(); if (defaultValue != null && directParent instanceof PsiTypeElement) { return; } } if (parent instanceof PsiParameter) { final PsiParameter parameter = (PsiParameter)parent; final PsiElement declarationScope = parameter.getDeclarationScope(); if (declarationScope instanceof PsiMethod) { final PsiMethod method = (PsiMethod)declarationScope; if (ignoreParametersOfOverridingMethods) { if (MethodUtils.getSuper(method) != null || MethodCallUtils.isUsedAsSuperConstructorCallArgument(parameter, false)) { return; } } else if (ignoreUncompilable && (LibraryUtil.isOverrideOfLibraryMethod(method) || MethodCallUtils.isUsedAsSuperConstructorCallArgument(parameter, true))) { return; } } } final PsiJavaCodeReferenceElement referenceElement = typeElement.getInnermostComponentReferenceElement(); checkReferenceElement(referenceElement); } private void reportProblem(@NotNull PsiElement element) { InspectionGadgetsFix fix = createFix(element); if (fix == null && ignoreWhenQuickFixNotAvailable) return; registerError(element, fix); } @Override public void visitReferenceElement(PsiJavaCodeReferenceElement reference) { super.visitReferenceElement(reference); final PsiElement referenceParent = reference.getParent(); if (!(referenceParent instanceof PsiReferenceList)) { return; } final PsiReferenceList referenceList = (PsiReferenceList)referenceParent; final PsiElement listParent = referenceList.getParent(); if (!(listParent instanceof PsiClass)) { return; } if (referenceList.equals(((PsiClass)listParent).getPermitsList())) { return; } checkReferenceElement(reference); } private void checkReferenceElement(PsiJavaCodeReferenceElement reference) { if (reference == null) { return; } final PsiType[] typeParameters = reference.getTypeParameters(); if (typeParameters.length > 0) { return; } final PsiElement element = reference.resolve(); if (!(element instanceof PsiClass)) { return; } final PsiClass aClass = (PsiClass)element; final PsiElement qualifier = reference.getQualifier(); if (qualifier instanceof PsiJavaCodeReferenceElement) { final PsiJavaCodeReferenceElement qualifierReference = (PsiJavaCodeReferenceElement)qualifier; if (!aClass.hasModifierProperty(PsiModifier.STATIC) && !aClass.isInterface() && !aClass.isEnum()) { checkReferenceElement(qualifierReference); } } if (!aClass.hasTypeParameters()) { return; } reportProblem(reference); } } @Nullable private static PsiType getSuggestedType(@NotNull PsiVariable variable) { final PsiExpression initializer = variable.getInitializer(); if (initializer == null) return null; final PsiType variableType = variable.getType(); final PsiType initializerType = initializer.getType(); if (!(variableType instanceof PsiClassType)) return null; final PsiClassType variableClassType = (PsiClassType) variableType; if (!variableClassType.isRaw()) return null; if (!(initializerType instanceof PsiClassType)) return null; final PsiClassType initializerClassType = (PsiClassType) initializerType; if (initializerClassType.isRaw()) return null; final PsiClassType.ClassResolveResult variableResolveResult = variableClassType.resolveGenerics(); final PsiClassType.ClassResolveResult initializerResolveResult = initializerClassType.resolveGenerics(); if (initializerResolveResult.getElement() == null) return null; PsiClass variableResolved = variableResolveResult.getElement(); if (variableResolved == null) return null; PsiSubstitutor targetSubstitutor = TypeConversionUtil .getClassSubstitutor(variableResolved, initializerResolveResult.getElement(), initializerResolveResult.getSubstitutor()); if (targetSubstitutor == null) return null; PsiType type = JavaPsiFacade.getElementFactory(variable.getProject()).createType(variableResolved, targetSubstitutor); if (variableType.equals(type)) return null; return type; } private static class CastQuickFix extends InspectionGadgetsFix { private final String myTargetType; private CastQuickFix(String type) { myTargetType = type; } @Override public @NotNull String getName() { return JavaBundle.message("raw.variable.type.can.be.generic.cast.quickfix", myTargetType); } @Override public @NotNull String getFamilyName() { return JavaBundle.message("raw.variable.type.can.be.generic.cast.quickfix.family"); } @Override protected void doFix(Project project, ProblemDescriptor descriptor) { PsiTypeElement cast = PsiTreeUtil.getNonStrictParentOfType(descriptor.getStartElement(), PsiTypeElement.class); if (cast == null) return; CodeStyleManager.getInstance(project).reformat(new CommentTracker().replace(cast, myTargetType)); } } private static class RawTypeCanBeGenericFix extends InspectionGadgetsFix { private final @IntentionName String myName; RawTypeCanBeGenericFix(@NotNull @IntentionName String name) { myName = name; } @NotNull @Override public String getName() { return myName; } @NotNull @Override public String getFamilyName() { return JavaBundle.message("raw.variable.type.can.be.generic.family.quickfix"); } @Override public boolean startInWriteAction() { return false; } @Override protected void doFix(Project project, ProblemDescriptor descriptor) { final PsiElement element = descriptor.getStartElement().getParent(); if (element instanceof PsiVariable) { final PsiVariable variable = (PsiVariable)element; final PsiType type = getSuggestedType(variable); if (type != null) { final TypeMigrationRules rules = new TypeMigrationRules(project); rules.setBoundScope(PsiSearchHelper.getInstance(project).getUseScope(variable)); TypeMigrationProcessor.runHighlightingTypeMigration(project, null, rules, variable, type, false, true); } } } } }
{ "content_hash": "6129c78e5a343444128d855e9c70e229", "timestamp": "", "source": "github", "line_count": 384, "max_line_length": 158, "avg_line_length": 41.885416666666664, "alnum_prop": 0.7154314847052972, "repo_name": "smmribeiro/intellij-community", "id": "c3ce13c12534be01142c8f2825a87e0c696ecf5c", "size": "16084", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "java/java-impl-inspections/src/com/intellij/codeInspection/miscGenerics/RawUseOfParameterizedTypeInspection.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
import * as React from 'react'; import { Link } from 'react-router-dom'; import AppBar from 'material-ui/AppBar'; import Toolbar from 'material-ui/Toolbar'; import Drawer from 'material-ui/Drawer'; import List, { ListItem, ListItemIcon, ListItemText } from 'material-ui/List'; import MenuIcon from 'material-ui-icons/Menu'; import LibraryMusic from 'material-ui-icons/LibraryMusic'; import Settings from 'material-ui-icons/Settings'; import { Root, MenuButton, FlexTypo, StyledLink, DrawerContainer } from './styles'; import Search from 'components/Search'; interface IProps extends React.Props<NavBar> { title: string; } interface IState { drawerOpen: boolean; } export default class NavBar extends React.PureComponent<IProps, IState> { constructor(props: IProps) { super(props); this.state = { drawerOpen: false, }; } toggleDrawer = () => { this.setState({ drawerOpen: !this.state.drawerOpen, }); } render() { return ( <Root> <AppBar position="static" color="primary"> <Toolbar> <MenuButton color="contrast" aria-label="Menu" onClick={this.toggleDrawer}> <MenuIcon /> </MenuButton> {/* Side drawer */} <Drawer open={this.state.drawerOpen} onClose={this.toggleDrawer}> <DrawerContainer tabIndex={0} role="button" onClick={this.toggleDrawer} onKeyDown={this.toggleDrawer} > <List> <StyledLink to="/"> <ListItem button> <ListItemIcon> <LibraryMusic /> </ListItemIcon> <ListItemText primary="Listen" /> </ListItem> </StyledLink> <StyledLink to="/settings"> <ListItem button> <ListItemIcon> <Settings /> </ListItemIcon> <ListItemText primary="Settings" /> </ListItem> </StyledLink> </List> </DrawerContainer> </Drawer> <FlexTypo type="title" color="inherit"> <StyledLink to="/"> {this.props.title} </StyledLink> </FlexTypo> <Search /> </Toolbar> </AppBar> </Root> ); } }
{ "content_hash": "8c069358248e296c88855b4caec72bc5", "timestamp": "", "source": "github", "line_count": 90, "max_line_length": 87, "avg_line_length": 27.877777777777776, "alnum_prop": 0.5173375846950976, "repo_name": "subnomo/tubetop", "id": "b0336b9d1b055ec931b8ca3d105cd0bf1b58c491", "size": "2509", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/renderer/components/NavBar/index.tsx", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "862" }, { "name": "JavaScript", "bytes": "1721" }, { "name": "TypeScript", "bytes": "114915" } ], "symlink_target": "" }
Now that you have fileToCin [Primer](Primer.md) and learned how to write tests using Google Test, it's time to learn some new tricks. This document will show you more assertions as well as how to construct complex failure messages, propagate fatal failures, reuse and speed up your test fixtures, and use various flags with your tests. # More Assertions # This section covers some less frequently used, but still significant, assertions. ## Explicit Success and Failure ## These three assertions do not actually test a value or expression. Instead, they generate a success or failure directly. Like the macros that actually perform a test, you may stream a custom failure message into the them. | `SUCCEED();` | |:-------------| Generates a success. This does NOT make the overall test succeed. A test is considered successful only if none of its assertions fail during its execution. Note: `SUCCEED()` is purely documentary and currently doesn't generate any user-visible output. However, we may add `SUCCEED()` messages to Google Test's output in the future. | `FAIL();` | `ADD_FAILURE();` | `ADD_FAILURE_AT("`_file\_path_`", `_line\_number_`);` | |:-----------|:-----------------|:------------------------------------------------------| `FAIL()` generates a fatal failure, while `ADD_FAILURE()` and `ADD_FAILURE_AT()` generate a nonfatal failure. These are useful when control flow, rather than a Boolean expression, deteremines the test's success or failure. For example, you might want to write something like: ``` switch(expression) { case 1: ... some checks ... case 2: ... some other checks ... default: FAIL() << "We shouldn't get here."; } ``` Note: you can only use `FAIL()` in functions that return `void`. See the [Assertion Placement section](#assertion-placement) for more information. _Availability_: Linux, Windows, Mac. ## Exception Assertions ## These are for verifying that a piece of code throws (or does not throw) an exception of the given type: | **Fatal assertion** | **Nonfatal assertion** | **Verifies** | |:--------------------|:-----------------------|:-------------| | `ASSERT_THROW(`_statement_, _exception\_type_`);` | `EXPECT_THROW(`_statement_, _exception\_type_`);` | _statement_ throws an exception of the given type | | `ASSERT_ANY_THROW(`_statement_`);` | `EXPECT_ANY_THROW(`_statement_`);` | _statement_ throws an exception of any type | | `ASSERT_NO_THROW(`_statement_`);` | `EXPECT_NO_THROW(`_statement_`);` | _statement_ doesn't throw any exception | Examples: ``` ASSERT_THROW(Foo(5), bar_exception); EXPECT_NO_THROW({ int n = 5; Bar(&n); }); ``` _Availability_: Linux, Windows, Mac; since version 1.1.0. ## Predicate Assertions for Better Error Messages ## Even though Google Test has a rich set of assertions, they can never be complete, as it's impossible (nor a good idea) to anticipate all the scenarios a user might run into. Therefore, sometimes a user has to use `EXPECT_TRUE()` to check a complex expression, for lack of a better macro. This has the problem of not showing you the values of the parts of the expression, making it hard to understand what went wrong. As a workaround, some users choose to construct the failure message by themselves, streaming it into `EXPECT_TRUE()`. However, this is awkward especially when the expression has side-effects or is expensive to evaluate. Google Test gives you three different options to solve this problem: ### Using an Existing Boolean Function ### If you already have a function or a functor that returns `bool` (or a type that can be implicitly converted to `bool`), you can use it in a _predicate assertion_ to get the function arguments printed for free: | **Fatal assertion** | **Nonfatal assertion** | **Verifies** | |:--------------------|:-----------------------|:-------------| | `ASSERT_PRED1(`_pred1, val1_`);` | `EXPECT_PRED1(`_pred1, val1_`);` | _pred1(val1)_ returns true | | `ASSERT_PRED2(`_pred2, val1, val2_`);` | `EXPECT_PRED2(`_pred2, val1, val2_`);` | _pred2(val1, val2)_ returns true | | ... | ... | ... | In the above, _predn_ is an _n_-ary predicate function or functor, where _val1_, _val2_, ..., and _valn_ are its arguments. The assertion succeeds if the predicate returns `true` when applied to the given arguments, and fails otherwise. When the assertion fails, it prints the value of each argument. In either case, the arguments are evaluated exactly once. Here's an example. Given ``` // Returns true iff m and n have no common divisors except 1. bool MutuallyPrime(int m, int n) { ... } const int a = 3; const int b = 4; const int c = 10; ``` the assertion `EXPECT_PRED2(MutuallyPrime, a, b);` will succeed, while the assertion `EXPECT_PRED2(MutuallyPrime, b, c);` will fail with the message <pre> !MutuallyPrime(b, c) is false, where<br> b is 4<br> c is 10<br> </pre> **Notes:** 1. If you see a compiler error "no matching function to call" when using `ASSERT_PRED*` or `EXPECT_PRED*`, please see [this FAQ](FAQ.md#the-compiler-complains-no-matching-function-to-call-when-i-use-assert_predn-how-do-i-fix-it) for how to resolve it. 1. Currently we only provide predicate assertions of arity <= 5. If you need a higher-arity assertion, let us know. _Availability_: Linux, Windows, Mac ### Using a Function That Returns an AssertionResult ### While `EXPECT_PRED*()` and friends are handy for a quick job, the syntax is not satisfactory: you have to use different macros for different arities, and it feels more like Lisp than C++. The `::testing::AssertionResult` class solves this problem. An `AssertionResult` object represents the result of an assertion (whether it's a success or a failure, and an associated message). You can create an `AssertionResult` using one of these factory functions: ``` namespace testing { // Returns an AssertionResult object to indicate that an assertion has // succeeded. AssertionResult AssertionSuccess(); // Returns an AssertionResult object to indicate that an assertion has // failed. AssertionResult AssertionFailure(); } ``` You can then use the `<<` operator to stream messages to the `AssertionResult` object. To provide more readable messages in Boolean assertions (e.g. `EXPECT_TRUE()`), write a predicate function that returns `AssertionResult` instead of `bool`. For example, if you define `IsEven()` as: ``` ::testing::AssertionResult IsEven(int n) { if ((n % 2) == 0) return ::testing::AssertionSuccess(); else return ::testing::AssertionFailure() << n << " is odd"; } ``` instead of: ``` bool IsEven(int n) { return (n % 2) == 0; } ``` the failed assertion `EXPECT_TRUE(IsEven(Fib(4)))` will print: <pre> Value of: IsEven(Fib(4))<br> Actual: false (*3 is odd*)<br> Expected: true<br> </pre> instead of a more opaque <pre> Value of: IsEven(Fib(4))<br> Actual: false<br> Expected: true<br> </pre> If you want informative messages in `EXPECT_FALSE` and `ASSERT_FALSE` as well, and are fine with making the predicate slower in the success case, you can supply a success message: ``` ::testing::AssertionResult IsEven(int n) { if ((n % 2) == 0) return ::testing::AssertionSuccess() << n << " is even"; else return ::testing::AssertionFailure() << n << " is odd"; } ``` Then the statement `EXPECT_FALSE(IsEven(Fib(6)))` will print <pre> Value of: IsEven(Fib(6))<br> Actual: true (8 is even)<br> Expected: false<br> </pre> _Availability_: Linux, Windows, Mac; since version 1.4.1. ### Using a Predicate-Formatter ### If you find the default message generated by `(ASSERT|EXPECT)_PRED*` and `(ASSERT|EXPECT)_(TRUE|FALSE)` unsatisfactory, or some arguments to your predicate do not support streaming to `ostream`, you can instead use the following _predicate-formatter assertions_ to _fully_ customize how the message is formatted: | **Fatal assertion** | **Nonfatal assertion** | **Verifies** | |:--------------------|:-----------------------|:-------------| | `ASSERT_PRED_FORMAT1(`_pred\_format1, val1_`);` | `EXPECT_PRED_FORMAT1(`_pred\_format1, val1_`);` | _pred\_format1(val1)_ is successful | | `ASSERT_PRED_FORMAT2(`_pred\_format2, val1, val2_`);` | `EXPECT_PRED_FORMAT2(`_pred\_format2, val1, val2_`);` | _pred\_format2(val1, val2)_ is successful | | `...` | `...` | `...` | The difference between this and the previous two groups of macros is that instead of a predicate, `(ASSERT|EXPECT)_PRED_FORMAT*` take a _predicate-formatter_ (_pred\_formatn_), which is a function or functor with the signature: `::testing::AssertionResult PredicateFormattern(const char* `_expr1_`, const char* `_expr2_`, ... const char* `_exprn_`, T1 `_val1_`, T2 `_val2_`, ... Tn `_valn_`);` where _val1_, _val2_, ..., and _valn_ are the values of the predicate arguments, and _expr1_, _expr2_, ..., and _exprn_ are the corresponding expressions as they appear in the source code. The types `T1`, `T2`, ..., and `Tn` can be either value types or reference types. For example, if an argument has type `Foo`, you can declare it as either `Foo` or `const Foo&`, whichever is appropriate. A predicate-formatter returns a `::testing::AssertionResult` object to indicate whether the assertion has succeeded or not. The only way to create such an object is to call one of these factory functions: As an example, let's improve the failure message in the previous example, which uses `EXPECT_PRED2()`: ``` // Returns the smallest prime common divisor of m and n, // or 1 when m and n are mutually prime. int SmallestPrimeCommonDivisor(int m, int n) { ... } // A predicate-formatter for asserting that two integers are mutually prime. ::testing::AssertionResult AssertMutuallyPrime(const char* m_expr, const char* n_expr, int m, int n) { if (MutuallyPrime(m, n)) return ::testing::AssertionSuccess(); return ::testing::AssertionFailure() << m_expr << " and " << n_expr << " (" << m << " and " << n << ") are not mutually prime, " << "as they have a common divisor " << SmallestPrimeCommonDivisor(m, n); } ``` With this predicate-formatter, we can use ``` EXPECT_PRED_FORMAT2(AssertMutuallyPrime, b, c); ``` to generate the message <pre> b and c (4 and 10) are not mutually prime, as they have a common divisor 2.<br> </pre> As you may have realized, many of the assertions we introduced earlier are special cases of `(EXPECT|ASSERT)_PRED_FORMAT*`. In fact, most of them are indeed defined using `(EXPECT|ASSERT)_PRED_FORMAT*`. _Availability_: Linux, Windows, Mac. ## Floating-Point Comparison ## Comparing floating-point numbers is tricky. Due to round-off errors, it is very unlikely that two floating-points will match exactly. Therefore, `ASSERT_EQ` 's naive comparison usually doesn't work. And since floating-points can have a wide value range, no single fixed error bound works. It's better to compare by a fixed relative error bound, except for values close to 0 due to the loss of precision there. In general, for floating-point comparison to make sense, the user needs to carefully choose the error bound. If they don't want or care to, comparing in terms of Units in the Last Place (ULPs) is a good default, and Google Test provides assertions to do this. Full details about ULPs are quite long; if you want to learn more, see [this article on float comparison](http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm). ### Floating-Point Macros ### | **Fatal assertion** | **Nonfatal assertion** | **Verifies** | |:--------------------|:-----------------------|:-------------| | `ASSERT_FLOAT_EQ(`_val1, val2_`);` | `EXPECT_FLOAT_EQ(`_val1, val2_`);` | the two `float` values are almost equal | | `ASSERT_DOUBLE_EQ(`_val1, val2_`);` | `EXPECT_DOUBLE_EQ(`_val1, val2_`);` | the two `double` values are almost equal | By "almost equal", we mean the two values are within 4 ULP's from each other. The following assertions allow you to choose the acceptable error bound: | **Fatal assertion** | **Nonfatal assertion** | **Verifies** | |:--------------------|:-----------------------|:-------------| | `ASSERT_NEAR(`_val1, val2, abs\_error_`);` | `EXPECT_NEAR`_(val1, val2, abs\_error_`);` | the difference between _val1_ and _val2_ doesn't exceed the given absolute error | _Availability_: Linux, Windows, Mac. ### Floating-Point Predicate-Format Functions ### Some floating-point operations are useful, but not that often used. In order to avoid an explosion of new macros, we provide them as predicate-format functions that can be used in predicate assertion macros (e.g. `EXPECT_PRED_FORMAT2`, etc). ``` EXPECT_PRED_FORMAT2(::testing::FloatLE, val1, val2); EXPECT_PRED_FORMAT2(::testing::DoubleLE, val1, val2); ``` Verifies that _val1_ is less than, or almost equal to, _val2_. You can replace `EXPECT_PRED_FORMAT2` in the above table with `ASSERT_PRED_FORMAT2`. _Availability_: Linux, Windows, Mac. ## Windows HRESULT assertions ## These assertions test for `HRESULT` success or failure. | **Fatal assertion** | **Nonfatal assertion** | **Verifies** | |:--------------------|:-----------------------|:-------------| | `ASSERT_HRESULT_SUCCEEDED(`_expression_`);` | `EXPECT_HRESULT_SUCCEEDED(`_expression_`);` | _expression_ is a success `HRESULT` | | `ASSERT_HRESULT_FAILED(`_expression_`);` | `EXPECT_HRESULT_FAILED(`_expression_`);` | _expression_ is a failure `HRESULT` | The generated output contains the human-readable error message associated with the `HRESULT` code returned by _expression_. You might use them like this: ``` CComPtr shell; ASSERT_HRESULT_SUCCEEDED(shell.CoCreateInstance(L"Shell.Application")); CComVariant empty; ASSERT_HRESULT_SUCCEEDED(shell->ShellExecute(CComBSTR(url), empty, empty, empty, empty)); ``` _Availability_: Windows. ## Type Assertions ## You can call the function ``` ::testing::StaticAssertTypeEq<T1, T2>(); ``` to assert that types `T1` and `T2` are the same. The function does nothing if the assertion is satisfied. If the types are different, the function call will fail to compile, and the compiler error message will likely (depending on the compiler) show you the actual values of `T1` and `T2`. This is mainly useful inside template code. _Caveat:_ When used inside a member function of a class template or a function template, `StaticAssertTypeEq<T1, T2>()` is effective _only if_ the function is instantiated. For example, given: ``` template <typename T> class Foo { public: void Bar() { ::testing::StaticAssertTypeEq<int, T>(); } }; ``` the code: ``` void Test1() { Foo<bool> foo; } ``` will _not_ generate a compiler error, as `Foo<bool>::Bar()` is never actually instantiated. Instead, you need: ``` void Test2() { Foo<bool> foo; foo.Bar(); } ``` to cause a compiler error. _Availability:_ Linux, Windows, Mac; since version 1.3.0. ## Assertion Placement ## You can use assertions in any C++ function. In particular, it doesn't have to be a method of the test fixture class. The one constraint is that assertions that generate a fatal failure (`FAIL*` and `ASSERT_*`) can only be used in void-returning functions. This is a consequence of Google Test not using exceptions. By placing it in a non-void function you'll get a confusing compile error like `"error: void value not ignored as it ought to be"`. If you need to use assertions in a function that returns non-void, one option is to make the function return the value in an out parameter instead. For example, you can rewrite `T2 Foo(T1 x)` to `void Foo(T1 x, T2* result)`. You need to make sure that `*result` contains some sensible value even when the function returns prematurely. As the function now returns `void`, you can use any assertion inside of it. If changing the function's type is not an option, you should just use assertions that generate non-fatal failures, such as `ADD_FAILURE*` and `EXPECT_*`. _Note_: Constructors and destructors are not considered void-returning functions, according to the C++ language specification, and so you may not use fatal assertions in them. You'll get a compilation error if you try. A simple workaround is to transfer the entire body of the constructor or destructor to a private void-returning method. However, you should be aware that a fatal assertion failure in a constructor does not terminate the current test, as your intuition might suggest; it merely returns from the constructor early, possibly leaving your object in a partially-constructed state. Likewise, a fatal assertion failure in a destructor may leave your object in a partially-destructed state. Use assertions carefully in these situations! # Teaching Google Test How to Print Your Values # When a test assertion such as `EXPECT_EQ` fails, Google Test prints the argument values to help you debug. It does this using a user-extensible value printer. This printer knows how to print built-in C++ types, native arrays, STL containers, and any type that supports the `<<` operator. For other types, it prints the raw bytes in the value and hopes that you the user can figure it out. As mentioned earlier, the printer is _extensible_. That means you can teach it to do a better job at printing your particular type than to dump the bytes. To do that, define `<<` for your type: ``` #include <iostream> namespace foo { class Bar { ... }; // We want Google Test to be able to print instances of this. // It's important that the << operator is defined in the SAME // namespace that defines Bar. C++'s look-up rules rely on that. ::std::ostream& operator<<(::std::ostream& os, const Bar& bar) { return os << bar.DebugString(); // whatever needed to print bar to os } } // namespace foo ``` Sometimes, this might not be an option: your team may consider it bad style to have a `<<` operator for `Bar`, or `Bar` may already have a `<<` operator that doesn't do what you want (and you cannot change it). If so, you can instead define a `PrintTo()` function like this: ``` #include <iostream> namespace foo { class Bar { ... }; // It's important that PrintTo() is defined in the SAME // namespace that defines Bar. C++'s look-up rules rely on that. void PrintTo(const Bar& bar, ::std::ostream* os) { *os << bar.DebugString(); // whatever needed to print bar to os } } // namespace foo ``` If you have defined both `<<` and `PrintTo()`, the latter will be used when Google Test is concerned. This allows you to customize how the value appears in Google Test's output without affecting code that relies on the behavior of its `<<` operator. If you want to print a value `x` using Google Test's value printer yourself, just call `::testing::PrintToString(`_x_`)`, which returns an `std::string`: ``` vector<pair<Bar, int> > bar_ints = GetBarIntVector(); EXPECT_TRUE(IsCorrectBarIntVector(bar_ints)) << "bar_ints = " << ::testing::PrintToString(bar_ints); ``` # Death Tests # In many applications, there are assertions that can cause application failure if a condition is not met. These sanity checks, which ensure that the program is in a known good state, are there to fail at the earliest possible time after some program state is corrupted. If the assertion checks the wrong condition, then the program may proceed in an erroneous state, which could lead to memory corruption, security holes, or worse. Hence it is vitally important to test that such assertion statements work as expected. Since these precondition checks cause the processes to die, we call such tests _death tests_. More generally, any test that checks that a program terminates (except by throwing an exception) in an expected fashion is also a death test. Note that if a piece of code throws an exception, we don't consider it "death" for the purpose of death tests, as the caller of the code could catch the exception and avoid the crash. If you want to verify exceptions thrown by your code, see [Exception Assertions](#exception-assertions). If you want to test `EXPECT_*()/ASSERT_*()` failures in your test code, see [Catching Failures](#catching-failures). ## How to Write a Death Test ## Google Test has the following macros to support death tests: | **Fatal assertion** | **Nonfatal assertion** | **Verifies** | |:--------------------|:-----------------------|:-------------| | `ASSERT_DEATH(`_statement, regex_`);` | `EXPECT_DEATH(`_statement, regex_`);` | _statement_ crashes with the given error | | `ASSERT_DEATH_IF_SUPPORTED(`_statement, regex_`);` | `EXPECT_DEATH_IF_SUPPORTED(`_statement, regex_`);` | if death tests are supported, verifies that _statement_ crashes with the given error; otherwise verifies nothing | | `ASSERT_EXIT(`_statement, predicate, regex_`);` | `EXPECT_EXIT(`_statement, predicate, regex_`);` |_statement_ exits with the given error and its exit code matches _predicate_ | where _statement_ is a statement that is expected to cause the process to die, _predicate_ is a function or function object that evaluates an integer exit status, and _regex_ is a regular expression that the stderr output of _statement_ is expected to match. Note that _statement_ can be _any valid statement_ (including _compound statement_) and doesn't have to be an expression. As usual, the `ASSERT` variants abort the current test function, while the `EXPECT` variants do not. **Note:** We use the word "crash" here to mean that the process terminates with a _non-zero_ exit status code. There are two possibilities: either the process has called `exit()` or `_exit()` with a non-zero value, or it may be killed by a signal. This means that if _statement_ terminates the process with a 0 exit code, it is _not_ considered a crash by `EXPECT_DEATH`. Use `EXPECT_EXIT` instead if this is the case, or if you want to restrict the exit code more precisely. A predicate here must accept an `int` and return a `bool`. The death test succeeds only if the predicate returns `true`. Google Test defines a few predicates that handle the most common cases: ``` ::testing::ExitedWithCode(exit_code) ``` This expression is `true` if the program exited normally with the given exit code. ``` ::testing::KilledBySignal(signal_number) // Not available on Windows. ``` This expression is `true` if the program was killed by the given signal. The `*_DEATH` macros are convenient wrappers for `*_EXIT` that use a predicate that verifies the process' exit code is non-zero. Note that a death test only cares about three things: 1. does _statement_ abort or exit the process? 1. (in the case of `ASSERT_EXIT` and `EXPECT_EXIT`) does the exit status satisfy _predicate_? Or (in the case of `ASSERT_DEATH` and `EXPECT_DEATH`) is the exit status non-zero? And 1. does the stderr output match _regex_? In particular, if _statement_ generates an `ASSERT_*` or `EXPECT_*` failure, it will **not** cause the death test to fail, as Google Test assertions don't abort the process. To write a death test, simply use one of the above macros inside your test function. For example, ``` TEST(MyDeathTest, Foo) { // This death test uses a compound statement. ASSERT_DEATH({ int n = 5; Foo(&n); }, "Error on line .* of Foo()"); } TEST(MyDeathTest, NormalExit) { EXPECT_EXIT(NormalExit(), ::testing::ExitedWithCode(0), "Success"); } TEST(MyDeathTest, KillMyself) { EXPECT_EXIT(KillMyself(), ::testing::KilledBySignal(SIGKILL), "Sending myself unblockable signal"); } ``` verifies that: * calling `Foo(5)` causes the process to die with the given error message, * calling `NormalExit()` causes the process to print `"Success"` to stderr and exit with exit code 0, and * calling `KillMyself()` kills the process with signal `SIGKILL`. The test function body may contain other assertions and statements as well, if necessary. _Important:_ We strongly recommend you to follow the convention of naming your test case (not test) `*DeathTest` when it contains a death test, as demonstrated in the above example. The `Death Tests And Threads` section below explains why. If a test fixture class is shared by normal tests and death tests, you can use typedef to introduce an alias for the fixture class and avoid duplicating its code: ``` class FooTest : public ::testing::Test { ... }; typedef FooTest FooDeathTest; TEST_F(FooTest, DoesThis) { // normal test } TEST_F(FooDeathTest, DoesThat) { // death test } ``` _Availability:_ Linux, Windows (requires MSVC 8.0 or above), Cygwin, and Mac (the latter three are supported since v1.3.0). `(ASSERT|EXPECT)_DEATH_IF_SUPPORTED` are new in v1.4.0. ## Regular Expression Syntax ## On POSIX systems (e.g. Linux, Cygwin, and Mac), Google Test uses the [POSIX extended regular expression](http://www.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap09.html#tag_09_04) syntax in death tests. To learn about this syntax, you may want to fileToCin this [Wikipedia entry](http://en.wikipedia.org/wiki/Regular_expression#POSIX_Extended_Regular_Expressions). On Windows, Google Test uses its own simple regular expression implementation. It lacks many features you can find in POSIX extended regular expressions. For example, we don't support union (`"x|y"`), grouping (`"(xy)"`), brackets (`"[xy]"`), and repetition count (`"x{5,7}"`), among others. Below is what we do support (Letter `A` denotes a literal character, period (`.`), or a single `\\` escape sequence; `x` and `y` denote regular expressions.): | `c` | matches any literal character `c` | |:----|:----------------------------------| | `\\d` | matches any decimal digit | | `\\D` | matches any character that's not a decimal digit | | `\\f` | matches `\f` | | `\\n` | matches `\n` | | `\\r` | matches `\r` | | `\\s` | matches any ASCII whitespace, including `\n` | | `\\S` | matches any character that's not a whitespace | | `\\t` | matches `\t` | | `\\v` | matches `\v` | | `\\w` | matches any letter, `_`, or decimal digit | | `\\W` | matches any character that `\\w` doesn't match | | `\\c` | matches any literal character `c`, which must be a punctuation | | `\\.` | matches the `.` character | | `.` | matches any single character except `\n` | | `A?` | matches 0 or 1 occurrences of `A` | | `A*` | matches 0 or many occurrences of `A` | | `A+` | matches 1 or many occurrences of `A` | | `^` | matches the beginning of a string (not that of each line) | | `$` | matches the end of a string (not that of each line) | | `xy` | matches `x` followed by `y` | To help you determine which capability is available on your system, Google Test defines macro `GTEST_USES_POSIX_RE=1` when it uses POSIX extended regular expressions, or `GTEST_USES_SIMPLE_RE=1` when it uses the simple version. If you want your death tests to work in both cases, you can either `#if` on these macros or use the more limited syntax only. ## How It Works ## Under the hood, `ASSERT_EXIT()` spawns a new process and executes the death test statement in that process. The details of of how precisely that happens depend on the platform and the variable `::testing::GTEST_FLAG(death_test_style)` (which is initialized from the command-line flag `--gtest_death_test_style`). * On POSIX systems, `fork()` (or `clone()` on Linux) is used to spawn the child, after which: * If the variable's value is `"fast"`, the death test statement is immediately executed. * If the variable's value is `"threadsafe"`, the child process re-executes the unit test binary just as it was originally invoked, but with some extra flags to cause just the single death test under consideration to be run. * On Windows, the child is spawned using the `CreateProcess()` API, and re-executes the binary to cause just the single death test under consideration to be run - much like the `threadsafe` mode on POSIX. Other values for the variable are illegal and will cause the death test to fail. Currently, the flag's default value is `"fast"`. However, we reserve the right to change it in the future. Therefore, your tests should not depend on this. In either case, the parent process waits for the child process to complete, and checks that 1. the child's exit status satisfies the predicate, and 1. the child's stderr matches the regular expression. If the death test statement runs to completion without dying, the child process will nonetheless terminate, and the assertion fails. ## Death Tests And Threads ## The reason for the two death test styles has to do with thread safety. Due to well-known problems with forking in the presence of threads, death tests should be run in a single-threaded context. Sometimes, however, it isn't feasible to arrange that kind of environment. For example, statically-initialized modules may start threads before main is ever reached. Once threads have been created, it may be difficult or impossible to clean them up. Google Test has three features intended to raise awareness of threading issues. 1. A warning is emitted if multiple threads are running when a death test is encountered. 1. Test cases with a name ending in "DeathTest" are run before all other tests. 1. It uses `clone()` instead of `fork()` to spawn the child process on Linux (`clone()` is not available on Cygwin and Mac), as `fork()` is more likely to cause the child to hang when the parent process has multiple threads. It's perfectly fine to create threads inside a death test statement; they are executed in a separate process and cannot affect the parent. ## Death Test Styles ## The "threadsafe" death test style was introduced in order to help mitigate the risks of testing in a possibly multithreaded environment. It trades increased test execution time (potentially dramatically so) for improved thread safety. We suggest using the faster, default "fast" style unless your test has specific problems with it. You can choose a particular style of death tests by setting the flag programmatically: ``` ::testing::FLAGS_gtest_death_test_style = "threadsafe"; ``` You can do this in `main()` to set the style for all death tests in the binary, or in individual tests. Recall that flags are saved before running each test and restored afterwards, so you need not do that yourself. For example: ``` TEST(MyDeathTest, TestOne) { ::testing::FLAGS_gtest_death_test_style = "threadsafe"; // This test is run in the "threadsafe" style: ASSERT_DEATH(ThisShouldDie(), ""); } TEST(MyDeathTest, TestTwo) { // This test is run in the "fast" style: ASSERT_DEATH(ThisShouldDie(), ""); } int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); ::testing::FLAGS_gtest_death_test_style = "fast"; return RUN_ALL_TESTS(); } ``` ## Caveats ## The _statement_ argument of `ASSERT_EXIT()` can be any valid C++ statement. If it leaves the current function via a `return` statement or by throwing an exception, the death test is considered to have failed. Some Google Test macros may return from the current function (e.g. `ASSERT_TRUE()`), so be sure to avoid them in _statement_. Since _statement_ runs in the child process, any in-memory side effect (e.g. modifying a variable, releasing memory, etc) it causes will _not_ be observable in the parent process. In particular, if you release memory in a death test, your program will fail the heap check as the parent process will never see the memory reclaimed. To solve this problem, you can 1. try not to free memory in a death test; 1. free the memory again in the parent process; or 1. do not use the heap checker in your program. Due to an implementation detail, you cannot place multiple death test assertions on the same line; otherwise, compilation will fail with an unobvious error message. Despite the improved thread safety afforded by the "threadsafe" style of death test, thread problems such as deadlock are still possible in the presence of handlers registered with `pthread_atfork(3)`. # Using Assertions in Sub-routines # ## Adding Traces to Assertions ## If a test sub-routine is called from several places, when an assertion inside it fails, it can be hard to tell which invocation of the sub-routine the failure is from. You can alleviate this problem using extra logging or custom failure messages, but that usually clutters up your tests. A better solution is to use the `SCOPED_TRACE` macro: | `SCOPED_TRACE(`_message_`);` | |:-----------------------------| where _message_ can be anything streamable to `std::ostream`. This macro will cause the current file name, line number, and the given message to be added in every failure message. The effect will be undone when the control leaves the current lexical scope. For example, ``` 10: void Sub1(int n) { 11: EXPECT_EQ(1, Bar(n)); 12: EXPECT_EQ(2, Bar(n + 1)); 13: } 14: 15: TEST(FooTest, Bar) { 16: { 17: SCOPED_TRACE("A"); // This trace point will be included in 18: // every failure in this scope. 19: Sub1(1); 20: } 21: // Now it won't. 22: Sub1(9); 23: } ``` could result in messages like these: ``` path/to/foo_test.cc:11: Failure Value of: Bar(n) Expected: 1 Actual: 2 Trace: path/to/foo_test.cc:17: A path/to/foo_test.cc:12: Failure Value of: Bar(n + 1) Expected: 2 Actual: 3 ``` Without the trace, it would've been difficult to know which invocation of `Sub1()` the two failures come from respectively. (You could add an extra message to each assertion in `Sub1()` to indicate the value of `n`, but that's tedious.) Some tips on using `SCOPED_TRACE`: 1. With a suitable message, it's often enough to use `SCOPED_TRACE` at the beginning of a sub-routine, instead of at each call site. 1. When calling sub-routines inside a loop, make the loop iterator part of the message in `SCOPED_TRACE` such that you can know which iteration the failure is from. 1. Sometimes the line number of the trace point is enough for identifying the particular invocation of a sub-routine. In this case, you don't have to choose a unique message for `SCOPED_TRACE`. You can simply use `""`. 1. You can use `SCOPED_TRACE` in an inner scope when there is one in the outer scope. In this case, all active trace points will be included in the failure messages, in reverse order they are encountered. 1. The trace dump is clickable in Emacs' compilation buffer - hit return on a line number and you'll be taken to that line in the source file! _Availability:_ Linux, Windows, Mac. ## Propagating Fatal Failures ## A common pitfall when using `ASSERT_*` and `FAIL*` is not understanding that when they fail they only abort the _current function_, not the entire test. For example, the following test will segfault: ``` void Subroutine() { // Generates a fatal failure and aborts the current function. ASSERT_EQ(1, 2); // The following won't be executed. ... } TEST(FooTest, Bar) { Subroutine(); // The intended behavior is for the fatal failure // in Subroutine() to abort the entire test. // The actual behavior: the function goes on after Subroutine() returns. int* p = NULL; *p = 3; // Segfault! } ``` Since we don't use exceptions, it is technically impossible to implement the intended behavior here. To alleviate this, Google Test provides two solutions. You could use either the `(ASSERT|EXPECT)_NO_FATAL_FAILURE` assertions or the `HasFatalFailure()` function. They are described in the following two subsections. ### Asserting on Subroutines ### As shown above, if your test calls a subroutine that has an `ASSERT_*` failure in it, the test will continue after the subroutine returns. This may not be what you want. Often people want fatal failures to propagate like exceptions. For that Google Test offers the following macros: | **Fatal assertion** | **Nonfatal assertion** | **Verifies** | |:--------------------|:-----------------------|:-------------| | `ASSERT_NO_FATAL_FAILURE(`_statement_`);` | `EXPECT_NO_FATAL_FAILURE(`_statement_`);` | _statement_ doesn't generate any new fatal failures in the current thread. | Only failures in the thread that executes the assertion are checked to determine the result of this type of assertions. If _statement_ creates new threads, failures in these threads are ignored. Examples: ``` ASSERT_NO_FATAL_FAILURE(Foo()); int i; EXPECT_NO_FATAL_FAILURE({ i = Bar(); }); ``` _Availability:_ Linux, Windows, Mac. Assertions from multiple threads are currently not supported. ### Checking for Failures in the Current Test ### `HasFatalFailure()` in the `::testing::Test` class returns `true` if an assertion in the current test has suffered a fatal failure. This allows functions to catch fatal failures in a sub-routine and return early. ``` class Test { public: ... static bool HasFatalFailure(); }; ``` The typical usage, which basically simulates the behavior of a thrown exception, is: ``` TEST(FooTest, Bar) { Subroutine(); // Aborts if Subroutine() had a fatal failure. if (HasFatalFailure()) return; // The following won't be executed. ... } ``` If `HasFatalFailure()` is used outside of `TEST()` , `TEST_F()` , or a test fixture, you must add the `::testing::Test::` prefix, as in: ``` if (::testing::Test::HasFatalFailure()) return; ``` Similarly, `HasNonfatalFailure()` returns `true` if the current test has at least one non-fatal failure, and `HasFailure()` returns `true` if the current test has at least one failure of either kind. _Availability:_ Linux, Windows, Mac. `HasNonfatalFailure()` and `HasFailure()` are available since version 1.4.0. # Logging Additional Information # In your test code, you can call `RecordProperty("key", value)` to log additional information, where `value` can be either a string or an `int`. The _last_ value recorded for a key will be emitted to the XML output if you specify one. For example, the test ``` TEST_F(WidgetUsageTest, MinAndMaxWidgets) { RecordProperty("MaximumWidgets", ComputeMaxUsage()); RecordProperty("MinimumWidgets", ComputeMinUsage()); } ``` will output XML like this: ``` ... <testcase name="MinAndMaxWidgets" status="run" time="6" classname="WidgetUsageTest" MaximumWidgets="12" MinimumWidgets="9" /> ... ``` _Note_: * `RecordProperty()` is a static member of the `Test` class. Therefore it needs to be prefixed with `::testing::Test::` if used outside of the `TEST` body and the test fixture class. * `key` must be a valid XML attribute name, and cannot conflict with the ones already used by Google Test (`name`, `status`, `time`, `classname`, `type_param`, and `value_param`). * Calling `RecordProperty()` outside of the lifespan of a test is allowed. If it's called outside of a test but between a test case's `SetUpTestCase()` and `TearDownTestCase()` methods, it will be attributed to the XML element for the test case. If it's called outside of all test cases (e.g. in a test environment), it will be attributed to the top-level XML element. _Availability_: Linux, Windows, Mac. # Sharing Resources Between Tests in the Same Test Case # Google Test creates a new test fixture object for each test in order to make tests independent and easier to debug. However, sometimes tests use resources that are expensive to set up, making the one-copy-per-test model prohibitively expensive. If the tests don't change the resource, there's no harm in them sharing a single resource copy. So, in addition to per-test set-up/tear-down, Google Test also supports per-test-case set-up/tear-down. To use it: 1. In your test fixture class (say `FooTest` ), define as `static` some member variables to hold the shared resources. 1. In the same test fixture class, define a `static void SetUpTestCase()` function (remember not to spell it as **`SetupTestCase`** with a small `u`!) to set up the shared resources and a `static void TearDownTestCase()` function to tear them down. That's it! Google Test automatically calls `SetUpTestCase()` before running the _first test_ in the `FooTest` test case (i.e. before creating the first `FooTest` object), and calls `TearDownTestCase()` after running the _last test_ in it (i.e. after deleting the last `FooTest` object). In between, the tests can use the shared resources. Remember that the test order is undefined, so your code can't depend on a test preceding or following another. Also, the tests must either not modify the state of any shared resource, or, if they do modify the state, they must restore the state to its original value before passing control to the next test. Here's an example of per-test-case set-up and tear-down: ``` class FooTest : public ::testing::Test { protected: // Per-test-case set-up. // Called before the first test in this test case. // Can be omitted if not needed. static void SetUpTestCase() { shared_resource_ = new ...; } // Per-test-case tear-down. // Called after the last test in this test case. // Can be omitted if not needed. static void TearDownTestCase() { delete shared_resource_; shared_resource_ = NULL; } // You can define per-test set-up and tear-down logic as usual. virtual void SetUp() { ... } virtual void TearDown() { ... } // Some expensive resource shared by all tests. static T* shared_resource_; }; T* FooTest::shared_resource_ = NULL; TEST_F(FooTest, Test1) { ... you can refer to shared_resource here ... } TEST_F(FooTest, Test2) { ... you can refer to shared_resource here ... } ``` _Availability:_ Linux, Windows, Mac. # Global Set-Up and Tear-Down # Just as you can do set-up and tear-down at the test level and the test case level, you can also do it at the test program level. Here's how. First, you subclass the `::testing::Environment` class to define a test environment, which knows how to set-up and tear-down: ``` class Environment { public: virtual ~Environment() {} // Override this to define how to set up the environment. virtual void SetUp() {} // Override this to define how to tear down the environment. virtual void TearDown() {} }; ``` Then, you register an instance of your environment class with Google Test by calling the `::testing::AddGlobalTestEnvironment()` function: ``` Environment* AddGlobalTestEnvironment(Environment* env); ``` Now, when `RUN_ALL_TESTS()` is called, it first calls the `SetUp()` method of the environment object, then runs the tests if there was no fatal failures, and finally calls `TearDown()` of the environment object. It's OK to register multiple environment objects. In this case, their `SetUp()` will be called in the order they are registered, and their `TearDown()` will be called in the reverse order. Note that Google Test takes ownership of the registered environment objects. Therefore **do not delete them** by yourself. You should call `AddGlobalTestEnvironment()` before `RUN_ALL_TESTS()` is called, probably in `main()`. If you use `gtest_main`, you need to call this before `main()` starts for it to take effect. One way to do this is to define a global variable like this: ``` ::testing::Environment* const foo_env = ::testing::AddGlobalTestEnvironment(new FooEnvironment); ``` However, we strongly recommend you to write your own `main()` and call `AddGlobalTestEnvironment()` there, as relying on initialization of global variables makes the code harder to fileToCin and may cause problems when you register multiple environments from different translation units and the environments have dependencies among them (remember that the compiler doesn't guarantee the order in which global variables from different translation units are initialized). _Availability:_ Linux, Windows, Mac. # Value Parameterized Tests # _Value-parameterized tests_ allow you to test your code with different parameters without writing multiple copies of the same test. Suppose you write a test for your code and then realize that your code is affected by a presence of a Boolean command line flag. ``` TEST(MyCodeTest, TestFoo) { // A code to test foo(). } ``` Usually people factor their test code into a function with a Boolean parameter in such situations. The function sets the flag, then executes the testing code. ``` void TestFooHelper(bool flag_value) { flag = flag_value; // A code to test foo(). } TEST(MyCodeTest, TestFoo) { TestFooHelper(false); TestFooHelper(true); } ``` But this setup has serious drawbacks. First, when a test assertion fails in your tests, it becomes unclear what value of the parameter caused it to fail. You can stream a clarifying message into your `EXPECT`/`ASSERT` statements, but it you'll have to do it with all of them. Second, you have to add one such helper function per test. What if you have ten tests? Twenty? A hundred? Value-parameterized tests will let you write your test only once and then easily instantiate and run it with an arbitrary number of parameter values. Here are some other situations when value-parameterized tests come handy: * You want to test different implementations of an OO interface. * You want to test your code over various inputs (a.k.a. data-driven testing). This feature is easy to abuse, so please exercise your good sense when doing it! ## How to Write Value-Parameterized Tests ## To write value-parameterized tests, first you should define a fixture class. It must be derived from both `::testing::Test` and `::testing::WithParamInterface<T>` (the latter is a pure interface), where `T` is the type of your parameter values. For convenience, you can just derive the fixture class from `::testing::TestWithParam<T>`, which itself is derived from both `::testing::Test` and `::testing::WithParamInterface<T>`. `T` can be any copyable type. If it's a raw pointer, you are responsible for managing the lifespan of the pointed values. ``` class FooTest : public ::testing::TestWithParam<const char*> { // You can implement all the usual fixture class members here. // To access the test parameter, call GetParam() from class // TestWithParam<T>. }; // Or, when you want to add parameters to a pre-existing fixture class: class BaseTest : public ::testing::Test { ... }; class BarTest : public BaseTest, public ::testing::WithParamInterface<const char*> { ... }; ``` Then, use the `TEST_P` macro to define as many test patterns using this fixture as you want. The `_P` suffix is for "parameterized" or "pattern", whichever you prefer to think. ``` TEST_P(FooTest, DoesBlah) { // Inside a test, access the test parameter with the GetParam() method // of the TestWithParam<T> class: EXPECT_TRUE(foo.Blah(GetParam())); ... } TEST_P(FooTest, HasBlahBlah) { ... } ``` Finally, you can use `INSTANTIATE_TEST_CASE_P` to instantiate the test case with any set of parameters you want. Google Test defines a number of functions for generating test parameters. They return what we call (surprise!) _parameter generators_. Here is a summary of them, which are all in the `testing` namespace: | `Range(begin, end[, step])` | Yields values `{begin, begin+step, begin+step+step, ...}`. The values do not include `end`. `step` defaults to 1. | |:----------------------------|:------------------------------------------------------------------------------------------------------------------| | `Values(v1, v2, ..., vN)` | Yields values `{v1, v2, ..., vN}`. | | `ValuesIn(container)` and `ValuesIn(begin, end)` | Yields values from a C-style array, an STL-style container, or an iterator range `[begin, end)`. `container`, `begin`, and `end` can be expressions whose values are determined at run time. | | `Bool()` | Yields sequence `{false, true}`. | | `Combine(g1, g2, ..., gN)` | Yields all combinations (the Cartesian product for the math savvy) of the values generated by the `N` generators. This is only available if your system provides the `<tr1/tuple>` header. If you are sure your system does, and Google Test disagrees, you can override it by defining `GTEST_HAS_TR1_TUPLE=1`. See comments in [include/gtest/internal/gtest-port.h](../include/gtest/internal/gtest-port.h) for more information. | For more details, see the comments at the definitions of these functions in the [source code](../include/gtest/gtest-param-test.h). The following statement will instantiate tests from the `FooTest` test case each with parameter values `"meeny"`, `"miny"`, and `"moe"`. ``` INSTANTIATE_TEST_CASE_P(InstantiationName, FooTest, ::testing::Values("meeny", "miny", "moe")); ``` To distinguish different instances of the pattern (yes, you can instantiate it more than once), the first argument to `INSTANTIATE_TEST_CASE_P` is a prefix that will be added to the actual test case name. Remember to pick unique prefixes for different instantiations. The tests from the instantiation above will have these names: * `InstantiationName/FooTest.DoesBlah/0` for `"meeny"` * `InstantiationName/FooTest.DoesBlah/1` for `"miny"` * `InstantiationName/FooTest.DoesBlah/2` for `"moe"` * `InstantiationName/FooTest.HasBlahBlah/0` for `"meeny"` * `InstantiationName/FooTest.HasBlahBlah/1` for `"miny"` * `InstantiationName/FooTest.HasBlahBlah/2` for `"moe"` You can use these names in [--gtest\_filter](#running-a-subset-of-the-tests). This statement will instantiate all tests from `FooTest` again, each with parameter values `"cat"` and `"dog"`: ``` const char* pets[] = {"cat", "dog"}; INSTANTIATE_TEST_CASE_P(AnotherInstantiationName, FooTest, ::testing::ValuesIn(pets)); ``` The tests from the instantiation above will have these names: * `AnotherInstantiationName/FooTest.DoesBlah/0` for `"cat"` * `AnotherInstantiationName/FooTest.DoesBlah/1` for `"dog"` * `AnotherInstantiationName/FooTest.HasBlahBlah/0` for `"cat"` * `AnotherInstantiationName/FooTest.HasBlahBlah/1` for `"dog"` Please note that `INSTANTIATE_TEST_CASE_P` will instantiate _all_ tests in the given test case, whether their definitions come before or _after_ the `INSTANTIATE_TEST_CASE_P` statement. You can see [these](../samples/sample7_unittest.cc) [files](../samples/sample8_unittest.cc) for more examples. _Availability_: Linux, Windows (requires MSVC 8.0 or above), Mac; since version 1.2.0. ## Creating Value-Parameterized Abstract Tests ## In the above, we define and instantiate `FooTest` in the same source file. Sometimes you may want to define value-parameterized tests in a library and let other people instantiate them later. This pattern is known as <i>abstract tests</i>. As an example of its application, when you are designing an interface you can write a standard suite of abstract tests (perhaps using a factory function as the test parameter) that all implementations of the interface are expected to pass. When someone implements the interface, he can instantiate your suite to get all the interface-conformance tests for free. To define abstract tests, you should organize your code like this: 1. Put the definition of the parameterized test fixture class (e.g. `FooTest`) in a header file, say `foo_param_test.h`. Think of this as _declaring_ your abstract tests. 1. Put the `TEST_P` definitions in `foo_param_test.cc`, which includes `foo_param_test.h`. Think of this as _implementing_ your abstract tests. Once they are defined, you can instantiate them by including `foo_param_test.h`, invoking `INSTANTIATE_TEST_CASE_P()`, and linking with `foo_param_test.cc`. You can instantiate the same abstract test case multiple times, possibly in different source files. # Typed Tests # Suppose you have multiple implementations of the same interface and want to make sure that all of them satisfy some common requirements. Or, you may have defined several types that are supposed to conform to the same "concept" and you want to verify it. In both cases, you want the same test logic repeated for different types. While you can write one `TEST` or `TEST_F` for each type you want to test (and you may even factor the test logic into a function template that you invoke from the `TEST`), it's tedious and doesn't scale: if you want _m_ tests over _n_ types, you'll end up writing _m\*n_ `TEST`s. _Typed tests_ allow you to repeat the same test logic over a list of types. You only need to write the test logic once, although you must know the type list when writing typed tests. Here's how you do it: First, define a fixture class template. It should be parameterized by a type. Remember to derive it from `::testing::Test`: ``` template <typename T> class FooTest : public ::testing::Test { public: ... typedef std::list<T> List; static T shared_; T value_; }; ``` Next, associate a list of types with the test case, which will be repeated for each type in the list: ``` typedef ::testing::Types<char, int, unsigned int> MyTypes; TYPED_TEST_CASE(FooTest, MyTypes); ``` The `typedef` is necessary for the `TYPED_TEST_CASE` macro to parse correctly. Otherwise the compiler will think that each comma in the type list introduces a new macro argument. Then, use `TYPED_TEST()` instead of `TEST_F()` to define a typed test for this test case. You can repeat this as many times as you want: ``` TYPED_TEST(FooTest, DoesBlah) { // Inside a test, refer to the special name TypeParam to get the type // parameter. Since we are inside a derived class template, C++ requires // us to visit the members of FooTest via 'this'. TypeParam n = this->value_; // To visit static members of the fixture, add the 'TestFixture::' // prefix. n += TestFixture::shared_; // To refer to typedefs in the fixture, add the 'typename TestFixture::' // prefix. The 'typename' is required to satisfy the compiler. typename TestFixture::List values; values.push_back(n); ... } TYPED_TEST(FooTest, HasPropertyA) { ... } ``` You can see `samples/sample6_unittest.cc` for a complete example. _Availability:_ Linux, Windows (requires MSVC 8.0 or above), Mac; since version 1.1.0. # Type-Parameterized Tests # _Type-parameterized tests_ are like typed tests, except that they don't require you to know the list of types ahead of time. Instead, you can define the test logic first and instantiate it with different type lists later. You can even instantiate it more than once in the same program. If you are designing an interface or concept, you can define a suite of type-parameterized tests to verify properties that any valid implementation of the interface/concept should have. Then, the author of each implementation can just instantiate the test suite with his type to verify that it conforms to the requirements, without having to write similar tests repeatedly. Here's an example: First, define a fixture class template, as we did with typed tests: ``` template <typename T> class FooTest : public ::testing::Test { ... }; ``` Next, declare that you will define a type-parameterized test case: ``` TYPED_TEST_CASE_P(FooTest); ``` The `_P` suffix is for "parameterized" or "pattern", whichever you prefer to think. Then, use `TYPED_TEST_P()` to define a type-parameterized test. You can repeat this as many times as you want: ``` TYPED_TEST_P(FooTest, DoesBlah) { // Inside a test, refer to TypeParam to get the type parameter. TypeParam n = 0; ... } TYPED_TEST_P(FooTest, HasPropertyA) { ... } ``` Now the tricky part: you need to register all test patterns using the `REGISTER_TYPED_TEST_CASE_P` macro before you can instantiate them. The first argument of the macro is the test case name; the rest are the names of the tests in this test case: ``` REGISTER_TYPED_TEST_CASE_P(FooTest, DoesBlah, HasPropertyA); ``` Finally, you are free to instantiate the pattern with the types you want. If you put the above code in a header file, you can `#include` it in multiple C++ source files and instantiate it multiple times. ``` typedef ::testing::Types<char, int, unsigned int> MyTypes; INSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, MyTypes); ``` To distinguish different instances of the pattern, the first argument to the `INSTANTIATE_TYPED_TEST_CASE_P` macro is a prefix that will be added to the actual test case name. Remember to pick unique prefixes for different instances. In the special case where the type list contains only one type, you can write that type directly without `::testing::Types<...>`, like this: ``` INSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, int); ``` You can see `samples/sample6_unittest.cc` for a complete example. _Availability:_ Linux, Windows (requires MSVC 8.0 or above), Mac; since version 1.1.0. # Testing Private Code # If you change your software's internal implementation, your tests should not break as long as the change is not observable by users. Therefore, per the _black-box testing principle_, most of the time you should test your code through its public interfaces. If you still find yourself needing to test internal implementation code, consider if there's a better design that wouldn't require you to do so. If you absolutely have to test non-public interface code though, you can. There are two cases to consider: * Static functions (_not_ the same as static member functions!) or unnamed namespaces, and * Private or protected class members ## Static Functions ## Both static functions and definitions/declarations in an unnamed namespace are only visible within the same translation unit. To test them, you can `#include` the entire `.cc` file being tested in your `*_test.cc` file. (`#include`ing `.cc` files is not a good way to reuse code - you should not do this in production code!) However, a better approach is to move the private code into the `foo::internal` namespace, where `foo` is the namespace your project normally uses, and put the private declarations in a `*-internal.h` file. Your production `.cc` files and your tests are allowed to include this internal header, but your clients are not. This way, you can fully test your internal implementation without leaking it to your clients. ## Private Class Members ## Private class members are only accessible from within the class or by friends. To access a class' private members, you can declare your test fixture as a friend to the class and define accessors in your fixture. Tests using the fixture can then access the private members of your production class via the accessors in the fixture. Note that even though your fixture is a friend to your production class, your tests are not automatically friends to it, as they are technically defined in sub-classes of the fixture. Another way to test private members is to refactor them into an implementation class, which is then declared in a `*-internal.h` file. Your clients aren't allowed to include this header but your tests can. Such is called the Pimpl (Private Implementation) idiom. Or, you can declare an individual test as a friend of your class by adding this line in the class body: ``` FRIEND_TEST(TestCaseName, TestName); ``` For example, ``` // foo.h #include "gtest/gtest_prod.h" // Defines FRIEND_TEST. class Foo { ... private: FRIEND_TEST(FooTest, BarReturnsZeroOnNull); int Bar(void* x); }; // foo_test.cc ... TEST(FooTest, BarReturnsZeroOnNull) { Foo foo; EXPECT_EQ(0, foo.Bar(NULL)); // Uses Foo's private member Bar(). } ``` Pay special attention when your class is defined in a namespace, as you should define your test fixtures and tests in the same namespace if you want them to be friends of your class. For example, if the code to be tested looks like: ``` namespace my_namespace { class Foo { friend class FooTest; FRIEND_TEST(FooTest, Bar); FRIEND_TEST(FooTest, Baz); ... definition of the class Foo ... }; } // namespace my_namespace ``` Your test code should be something like: ``` namespace my_namespace { class FooTest : public ::testing::Test { protected: ... }; TEST_F(FooTest, Bar) { ... } TEST_F(FooTest, Baz) { ... } } // namespace my_namespace ``` # Catching Failures # If you are building a testing utility on top of Google Test, you'll want to test your utility. What framework would you use to test it? Google Test, of course. The challenge is to verify that your testing utility reports failures correctly. In frameworks that report a failure by throwing an exception, you could catch the exception and assert on it. But Google Test doesn't use exceptions, so how do we test that a piece of code generates an expected failure? `"gtest/gtest-spi.h"` contains some constructs to do this. After `#include`ing this header, you can use | `EXPECT_FATAL_FAILURE(`_statement, substring_`);` | |:--------------------------------------------------| to assert that _statement_ generates a fatal (e.g. `ASSERT_*`) failure whose message contains the given _substring_, or use | `EXPECT_NONFATAL_FAILURE(`_statement, substring_`);` | |:-----------------------------------------------------| if you are expecting a non-fatal (e.g. `EXPECT_*`) failure. For technical reasons, there are some caveats: 1. You cannot stream a failure message to either macro. 1. _statement_ in `EXPECT_FATAL_FAILURE()` cannot reference local non-static variables or non-static members of `this` object. 1. _statement_ in `EXPECT_FATAL_FAILURE()` cannot return a value. _Note:_ Google Test is designed with threads in mind. Once the synchronization primitives in `"gtest/internal/gtest-port.h"` have been implemented, Google Test will become thread-safe, meaning that you can then use assertions in multiple threads concurrently. Before that, however, Google Test only supports single-threaded usage. Once thread-safe, `EXPECT_FATAL_FAILURE()` and `EXPECT_NONFATAL_FAILURE()` will capture failures in the current thread only. If _statement_ creates new threads, failures in these threads will be ignored. If you want to capture failures from all threads instead, you should use the following macros: | `EXPECT_FATAL_FAILURE_ON_ALL_THREADS(`_statement, substring_`);` | |:-----------------------------------------------------------------| | `EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(`_statement, substring_`);` | # Getting the Current Test's Name # Sometimes a function may need to know the name of the currently running test. For example, you may be using the `SetUp()` method of your test fixture to set the golden file name based on which test is running. The `::testing::TestInfo` class has this information: ``` namespace testing { class TestInfo { public: // Returns the test case name and the test name, respectively. // // Do NOT delete or free the return value - it's managed by the // TestInfo class. const char* test_case_name() const; const char* name() const; }; } // namespace testing ``` > To obtain a `TestInfo` object for the currently running test, call `current_test_info()` on the `UnitTest` singleton object: ``` // Gets information about the currently running test. // Do NOT delete the returned object - it's managed by the UnitTest class. const ::testing::TestInfo* const test_info = ::testing::UnitTest::GetInstance()->current_test_info(); printf("We are in test %s of test case %s.\n", test_info->name(), test_info->test_case_name()); ``` `current_test_info()` returns a null pointer if no test is running. In particular, you cannot find the test case name in `TestCaseSetUp()`, `TestCaseTearDown()` (where you know the test case name implicitly), or functions called from them. _Availability:_ Linux, Windows, Mac. # Extending Google Test by Handling Test Events # Google Test provides an <b>event listener API</b> to let you receive notifications about the progress of a test program and test failures. The events you can listen to include the start and end of the test program, a test case, or a test method, among others. You may use this API to augment or replace the standard console output, replace the XML output, or provide a completely different form of output, such as a GUI or a database. You can also use test events as checkpoints to implement a resource leak checker, for example. _Availability:_ Linux, Windows, Mac; since v1.4.0. ## Defining Event Listeners ## To define a event listener, you subclass either [testing::TestEventListener](../include/gtest/gtest.h#L991) or [testing::EmptyTestEventListener](../include/gtest/gtest.h#L1044). The former is an (abstract) interface, where <i>each pure virtual method<br> can be overridden to handle a test event</i> (For example, when a test starts, the `OnTestStart()` method will be called.). The latter provides an empty implementation of all methods in the interface, such that a subclass only needs to override the methods it cares about. When an event is fired, its context is passed to the handler function as an argument. The following argument types are used: * [UnitTest](../include/gtest/gtest.h#L1151) reflects the state of the entire test program, * [TestCase](../include/gtest/gtest.h#L778) has information about a test case, which can contain one or more tests, * [TestInfo](../include/gtest/gtest.h#L644) contains the state of a test, and * [TestPartResult](../include/gtest/gtest-test-part.h#L47) represents the result of a test assertion. An event handler function can examine the argument it receives to find out interesting information about the event and the test program's state. Here's an example: ``` class MinimalistPrinter : public ::testing::EmptyTestEventListener { // Called before a test starts. virtual void OnTestStart(const ::testing::TestInfo& test_info) { printf("*** Test %s.%s starting.\n", test_info.test_case_name(), test_info.name()); } // Called after a failed assertion or a SUCCEED() invocation. virtual void OnTestPartResult( const ::testing::TestPartResult& test_part_result) { printf("%s in %s:%d\n%s\n", test_part_result.failed() ? "*** Failure" : "Success", test_part_result.file_name(), test_part_result.line_number(), test_part_result.summary()); } // Called after a test ends. virtual void OnTestEnd(const ::testing::TestInfo& test_info) { printf("*** Test %s.%s ending.\n", test_info.test_case_name(), test_info.name()); } }; ``` ## Using Event Listeners ## To use the event listener you have defined, add an instance of it to the Google Test event listener list (represented by class [TestEventListeners](../include/gtest/gtest.h#L1064) - note the "s" at the end of the name) in your `main()` function, before calling `RUN_ALL_TESTS()`: ``` int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); // Gets hold of the event listener list. ::testing::TestEventListeners& listeners = ::testing::UnitTest::GetInstance()->listeners(); // Adds a listener to the end. Google Test takes the ownership. listeners.Append(new MinimalistPrinter); return RUN_ALL_TESTS(); } ``` There's only one problem: the default test result printer is still in effect, so its output will mingle with the output from your minimalist printer. To suppress the default printer, just release it from the event listener list and delete it. You can do so by adding one line: ``` ... delete listeners.Release(listeners.default_result_printer()); listeners.Append(new MinimalistPrinter); return RUN_ALL_TESTS(); ``` Now, sit back and enjoy a completely different output from your tests. For more details, you can fileToCin this [sample](../samples/sample9_unittest.cc). You may append more than one listener to the list. When an `On*Start()` or `OnTestPartResult()` event is fired, the listeners will receive it in the order they appear in the list (since new listeners are added to the end of the list, the default text printer and the default XML generator will receive the event first). An `On*End()` event will be received by the listeners in the _reverse_ order. This allows output by listeners added later to be framed by output from listeners added earlier. ## Generating Failures in Listeners ## You may use failure-raising macros (`EXPECT_*()`, `ASSERT_*()`, `FAIL()`, etc) when processing an event. There are some restrictions: 1. You cannot generate any failure in `OnTestPartResult()` (otherwise it will cause `OnTestPartResult()` to be called recursively). 1. A listener that handles `OnTestPartResult()` is not allowed to generate any failure. When you add listeners to the listener list, you should put listeners that handle `OnTestPartResult()` _before_ listeners that can generate failures. This ensures that failures generated by the latter are attributed to the right test by the former. We have a sample of failure-raising listener [here](../samples/sample10_unittest.cc). # Running Test Programs: Advanced Options # Google Test test programs are ordinary executables. Once built, you can run them directly and affect their behavior via the following environment variables and/or command line flags. For the flags to work, your programs must call `::testing::InitGoogleTest()` before calling `RUN_ALL_TESTS()`. To see a list of supported flags and their usage, please run your test program with the `--help` flag. You can also use `-h`, `-?`, or `/?` for short. This feature is added in version 1.3.0. If an option is specified both by an environment variable and by a flag, the latter takes precedence. Most of the options can also be set/fileToCin in code: to access the value of command line flag `--gtest_foo`, write `::testing::GTEST_FLAG(foo)`. A common pattern is to set the value of a flag before calling `::testing::InitGoogleTest()` to change the default value of the flag: ``` int main(int argc, char** argv) { // Disables elapsed time by default. ::testing::GTEST_FLAG(print_time) = false; // This allows the user to override the flag on the command line. ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } ``` ## Selecting Tests ## This section shows various options for choosing which tests to run. ### Listing Test Names ### Sometimes it is necessary to list the available tests in a program before running them so that a filter may be applied if needed. Including the flag `--gtest_list_tests` overrides all other flags and lists tests in the following format: ``` TestCase1. TestName1 TestName2 TestCase2. TestName ``` None of the tests listed are actually run if the flag is provided. There is no corresponding environment variable for this flag. _Availability:_ Linux, Windows, Mac. ### Running a Subset of the Tests ### By default, a Google Test program runs all tests the user has defined. Sometimes, you want to run only a subset of the tests (e.g. for debugging or quickly verifying a change). If you set the `GTEST_FILTER` environment variable or the `--gtest_filter` flag to a filter string, Google Test will only run the tests whose full names (in the form of `TestCaseName.TestName`) match the filter. The format of a filter is a '`:`'-separated list of wildcard patterns (called the positive patterns) optionally followed by a '`-`' and another '`:`'-separated pattern list (called the negative patterns). A test matches the filter if and only if it matches any of the positive patterns but does not match any of the negative patterns. A pattern may contain `'*'` (matches any string) or `'?'` (matches any single character). For convenience, the filter `'*-NegativePatterns'` can be also written as `'-NegativePatterns'`. For example: * `./foo_test` Has no flag, and thus runs all its tests. * `./foo_test --gtest_filter=*` Also runs everything, due to the single match-everything `*` value. * `./foo_test --gtest_filter=FooTest.*` Runs everything in test case `FooTest`. * `./foo_test --gtest_filter=*Null*:*Constructor*` Runs any test whose full name contains either `"Null"` or `"Constructor"`. * `./foo_test --gtest_filter=-*DeathTest.*` Runs all non-death tests. * `./foo_test --gtest_filter=FooTest.*-FooTest.Bar` Runs everything in test case `FooTest` except `FooTest.Bar`. _Availability:_ Linux, Windows, Mac. ### Temporarily Disabling Tests ### If you have a broken test that you cannot fix right away, you can add the `DISABLED_` prefix to its name. This will exclude it from execution. This is better than commenting out the code or using `#if 0`, as disabled tests are still compiled (and thus won't rot). If you need to disable all tests in a test case, you can either add `DISABLED_` to the front of the name of each test, or alternatively add it to the front of the test case name. For example, the following tests won't be run by Google Test, even though they will still be compiled: ``` // Tests that Foo does Abc. TEST(FooTest, DISABLED_DoesAbc) { ... } class DISABLED_BarTest : public ::testing::Test { ... }; // Tests that Bar does Xyz. TEST_F(DISABLED_BarTest, DoesXyz) { ... } ``` _Note:_ This feature should only be used for temporary pain-relief. You still have to fix the disabled tests at a later date. As a reminder, Google Test will print a banner warning you if a test program contains any disabled tests. _Tip:_ You can easily count the number of disabled tests you have using `grep`. This number can be used as a metric for improving your test quality. _Availability:_ Linux, Windows, Mac. ### Temporarily Enabling Disabled Tests ### To include [disabled tests](#temporarily-disabling-tests) in test execution, just invoke the test program with the `--gtest_also_run_disabled_tests` flag or set the `GTEST_ALSO_RUN_DISABLED_TESTS` environment variable to a value other than `0`. You can combine this with the [--gtest\_filter](#running-a-subset-of-the-tests) flag to further select which disabled tests to run. _Availability:_ Linux, Windows, Mac; since version 1.3.0. ## Repeating the Tests ## Once in a while you'll run into a test whose result is hit-or-miss. Perhaps it will fail only 1% of the time, making it rather hard to reproduce the bug under a debugger. This can be a major source of frustration. The `--gtest_repeat` flag allows you to repeat all (or selected) test methods in a program many times. Hopefully, a flaky test will eventually fail and give you a chance to debug. Here's how to use it: | `$ foo_test --gtest_repeat=1000` | Repeat foo\_test 1000 times and don't stop at failures. | |:---------------------------------|:--------------------------------------------------------| | `$ foo_test --gtest_repeat=-1` | A negative count means repeating forever. | | `$ foo_test --gtest_repeat=1000 --gtest_break_on_failure` | Repeat foo\_test 1000 times, stopping at the first failure. This is especially useful when running under a debugger: when the testfails, it will drop into the debugger and you can then inspect variables and stacks. | | `$ foo_test --gtest_repeat=1000 --gtest_filter=FooBar` | Repeat the tests whose name matches the filter 1000 times. | If your test program contains global set-up/tear-down code registered using `AddGlobalTestEnvironment()`, it will be repeated in each iteration as well, as the flakiness may be in it. You can also specify the repeat count by setting the `GTEST_REPEAT` environment variable. _Availability:_ Linux, Windows, Mac. ## Shuffling the Tests ## You can specify the `--gtest_shuffle` flag (or set the `GTEST_SHUFFLE` environment variable to `1`) to run the tests in a program in a random order. This helps to reveal bad dependencies between tests. By default, Google Test uses a random seed calculated from the current time. Therefore you'll get a different order every time. The console output includes the random seed value, such that you can reproduce an order-related test failure later. To specify the random seed explicitly, use the `--gtest_random_seed=SEED` flag (or set the `GTEST_RANDOM_SEED` environment variable), where `SEED` is an integer between 0 and 99999. The seed value 0 is special: it tells Google Test to do the default behavior of calculating the seed from the current time. If you combine this with `--gtest_repeat=N`, Google Test will pick a different random seed and re-shuffle the tests in each iteration. _Availability:_ Linux, Windows, Mac; since v1.4.0. ## Controlling Test Output ## This section teaches how to tweak the way test results are reported. ### Colored Terminal Output ### Google Test can use colors in its terminal output to make it easier to spot the separation between tests, and whether tests passed. You can set the GTEST\_COLOR environment variable or set the `--gtest_color` command line flag to `yes`, `no`, or `auto` (the default) to enable colors, disable colors, or let Google Test decide. When the value is `auto`, Google Test will use colors if and only if the output goes to a terminal and (on non-Windows platforms) the `TERM` environment variable is set to `xterm` or `xterm-color`. _Availability:_ Linux, Windows, Mac. ### Suppressing the Elapsed Time ### By default, Google Test prints the time it takes to run each test. To suppress that, run the test program with the `--gtest_print_time=0` command line flag. Setting the `GTEST_PRINT_TIME` environment variable to `0` has the same effect. _Availability:_ Linux, Windows, Mac. (In Google Test 1.3.0 and lower, the default behavior is that the elapsed time is **not** printed.) ### Generating an XML Report ### Google Test can emit a detailed XML report to a file in addition to its normal textual output. The report contains the duration of each test, and thus can help you identify slow tests. To generate the XML report, set the `GTEST_OUTPUT` environment variable or the `--gtest_output` flag to the string `"xml:_path_to_output_file_"`, which will create the file at the given location. You can also just use the string `"xml"`, in which case the output can be found in the `test_detail.xml` file in the current directory. If you specify a directory (for example, `"xml:output/directory/"` on Linux or `"xml:output\directory\"` on Windows), Google Test will create the XML file in that directory, named after the test executable (e.g. `foo_test.xml` for test program `foo_test` or `foo_test.exe`). If the file already exists (perhaps left over from a previous run), Google Test will pick a different name (e.g. `foo_test_1.xml`) to avoid overwriting it. The report uses the format described here. It is based on the `junitreport` Ant task and can be parsed by popular continuous build systems like [Hudson](https://hudson.dev.java.net/). Since that format was originally intended for Java, a little interpretation is required to make it apply to Google Test tests, as shown here: ``` <testsuites name="AllTests" ...> <testsuite name="test_case_name" ...> <testcase name="test_name" ...> <failure message="..."/> <failure message="..."/> <failure message="..."/> </testcase> </testsuite> </testsuites> ``` * The root `<testsuites>` element corresponds to the entire test program. * `<testsuite>` elements correspond to Google Test test cases. * `<testcase>` elements correspond to Google Test test functions. For instance, the following program ``` TEST(MathTest, Addition) { ... } TEST(MathTest, Subtraction) { ... } TEST(LogicTest, NonContradiction) { ... } ``` could generate this report: ``` <?xml version="1.0" encoding="UTF-8"?> <testsuites tests="3" failures="1" errors="0" time="35" name="AllTests"> <testsuite name="MathTest" tests="2" failures="1" errors="0" time="15"> <testcase name="Addition" status="run" time="7" classname=""> <failure message="Value of: add(1, 1)&#x0A; Actual: 3&#x0A;Expected: 2" type=""/> <failure message="Value of: add(1, -1)&#x0A; Actual: 1&#x0A;Expected: 0" type=""/> </testcase> <testcase name="Subtraction" status="run" time="5" classname=""> </testcase> </testsuite> <testsuite name="LogicTest" tests="1" failures="0" errors="0" time="5"> <testcase name="NonContradiction" status="run" time="5" classname=""> </testcase> </testsuite> </testsuites> ``` Things to note: * The `tests` attribute of a `<testsuites>` or `<testsuite>` element tells how many test functions the Google Test program or test case contains, while the `failures` attribute tells how many of them failed. * The `time` attribute expresses the duration of the test, test case, or entire test program in milliseconds. * Each `<failure>` element corresponds to a single failed Google Test assertion. * Some JUnit concepts don't apply to Google Test, yet we have to conform to the DTD. Therefore you'll see some dummy elements and attributes in the report. You can safely ignore these parts. _Availability:_ Linux, Windows, Mac. ## Controlling How Failures Are Reported ## ### Turning Assertion Failures into Break-Points ### When running test programs under a debugger, it's very convenient if the debugger can catch an assertion failure and automatically drop into interactive mode. Google Test's _break-on-failure_ mode supports this behavior. To enable it, set the `GTEST_BREAK_ON_FAILURE` environment variable to a value other than `0` . Alternatively, you can use the `--gtest_break_on_failure` command line flag. _Availability:_ Linux, Windows, Mac. ### Disabling Catching Test-Thrown Exceptions ### Google Test can be used either with or without exceptions enabled. If a test throws a C++ exception or (on Windows) a structured exception (SEH), by default Google Test catches it, reports it as a test failure, and continues with the next test method. This maximizes the coverage of a test run. Also, on Windows an uncaught exception will cause a pop-up window, so catching the exceptions allows you to run the tests automatically. When debugging the test failures, however, you may instead want the exceptions to be handled by the debugger, such that you can examine the call stack when an exception is thrown. To achieve that, set the `GTEST_CATCH_EXCEPTIONS` environment variable to `0`, or use the `--gtest_catch_exceptions=0` flag when running the tests. **Availability**: Linux, Windows, Mac. ### Letting Another Testing Framework Drive ### If you work on a project that has already been using another testing framework and is not ready to completely switch to Google Test yet, you can get much of Google Test's benefit by using its assertions in your existing tests. Just change your `main()` function to look like: ``` #include "gtest/gtest.h" int main(int argc, char** argv) { ::testing::GTEST_FLAG(throw_on_failure) = true; // Important: Google Test must be initialized. ::testing::InitGoogleTest(&argc, argv); ... whatever your existing testing framework requires ... } ``` With that, you can use Google Test assertions in addition to the native assertions your testing framework provides, for example: ``` void TestFooDoesBar() { Foo foo; EXPECT_LE(foo.Bar(1), 100); // A Google Test assertion. CPPUNIT_ASSERT(foo.IsEmpty()); // A native assertion. } ``` If a Google Test assertion fails, it will print an error message and throw an exception, which will be treated as a failure by your host testing framework. If you compile your code with exceptions disabled, a failed Google Test assertion will instead exit your program with a non-zero code, which will also signal a test failure to your test runner. If you don't write `::testing::GTEST_FLAG(throw_on_failure) = true;` in your `main()`, you can alternatively enable this feature by specifying the `--gtest_throw_on_failure` flag on the command-line or setting the `GTEST_THROW_ON_FAILURE` environment variable to a non-zero value. Death tests are _not_ supported when other test framework is used to organize tests. _Availability:_ Linux, Windows, Mac; since v1.3.0. ## Distributing Test Functions to Multiple Machines ## If you have more than one machine you can use to run a test program, you might want to run the test functions in parallel and get the result faster. We call this technique _sharding_, where each machine is called a _shard_. Google Test is compatible with test sharding. To take advantage of this feature, your test runner (not part of Google Test) needs to do the following: 1. Allocate a number of machines (shards) to run the tests. 1. On each shard, set the `GTEST_TOTAL_SHARDS` environment variable to the total number of shards. It must be the same for all shards. 1. On each shard, set the `GTEST_SHARD_INDEX` environment variable to the index of the shard. Different shards must be assigned different indices, which must be in the range `[0, GTEST_TOTAL_SHARDS - 1]`. 1. Run the same test program on all shards. When Google Test sees the above two environment variables, it will select a subset of the test functions to run. Across all shards, each test function in the program will be run exactly once. 1. Wait for all shards to finish, then collect and report the results. Your project may have tests that were written without Google Test and thus don't understand this protocol. In order for your test runner to figure out which test supports sharding, it can set the environment variable `GTEST_SHARD_STATUS_FILE` to a non-existent file path. If a test program supports sharding, it will create this file to acknowledge the fact (the actual contents of the file are not important at this time; although we may stick some useful information in it in the future.); otherwise it will not create it. Here's an example to make it clear. Suppose you have a test program `foo_test` that contains the following 5 test functions: ``` TEST(A, V) TEST(A, W) TEST(B, X) TEST(B, Y) TEST(B, Z) ``` and you have 3 machines at your disposal. To run the test functions in parallel, you would set `GTEST_TOTAL_SHARDS` to 3 on all machines, and set `GTEST_SHARD_INDEX` to 0, 1, and 2 on the machines respectively. Then you would run the same `foo_test` on each machine. Google Test reserves the right to change how the work is distributed across the shards, but here's one possible scenario: * Machine #0 runs `A.V` and `B.X`. * Machine #1 runs `A.W` and `B.Y`. * Machine #2 runs `B.Z`. _Availability:_ Linux, Windows, Mac; since version 1.3.0. # Fusing Google Test Source Files # Google Test's implementation consists of ~30 files (excluding its own tests). Sometimes you may want them to be packaged up in two files (a `.h` and a `.cc`) instead, such that you can easily copy them to a new machine and start hacking there. For this we provide an experimental Python script `fuse_gtest_files.py` in the `scripts/` directory (since release 1.3.0). Assuming you have Python 2.4 or above installed on your machine, just go to that directory and run ``` python fuse_gtest_files.py OUTPUT_DIR ``` and you should see an `OUTPUT_DIR` directory being created with files `gtest/gtest.h` and `gtest/gtest-all.cc` in it. These files contain everything you need to use Google Test. Just copy them to anywhere you want and you are ready to write tests. You can use the [scripts/test/Makefile](../scripts/test/Makefile) file as an example on how to compile your tests against them. # Where to Go from Here # Congratulations! You've now learned more advanced Google Test tools and are ready to tackle more complex testing tasks. If you want to dive even deeper, you can fileToCin the [Frequently-Asked Questions](FAQ.md).
{ "content_hash": "134e37b6d815773ebe967311924e0466", "timestamp": "", "source": "github", "line_count": 2180, "max_line_length": 454, "avg_line_length": 40.253669724770646, "alnum_prop": 0.7193372306359896, "repo_name": "fpopic/bioinf", "id": "d55e797ebcf2e697b6ac71f8758e07197f7a0ebe", "size": "87755", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "bioinf/test/lib/gtest-1.8.0/docs/AdvancedGuide.md", "mode": "33261", "license": "mit", "language": [ { "name": "C", "bytes": "9502" }, { "name": "C++", "bytes": "2139253" }, { "name": "CMake", "bytes": "23674" }, { "name": "M4", "bytes": "19093" }, { "name": "Makefile", "bytes": "9924" }, { "name": "Objective-C", "bytes": "3143" }, { "name": "Python", "bytes": "254679" }, { "name": "Shell", "bytes": "15028" } ], "symlink_target": "" }
<?php namespace App\Seeder; use App\Factory\ClientFactory; use Illuminate\Database\Seeder; class ClientSeeder extends Seeder { private const COUNT = 3; public function run() { for ($i = 0; $i < self::COUNT; $i++) { ClientFactory::new()->create(); } } }
{ "content_hash": "ccce96cb74e77d6b13b9b565447a0767", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 46, "avg_line_length": 18.75, "alnum_prop": 0.59, "repo_name": "ivacuum/hosting", "id": "3a6922718c5329cecf540e7dfc2c95baa6f611d4", "size": "300", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/Seeder/ClientSeeder.php", "mode": "33188", "license": "mit", "language": [ { "name": "Blade", "bytes": "2538321" }, { "name": "CSS", "bytes": "25260" }, { "name": "JavaScript", "bytes": "29960" }, { "name": "PHP", "bytes": "994078" }, { "name": "Shell", "bytes": "697" }, { "name": "Vue", "bytes": "16439" } ], "symlink_target": "" }
var _ = require('lodash'); exports.parse = function(node, state) { _.extend(state, { proxyPropertyDefinition: { parents: [ 'Ti.UI.TextField', 'Ti.Map.Annotation' ] } }); return require('./_ProxyProperty').parse(node, state); };
{ "content_hash": "12babbfd22469c51fc6108ed4227f784", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 55, "avg_line_length": 19.23076923076923, "alnum_prop": 0.616, "repo_name": "brentonhouse/brentonhouse.alloy", "id": "f39c3580311674117d52aa547fd3f1cee085ad4f", "size": "250", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "Alloy/commands/compile/parsers/_ProxyProperty.LeftButton.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "3828" }, { "name": "CoffeeScript", "bytes": "872" }, { "name": "HTML", "bytes": "5471" }, { "name": "JavaScript", "bytes": "3336722" }, { "name": "Python", "bytes": "5251" } ], "symlink_target": "" }
package models; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.TreeMap; import javax.persistence.*; import com.fasterxml.jackson.annotation.*; import com.avaje.ebean.Model; import com.avaje.ebean.Model.Finder; @Entity public class PersonAtCase extends Model { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "testify_record_id_seq") public Integer id; @ManyToOne @JoinColumn(name="person_id") public Person person; @ManyToOne @JoinColumn(name="case_id") @JsonIgnore public Case the_case; public final static int ROLE_TESTIFIER = 0; public final static int ROLE_WRITER = 1; public Integer role; public static PersonAtCase create(Case c, Person p, Integer r) { PersonAtCase result = new PersonAtCase(); result.the_case = c; result.person = p; result.role = r; result.save(); return result; } }
{ "content_hash": "31f0d0061eea5edd03fa599ee2c01980", "timestamp": "", "source": "github", "line_count": 44, "max_line_length": 92, "avg_line_length": 22.204545454545453, "alnum_prop": 0.6775844421699079, "repo_name": "schmave/demschooltools", "id": "3208676489e4000cd6c795cdba563f6cd050e989", "size": "977", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/models/PersonAtCase.java", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "1446" }, { "name": "CSS", "bytes": "20259" }, { "name": "HTML", "bytes": "156964" }, { "name": "Java", "bytes": "349897" }, { "name": "JavaScript", "bytes": "251047" }, { "name": "Less", "bytes": "15032" }, { "name": "Procfile", "bytes": "172" }, { "name": "Python", "bytes": "38902" }, { "name": "Scala", "bytes": "2855" }, { "name": "Shell", "bytes": "559" } ], "symlink_target": "" }
const mainPackage = require('../package.json'); const exPackage = require('../example/package.json'); const allMainDeps = { ...mainPackage.dependencies, ...mainPackage.peerDependencies, ...mainPackage.devDependencies }; const allExDeps = { ...exPackage.dependencies, ...exPackage.peerDependencies, ...exPackage.devDependencies }; const res = Object.keys(allMainDeps).filter( k => (allExDeps[k] ? allMainDeps[k] !== allExDeps[k] : false) ); if (res.length > 0) { console.error(`Please make sure ${res.join(', ')} versions are inline`); process.exit(1); }
{ "content_hash": "aa7340ca7ae2e10f7cfbc362a4bb38ea", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 74, "avg_line_length": 25.043478260869566, "alnum_prop": 0.6875, "repo_name": "alex3165/react-mapbox-gl", "id": "94249c05fe87a5f7b4a9e0d8650ac192afd9cecb", "size": "576", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "scripts/dependencies-mismatch.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "5320" }, { "name": "HTML", "bytes": "4424" }, { "name": "JavaScript", "bytes": "1047" }, { "name": "Shell", "bytes": "235" }, { "name": "TypeScript", "bytes": "162946" } ], "symlink_target": "" }
:: Calculate field of view metrics using Python echo off cmd /c runCreateCADAssembly.bat FOR /F "skip=2 tokens=2,*" %%A IN ('C:\Windows\SysWoW64\REG.exe query "HKLM\software\META" /v "META_PATH"') DO set META_PATH=%%B set META_PYTHON_PATH="%META_PATH%\bin\Python27\Scripts\Python.exe" %META_PYTHON_PATH% scripts\convert.py || goto :ERROR_SECTION %META_PYTHON_PATH% scripts\field_of_fire.py || goto :ERROR_SECTION %META_PYTHON_PATH% scripts\update_summary.py || goto :ERROR_SECTION exit 0 :ERROR_SECTION set ERROR_CODE=%ERRORLEVEL% set ERROR_MSG="Encountered error during execution, error level is %ERROR_CODE%" echo %ERROR_MSG% >>_FAILED.txt echo "" echo "See Error Log: _FAILED.txt" ping -n 8 127.0.0.1 > nul exit /b %ERROR_CODE%
{ "content_hash": "307a8ab1c6866c65d6eb61d10828da0d", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 128, "avg_line_length": 39.473684210526315, "alnum_prop": 0.716, "repo_name": "pombredanne/metamorphosys-desktop", "id": "3a87eb605f6b6b2ae2bd998ae5c2d4819379a774", "size": "750", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "metamorphosys/META/analysis_tools/PYTHON_RICARDO/output_field_of_fire/run_field_of_fire.cmd", "mode": "33261", "license": "mit", "language": [ { "name": "Arduino", "bytes": "10683" }, { "name": "Assembly", "bytes": "117345" }, { "name": "Awk", "bytes": "3591" }, { "name": "Batchfile", "bytes": "228118" }, { "name": "BitBake", "bytes": "4526" }, { "name": "C", "bytes": "3613212" }, { "name": "C#", "bytes": "11617773" }, { "name": "C++", "bytes": "51448188" }, { "name": "CMake", "bytes": "3055" }, { "name": "CSS", "bytes": "109563" }, { "name": "Clojure", "bytes": "37831" }, { "name": "Eagle", "bytes": "3782687" }, { "name": "Emacs Lisp", "bytes": "8514" }, { "name": "GAP", "bytes": "49124" }, { "name": "Groff", "bytes": "2178" }, { "name": "Groovy", "bytes": "7686" }, { "name": "HTML", "bytes": "4025250" }, { "name": "Inno Setup", "bytes": "35715" }, { "name": "Java", "bytes": "489537" }, { "name": "JavaScript", "bytes": "167454" }, { "name": "Lua", "bytes": "1660" }, { "name": "Makefile", "bytes": "97209" }, { "name": "Mathematica", "bytes": "26" }, { "name": "Matlab", "bytes": "80874" }, { "name": "Max", "bytes": "78198" }, { "name": "Modelica", "bytes": "44541139" }, { "name": "Objective-C", "bytes": "34004" }, { "name": "Perl", "bytes": "19285" }, { "name": "PostScript", "bytes": "400254" }, { "name": "PowerShell", "bytes": "19749" }, { "name": "Processing", "bytes": "1477" }, { "name": "Prolog", "bytes": "3121" }, { "name": "Protocol Buffer", "bytes": "58995" }, { "name": "Python", "bytes": "5517835" }, { "name": "Ruby", "bytes": "4483" }, { "name": "Shell", "bytes": "956773" }, { "name": "Smarty", "bytes": "37892" }, { "name": "TeX", "bytes": "4183594" }, { "name": "Visual Basic", "bytes": "22546" }, { "name": "XSLT", "bytes": "332312" } ], "symlink_target": "" }
"""Module for testing features introduced in 12.1""" import datetime import sys if sys.version_info > (3,): long = int class TestFeatures12_1(BaseTestCase): def testArrayDMLRowCountsOff(self): "test executing with arraydmlrowcounts mode disabled" self.cursor.execute("truncate table TestArrayDML") rows = [ (1, "First"), (2, "Second") ] sql = "insert into TestArrayDML (IntCol,StringCol) values (:1,:2)" self.cursor.executemany(sql, rows, arraydmlrowcounts = False) self.assertRaises(cx_Oracle.DatabaseError, self.cursor.getarraydmlrowcounts) rows = [ (3, "Third"), (4, "Fourth") ] self.cursor.executemany(sql, rows) self.assertRaises(cx_Oracle.DatabaseError, self.cursor.getarraydmlrowcounts) def testArrayDMLRowCountsOn(self): "test executing with arraydmlrowcounts mode enabled" self.cursor.execute("truncate table TestArrayDML") rows = [ ( 1, "First", 100), ( 2, "Second", 200), ( 3, "Third", 300), ( 4, "Fourth", 300), ( 5, "Fifth", 300) ] sql = "insert into TestArrayDML (IntCol,StringCol,IntCol2) " \ "values (:1,:2,:3)" self.cursor.executemany(sql, rows, arraydmlrowcounts = True) self.connection.commit() self.assertEqual(self.cursor.getarraydmlrowcounts(), [long(1), long(1), long(1), long(1), long(1)]) self.cursor.execute("select count(*) from TestArrayDML") count, = self.cursor.fetchone() self.assertEqual(count, len(rows)) def testBindPLSQLBooleanCollectionIn(self): "test binding a boolean collection (in)" typeObj = self.connection.gettype("PKG_TESTBOOLEANS.UDT_BOOLEANLIST") obj = typeObj.newobject() obj.setelement(1, True) obj.extend([True, False, True, True, False, True]) result = self.cursor.callfunc("pkg_TestBooleans.TestInArrays", int, (obj,)) self.assertEqual(result, 5) def testBindPLSQLBooleanCollectionOut(self): "test binding a boolean collection (out)" typeObj = self.connection.gettype("PKG_TESTBOOLEANS.UDT_BOOLEANLIST") obj = typeObj.newobject() self.cursor.callproc("pkg_TestBooleans.TestOutArrays", (6, obj)) self.assertEqual(obj.aslist(), [True, False, True, False, True, False]) def testBindPLSQLDateCollectionIn(self): "test binding a PL/SQL date collection (in)" typeObj = self.connection.gettype("PKG_TESTDATEARRAYS.UDT_DATELIST") obj = typeObj.newobject() obj.setelement(1, datetime.datetime(2016, 2, 5)) obj.append(datetime.datetime(2016, 2, 8, 12, 15, 30)) obj.append(datetime.datetime(2016, 2, 12, 5, 44, 30)) result = self.cursor.callfunc("pkg_TestDateArrays.TestInArrays", cx_Oracle.NUMBER, (2, datetime.datetime(2016, 2, 1), obj)) self.assertEqual(result, 24.75) def testBindPLSQLDateCollectionInOut(self): "test binding a PL/SQL date collection (in/out)" typeObj = self.connection.gettype("PKG_TESTDATEARRAYS.UDT_DATELIST") obj = typeObj.newobject() obj.setelement(1, datetime.datetime(2016, 1, 1)) obj.append(datetime.datetime(2016, 1, 7)) obj.append(datetime.datetime(2016, 1, 13)) obj.append(datetime.datetime(2016, 1, 19)) self.cursor.callproc("pkg_TestDateArrays.TestInOutArrays", (4, obj)) self.assertEqual(obj.aslist(), [datetime.datetime(2016, 1, 8), datetime.datetime(2016, 1, 14), datetime.datetime(2016, 1, 20), datetime.datetime(2016, 1, 26)]) def testBindPLSQLDateCollectionOut(self): "test binding a PL/SQL date collection (out)" typeObj = self.connection.gettype("PKG_TESTDATEARRAYS.UDT_DATELIST") obj = typeObj.newobject() self.cursor.callproc("pkg_TestDateArrays.TestOutArrays", (3, obj)) self.assertEqual(obj.aslist(), [datetime.datetime(2002, 12, 13, 4, 48), datetime.datetime(2002, 12, 14, 9, 36), datetime.datetime(2002, 12, 15, 14, 24)]) def testBindPLSQLNumberCollectionIn(self): "test binding a PL/SQL number collection (in)" typeObj = self.connection.gettype("PKG_TESTNUMBERARRAYS.UDT_NUMBERLIST") obj = typeObj.newobject() obj.setelement(1, 10) obj.extend([20, 30, 40, 50]) result = self.cursor.callfunc("pkg_TestNumberArrays.TestInArrays", int, (5, obj)) self.assertEqual(result, 155) def testBindPLSQLNumberCollectionInOut(self): "test binding a PL/SQL number collection (in/out)" typeObj = self.connection.gettype("PKG_TESTNUMBERARRAYS.UDT_NUMBERLIST") obj = typeObj.newobject() obj.setelement(1, 5) obj.extend([8, 3, 2]) self.cursor.callproc("pkg_TestNumberArrays.TestInOutArrays", (4, obj)) self.assertEqual(obj.aslist(), [50, 80, 30, 20]) def testBindPLSQLNumberCollectionOut(self): "test binding a PL/SQL number collection (out)" typeObj = self.connection.gettype("PKG_TESTNUMBERARRAYS.UDT_NUMBERLIST") obj = typeObj.newobject() self.cursor.callproc("pkg_TestNumberArrays.TestOutArrays", (3, obj)) self.assertEqual(obj.aslist(), [100, 200, 300]) def testBindPLSQLRecordArray(self): "test binding an array of PL/SQL records (in)" recType = self.connection.gettype("PKG_TESTRECORDS.UDT_RECORD") arrayType = self.connection.gettype("PKG_TESTRECORDS.UDT_RECORDARRAY") arrayObj = arrayType.newobject() for i in range(3): obj = recType.newobject() obj.NUMBERVALUE = i + 1 obj.STRINGVALUE = "String in record #%d" % (i + 1) obj.DATEVALUE = datetime.datetime(2017, i + 1, 1) obj.TIMESTAMPVALUE = datetime.datetime(2017, 1, i + 1) obj.BOOLEANVALUE = (i % 2) == 1 arrayObj.append(obj) result = self.cursor.callfunc("pkg_TestRecords.TestInArrays", str, (arrayObj,)) self.assertEqual(result, "udt_Record(1, 'String in record #1', " \ "to_date('2017-01-01', 'YYYY-MM-DD'), " \ "to_timestamp('2017-01-01 00:00:00', " \ "'YYYY-MM-DD HH24:MI:SS'), false); " \ "udt_Record(2, 'String in record #2', " \ "to_date('2017-02-01', 'YYYY-MM-DD'), " \ "to_timestamp('2017-01-02 00:00:00', " \ "'YYYY-MM-DD HH24:MI:SS'), true); " \ "udt_Record(3, 'String in record #3', " \ "to_date('2017-03-01', 'YYYY-MM-DD'), " \ "to_timestamp('2017-01-03 00:00:00', " \ "'YYYY-MM-DD HH24:MI:SS'), false)") def testBindPLSQLRecordIn(self): "test binding a PL/SQL record (in)" typeObj = self.connection.gettype("PKG_TESTRECORDS.UDT_RECORD") obj = typeObj.newobject() obj.NUMBERVALUE = 18 obj.STRINGVALUE = "A string in a record" obj.DATEVALUE = datetime.datetime(2016, 2, 15) obj.TIMESTAMPVALUE = datetime.datetime(2016, 2, 12, 14, 25, 36) obj.BOOLEANVALUE = False result = self.cursor.callfunc("pkg_TestRecords.GetStringRep", str, (obj,)) self.assertEqual(result, "udt_Record(18, 'A string in a record', " \ "to_date('2016-02-15', 'YYYY-MM-DD'), " \ "to_timestamp('2016-02-12 14:25:36', " \ "'YYYY-MM-DD HH24:MI:SS'), false)") def testBindPLSQLRecordOut(self): "test binding a PL/SQL record (out)" typeObj = self.connection.gettype("PKG_TESTRECORDS.UDT_RECORD") obj = typeObj.newobject() obj.NUMBERVALUE = 5 obj.STRINGVALUE = "Test value" obj.DATEVALUE = datetime.datetime.today() obj.TIMESTAMPVALUE = datetime.datetime.today() obj.BOOLEANVALUE = False self.cursor.callproc("pkg_TestRecords.TestOut", (obj,)) self.assertEqual(obj.NUMBERVALUE, 25) self.assertEqual(obj.STRINGVALUE, "String in record") self.assertEqual(obj.DATEVALUE, datetime.datetime(2016, 2, 16)) self.assertEqual(obj.TIMESTAMPVALUE, datetime.datetime(2016, 2, 16, 18, 23, 55)) self.assertEqual(obj.BOOLEANVALUE, True) def testBindPLSQLStringCollectionIn(self): "test binding a PL/SQL string collection (in)" typeObj = self.connection.gettype("PKG_TESTSTRINGARRAYS.UDT_STRINGLIST") obj = typeObj.newobject() obj.setelement(1, "First element") obj.setelement(2, "Second element") obj.setelement(3, "Third element") result = self.cursor.callfunc("pkg_TestStringArrays.TestInArrays", int, (5, obj)) self.assertEqual(result, 45) def testBindPLSQLStringCollectionInOut(self): "test binding a PL/SQL string collection (in/out)" typeObj = self.connection.gettype("PKG_TESTSTRINGARRAYS.UDT_STRINGLIST") obj = typeObj.newobject() obj.setelement(1, "The first element") obj.append("The second element") obj.append("The third and final element") self.cursor.callproc("pkg_TestStringArrays.TestInOutArrays", (3, obj)) self.assertEqual(obj.aslist(), ['Converted element # 1 originally had length 17', 'Converted element # 2 originally had length 18', 'Converted element # 3 originally had length 27']) def testBindPLSQLStringCollectionOut(self): "test binding a PL/SQL string collection (out)" typeObj = self.connection.gettype("PKG_TESTSTRINGARRAYS.UDT_STRINGLIST") obj = typeObj.newobject() self.cursor.callproc("pkg_TestStringArrays.TestOutArrays", (4, obj)) self.assertEqual(obj.aslist(), ['Test out element # 1', 'Test out element # 2', 'Test out element # 3', 'Test out element # 4']) def testBindPLSQLStringCollectionOutWithHoles(self): "test binding a PL/SQL string collection (out with holes)" typeObj = self.connection.gettype("PKG_TESTSTRINGARRAYS.UDT_STRINGLIST") obj = typeObj.newobject() self.cursor.callproc("pkg_TestStringArrays.TestIndexBy", (obj,)) self.assertEqual(obj.first(), -1048576) self.assertEqual(obj.last(), 8388608) self.assertEqual(obj.next(-576), 284) self.assertEqual(obj.prev(284), -576) self.assertEqual(obj.size(), 4) self.assertEqual(obj.exists(-576), True) self.assertEqual(obj.exists(-577), False) self.assertEqual(obj.getelement(284), 'Third element') self.assertEqual(obj.aslist(), ["First element", "Second element", "Third element", "Fourth element"]) obj.delete(-576) obj.delete(284) self.assertEqual(obj.aslist(), ["First element", "Fourth element"]) def testExceptionInIteration(self): "test executing with arraydmlrowcounts with exception" self.cursor.execute("truncate table TestArrayDML") rows = [ (1, "First"), (2, "Second"), (2, "Third"), (4, "Fourth") ] sql = "insert into TestArrayDML (IntCol,StringCol) values (:1,:2)" self.assertRaises(cx_Oracle.DatabaseError, self.cursor.executemany, sql, rows, arraydmlrowcounts = True) self.assertEqual(self.cursor.getarraydmlrowcounts(), [long(1), long(1)]) def testExecutingDelete(self): "test executing delete statement with arraydmlrowcount mode" self.cursor.execute("truncate table TestArrayDML") rows = [ (1, "First", 100), (2, "Second", 200), (3, "Third", 300), (4, "Fourth", 300), (5, "Fifth", 300), (6, "Sixth", 400), (7, "Seventh", 400), (8, "Eighth", 500) ] sql = "insert into TestArrayDML (IntCol,StringCol,IntCol2) " \ "values (:1, :2, :3)" self.cursor.executemany(sql, rows) rows = [ (200,), (300,), (400,) ] statement = "delete from TestArrayDML where IntCol2 = :1" self.cursor.executemany(statement, rows, arraydmlrowcounts = True) self.assertEqual(self.cursor.getarraydmlrowcounts(), [long(1), long(3), long(2)]) def testExecutingUpdate(self): "test executing update statement with arraydmlrowcount mode" self.cursor.execute("truncate table TestArrayDML") rows = [ (1, "First",100), (2, "Second",200), (3, "Third",300), (4, "Fourth",300), (5, "Fifth",300), (6, "Sixth",400), (7, "Seventh",400), (8, "Eighth",500) ] sql = "insert into TestArrayDML (IntCol,StringCol,IntCol2) " \ "values (:1, :2, :3)" self.cursor.executemany(sql, rows) rows = [ ("One", 100), ("Two", 200), ("Three", 300), ("Four", 400) ] sql = "update TestArrayDML set StringCol = :1 where IntCol2 = :2" self.cursor.executemany(sql, rows, arraydmlrowcounts = True) self.assertEqual(self.cursor.getarraydmlrowcounts(), [long(1), long(1), long(3), long(2)]) def testImplicitResults(self): "test getimplicitresults() returns the correct data" self.cursor.execute(""" declare c1 sys_refcursor; c2 sys_refcursor; begin open c1 for select NumberCol from TestNumbers where IntCol between 3 and 5; dbms_sql.return_result(c1); open c2 for select NumberCol from TestNumbers where IntCol between 7 and 10; dbms_sql.return_result(c2); end;""") results = self.cursor.getimplicitresults() self.assertEqual(len(results), 2) self.assertEqual([n for n, in results[0]], [3.75, 5, 6.25]) self.assertEqual([n for n, in results[1]], [8.75, 10, 11.25, 12.5]) def testImplicitResultsNoStatement(self): "test getimplicitresults() without executing a statement" self.assertRaises(cx_Oracle.InterfaceError, self.cursor.getimplicitresults) def testInsertWithBatchError(self): "test executing insert with multiple distinct batch errors" self.cursor.execute("truncate table TestArrayDML") rows = [ (1, "First", 100), (2, "Second", 200), (2, "Third", 300), (4, "Fourth", 400), (5, "Fourth", 1000)] sql = "insert into TestArrayDML (IntCol, StringCol, IntCol2) " \ "values (:1, :2, :3)" self.cursor.executemany(sql, rows, batcherrors = True, arraydmlrowcounts = True) expectedErrors = [ ( 4, 1438, "ORA-01438: value larger than specified " \ "precision allowed for this column" ), ( 2, 1, "ORA-00001: unique constraint " \ "(CX_ORACLE.TESTARRAYDML_PK) violated") ] actualErrors = [(e.offset, e.code, e.message) \ for e in self.cursor.getbatcherrors()] self.assertEqual(actualErrors, expectedErrors) self.assertEqual(self.cursor.getarraydmlrowcounts(), [long(1), long(1), long(0), long(1), long(0)]) def testBatchErrorFalse(self): "test batcherrors mode set to False" self.cursor.execute("truncate table TestArrayDML") rows = [ (1, "First", 100), (2, "Second", 200), (2, "Third", 300) ] sql = "insert into TestArrayDML (IntCol, StringCol, IntCol2) " \ "values (:1, :2, :3)" self.assertRaises(cx_Oracle.IntegrityError, self.cursor.executemany, sql, rows, batcherrors = False) def testUpdatewithBatchError(self): "test executing in succession with batch error" self.cursor.execute("truncate table TestArrayDML") rows = [ (1, "First", 100), (2, "Second", 200), (3, "Third", 300), (4, "Second", 300), (5, "Fifth", 300), (6, "Sixth", 400), (6, "Seventh", 400), (8, "Eighth", 100) ] sql = "insert into TestArrayDML (IntCol, StringCol, IntCol2) " \ "values (:1, :2, :3)" self.cursor.executemany(sql, rows, batcherrors = True) expectedErrors = [ ( 6, 1, "ORA-00001: unique constraint " \ "(CX_ORACLE.TESTARRAYDML_PK) violated") ] actualErrors = [(e.offset, e.code, e.message) \ for e in self.cursor.getbatcherrors()] self.assertEqual(actualErrors, expectedErrors) rows = [ (101, "First"), (201, "Second"), (3000, "Third"), (900, "Ninth"), (301, "Third") ] sql = "update TestArrayDML set IntCol2 = :1 where StringCol = :2" self.cursor.executemany(sql, rows, arraydmlrowcounts = True, batcherrors = True) expectedErrors = [ ( 2, 1438, "ORA-01438: value larger than specified " \ "precision allowed for this column" ) ] actualErrors = [(e.offset, e.code, e.message) \ for e in self.cursor.getbatcherrors()] self.assertEqual(actualErrors, expectedErrors) self.assertEqual(self.cursor.getarraydmlrowcounts(), [long(1), long(2), long(0), long(0), long(1)]) self.assertEqual(self.cursor.rowcount, 4)
{ "content_hash": "52a850b6c6809e86cc663eaa7cb40a7c", "timestamp": "", "source": "github", "line_count": 404, "max_line_length": 80, "avg_line_length": 45.18069306930693, "alnum_prop": 0.5715224894537885, "repo_name": "kawamon/hue", "id": "194e32a206b618cdeca18546f53f400448ee969e", "size": "18673", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "desktop/core/ext-py/cx_Oracle-6.4.1/test/Features12_1.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ABAP", "bytes": "962" }, { "name": "ActionScript", "bytes": "1133" }, { "name": "Ada", "bytes": "99" }, { "name": "Assembly", "bytes": "5786" }, { "name": "AutoHotkey", "bytes": "720" }, { "name": "Batchfile", "bytes": "118907" }, { "name": "C", "bytes": "3196521" }, { "name": "C#", "bytes": "83" }, { "name": "C++", "bytes": "308860" }, { "name": "COBOL", "bytes": "4" }, { "name": "CSS", "bytes": "1050129" }, { "name": "Cirru", "bytes": "520" }, { "name": "Clojure", "bytes": "794" }, { "name": "CoffeeScript", "bytes": "403" }, { "name": "ColdFusion", "bytes": "86" }, { "name": "Common Lisp", "bytes": "632" }, { "name": "D", "bytes": "324" }, { "name": "Dart", "bytes": "489" }, { "name": "Dockerfile", "bytes": "10981" }, { "name": "Eiffel", "bytes": "375" }, { "name": "Elixir", "bytes": "692" }, { "name": "Elm", "bytes": "487" }, { "name": "Emacs Lisp", "bytes": "411907" }, { "name": "Erlang", "bytes": "487" }, { "name": "Forth", "bytes": "979" }, { "name": "FreeMarker", "bytes": "1017" }, { "name": "G-code", "bytes": "521" }, { "name": "GLSL", "bytes": "512" }, { "name": "Genshi", "bytes": "946" }, { "name": "Gherkin", "bytes": "699" }, { "name": "Go", "bytes": "7312" }, { "name": "Groovy", "bytes": "1080" }, { "name": "HTML", "bytes": "24999718" }, { "name": "Haskell", "bytes": "512" }, { "name": "Haxe", "bytes": "447" }, { "name": "HiveQL", "bytes": "43" }, { "name": "Io", "bytes": "140" }, { "name": "JSONiq", "bytes": "4" }, { "name": "Java", "bytes": "471854" }, { "name": "JavaScript", "bytes": "28075556" }, { "name": "Julia", "bytes": "210" }, { "name": "Jupyter Notebook", "bytes": "73168" }, { "name": "LSL", "bytes": "2080" }, { "name": "Lean", "bytes": "213" }, { "name": "Lex", "bytes": "264449" }, { "name": "Liquid", "bytes": "1883" }, { "name": "LiveScript", "bytes": "5747" }, { "name": "Lua", "bytes": "78382" }, { "name": "M4", "bytes": "1377" }, { "name": "MATLAB", "bytes": "203" }, { "name": "Makefile", "bytes": "269655" }, { "name": "Mako", "bytes": "3614942" }, { "name": "Mask", "bytes": "597" }, { "name": "Myghty", "bytes": "936" }, { "name": "Nix", "bytes": "2212" }, { "name": "OCaml", "bytes": "539" }, { "name": "Objective-C", "bytes": "2672" }, { "name": "OpenSCAD", "bytes": "333" }, { "name": "PHP", "bytes": "662" }, { "name": "PLSQL", "bytes": "31565" }, { "name": "PLpgSQL", "bytes": "6006" }, { "name": "Pascal", "bytes": "1412" }, { "name": "Perl", "bytes": "4327" }, { "name": "PigLatin", "bytes": "371" }, { "name": "PowerShell", "bytes": "3204" }, { "name": "Python", "bytes": "76440000" }, { "name": "R", "bytes": "2445" }, { "name": "Roff", "bytes": "95764" }, { "name": "Ruby", "bytes": "1098" }, { "name": "Rust", "bytes": "495" }, { "name": "Scala", "bytes": "1541" }, { "name": "Scheme", "bytes": "559" }, { "name": "Shell", "bytes": "190718" }, { "name": "Smarty", "bytes": "130" }, { "name": "TSQL", "bytes": "10013" }, { "name": "Tcl", "bytes": "899" }, { "name": "TeX", "bytes": "165743" }, { "name": "Thrift", "bytes": "317058" }, { "name": "TypeScript", "bytes": "1607" }, { "name": "VBA", "bytes": "2884" }, { "name": "VBScript", "bytes": "938" }, { "name": "VHDL", "bytes": "830" }, { "name": "Vala", "bytes": "485" }, { "name": "Verilog", "bytes": "274" }, { "name": "Vim Snippet", "bytes": "226931" }, { "name": "XQuery", "bytes": "114" }, { "name": "XSLT", "bytes": "521413" }, { "name": "Yacc", "bytes": "2133855" } ], "symlink_target": "" }
This is the repo for my personal website, [svdb.co](https://svdb.co). &mdash; [@svdb](https://twitter.com/svdb) The MIT License (MIT) Copyright (c) 2016 Sjaak van den Berg <mail@svdb.co> 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.
{ "content_hash": "4c9040581d5906c39e7ec9c079160e3f", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 74, "avg_line_length": 46.73076923076923, "alnum_prop": 0.7893004115226337, "repo_name": "sjaakvandenberg/sjaakvandenberg.github.io", "id": "a569c7318b56625befca9cf01fdfaecacf5e28ef", "size": "1226", "binary": false, "copies": "1", "ref": "refs/heads/source", "path": "source/README.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "21249" }, { "name": "HTML", "bytes": "7889" } ], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.7"/> <title>App Engine Python SDK: google.appengine.ext.testbed.Error Class Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> <link href="common.css" rel="stylesheet" type="text/css"/> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectlogo"><img alt="Logo" src="gae-python.logo.png"/></td> <td style="padding-left: 0.5em;"> <div id="projectname">App Engine Python SDK &#160;<span id="projectnumber">v1.6.9 rev.445</span> </div> <div id="projectbrief">The Python runtime is available as an experimental Preview feature.</div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.7 --> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><b>google</b></li><li class="navelem"><b>appengine</b></li><li class="navelem"><b>ext</b></li><li class="navelem"><b>testbed</b></li><li class="navelem"><a class="el" href="classgoogle_1_1appengine_1_1ext_1_1testbed_1_1_error.html">Error</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="headertitle"> <div class="title">google.appengine.ext.testbed.Error Class Reference</div> </div> </div><!--header--> <div class="contents"> <div class="dynheader"> Inheritance diagram for google.appengine.ext.testbed.Error:</div> <div class="dyncontent"> <div class="center"> <img src="classgoogle_1_1appengine_1_1ext_1_1testbed_1_1_error.png" usemap="#google.appengine.ext.testbed.Error_map" alt=""/> <map id="google.appengine.ext.testbed.Error_map" name="google.appengine.ext.testbed.Error_map"> <area href="classgoogle_1_1appengine_1_1ext_1_1testbed_1_1_not_activated_error.html" alt="google.appengine.ext.testbed.NotActivatedError" shape="rect" coords="0,112,313,136"/> <area href="classgoogle_1_1appengine_1_1ext_1_1testbed_1_1_stub_not_supported_error.html" alt="google.appengine.ext.testbed.StubNotSupportedError" shape="rect" coords="323,112,636,136"/> </map> </div></div> <a name="details" id="details"></a><h2 class="groupheader">Detailed Description</h2> <div class="textblock"><pre class="fragment">Base testbed error type.</pre> </div><hr/>The documentation for this class was generated from the following file:<ul> <li>code/googleappengine-read-only/python/google/appengine/ext/testbed/__init__.py</li> </ul> </div><!-- contents --> <address class="footer"> <small>Maintained by <a href="http://www.tzmartin.com">tzmartin</a></small> </address>
{ "content_hash": "ac465b3a229a362b05418c9950396ce9", "timestamp": "", "source": "github", "line_count": 60, "max_line_length": 273, "avg_line_length": 51.38333333333333, "alnum_prop": 0.6993188452805709, "repo_name": "tzmartin/gae-python.docset", "id": "4ec808ba8c2fbae0d29b880c24f486c84472b3f1", "size": "3083", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Contents/Resources/Documents/classgoogle_1_1appengine_1_1ext_1_1testbed_1_1_error.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "26526" }, { "name": "JavaScript", "bytes": "3140" } ], "symlink_target": "" }
local ffi = require 'ffi' local Threads = require 'threads' Threads.serialization('threads.sharedserialize') -- This script contains the logic to create K threads for parallel data-loading. -- For the data-loading details, look at donkey.lua ------------------------------------------------------------------------------- do -- start K datathreads (donkeys) if opt.nDonkeys > 0 then local options = opt -- make an upvalue to serialize over to donkey threads donkeys = Threads( opt.nDonkeys, function() require 'torch' end, function(idx) opt = options -- pass to all donkeys via upvalue tid = idx local seed = opt.manualSeed + idx torch.manualSeed(seed) print(string.format('Starting donkey with id: %d seed: %d', tid, seed)) paths.dofile('donkey.lua') end ); else -- single threaded data loading. useful for debugging paths.dofile('donkey.lua') donkeys = {} function donkeys:addjob(f1, f2) f2(f1()) end function donkeys:synchronize() end end end nClasses = nil classes = nil donkeys:addjob(function() return trainLoader.classes end, function(c) classes = c end) donkeys:synchronize() nClasses = #classes assert(nClasses, "Failed to get nClasses") assert(nClasses == opt.nClasses, "nClasses is reported different in the data loader, and in the commandline options") print('nClasses: ', nClasses) torch.save(paths.concat(opt.save, 'classes.t7'), classes) nTest = 0 donkeys:addjob(function() return testLoader:size() end, function(c) nTest = c end) donkeys:synchronize() assert(nTest > 0, "Failed to get nTest") print('nTest: ', nTest)
{ "content_hash": "b10003c623477e32ccb2f7d8f88d2e92", "timestamp": "", "source": "github", "line_count": 48, "max_line_length": 91, "avg_line_length": 35.895833333333336, "alnum_prop": 0.6331979106210098, "repo_name": "gyoho/cnn-object-recognition", "id": "853531ef4dc9b5f85adf89229d7d7f074ebd2b0f", "size": "1724", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/ImageNet/data.lua", "mode": "33188", "license": "mit", "language": [ { "name": "Jupyter Notebook", "bytes": "29326" }, { "name": "Lua", "bytes": "31102" } ], "symlink_target": "" }
#include "rolestats.h" #include "rolecalcminmax.h" #include "rolecalcrecenter.h" using std::unique_copy; using std::distance; using std::accumulate; RoleStats::RoleStats(const QVector<double> &unsorted, const double invalid_value, const bool override) : m_null_rating(-1) , m_invalid(invalid_value) , m_override(override) { set_list(unsorted); } void RoleStats::set_list(const QVector<double> &unsorted){ m_total_count = static_cast<double>(unsorted.size()); set_mode(unsorted); } void RoleStats::set_mode(const QVector<double> &unsorted){ m_valid = unsorted; qSort(m_valid); bool skewed = false; double valid_size = m_valid.size(); m_median = RoleCalcBase::find_median(m_valid); if(!m_override){ double first_quartile = m_valid.at((int)m_valid.size()/4.0); skewed = (m_median == first_quartile); QVector<double>::iterator valid_start = m_valid.begin(); if(m_valid.first() <= m_invalid){ valid_start = qUpperBound(m_valid.begin(),m_valid.end(),m_valid.first()); m_valid.erase(m_valid.begin(),valid_start); } valid_size = static_cast<double>(m_valid.size()); if(valid_size <= 0) return; if(skewed){ //count of distinct valid values QVector<double> uniques(valid_size); QVector<double>::Iterator u_end; u_end = unique_copy(m_valid.begin(),m_valid.end(),uniques.begin()); int unique_count = distance(uniques.begin(),u_end); float perc_unique = unique_count / valid_size; if(perc_unique < 0.25){ //rankecdf m_calc = QSharedPointer<RoleCalcBase>(new RoleCalcBase(m_valid)); LOGV << " - using only ecdfrank"; }else{ //rankecdf and min/max m_calc = QSharedPointer<RoleCalcBase>(new RoleCalcMinMax(m_valid)); LOGV << " - using a combination of ecdfrank and minmax"; } }else{ //rankecdf and recenter LOGV << " - using a combination of ecdfrank and recenter"; m_calc = QSharedPointer<RoleCalcBase>(new RoleCalcRecenter(m_valid)); } }else{ LOGV << " - using basic range transform"; } bool print_debug_info = (DT->get_log_manager()->get_appender("core")->minimum_level() <= LL_VERBOSE); if(print_debug_info){ RoleCalcBase tmp(m_valid); double tmp_total = 0; foreach(double val, m_valid){ tmp_total += tmp.base_rating(val); } double tmp_avg = tmp_total / m_valid.size(); LOGV << " - base avg:" << tmp_avg; } double total = 0.0; if(skewed && !m_calc.isNull()){ for(QVector<double>::const_iterator it = m_valid.begin() ; it != m_valid.end() ; it++){ total += m_calc->rating(*it); } m_null_rating = ((m_total_count * 0.5f) - total) / (m_total_count - valid_size); LOGV << " - null rating:" << m_null_rating; } if(print_debug_info){ if(total <= 0){ foreach(double val, m_valid){ total += get_rating(val); } } if(m_null_rating != -1) total += ((m_total_count - valid_size) * m_null_rating); LOGV << " - total raw values:" << m_total_count; LOGV << " - median raw values:" << m_median; LOGV << " - average of valid raw values:" << accumulate(m_valid.begin(),m_valid.end(),0.0) / valid_size; LOGV << " - min raw valid value:" << m_valid.first() << "max raw valid value:" << m_valid.last(); LOGV << " - min rating:" << (m_null_rating > 0 ? m_null_rating : get_rating(m_valid.first())) << "max rating:" << get_rating(m_valid.last()); LOGV << " - average of final ratings:" << (total / m_total_count); LOGV << " ------------------------------"; } } double RoleStats::get_rating(double val){ if(!m_calc.isNull()){ if(val <= m_invalid && m_null_rating != -1){ return m_null_rating; }else{ return m_calc->rating(val); } }else{ if(m_override){ return RoleCalcBase::range_transform(val,m_valid.first(),m_median,m_valid.last()); }else{ return 0.0; } } }
{ "content_hash": "9fa7baa016c7bc20ea8d30d685b8933d", "timestamp": "", "source": "github", "line_count": 125, "max_line_length": 153, "avg_line_length": 35.304, "alnum_prop": 0.5386358486290506, "repo_name": "splintermind/Dwarf-Therapist", "id": "b8ee1aa0140f403c0a14ff82d2cc19e7107b96f0", "size": "5496", "binary": false, "copies": "1", "ref": "refs/heads/DF2016", "path": "src/rolestats.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "3101" }, { "name": "C++", "bytes": "1665057" }, { "name": "Lua", "bytes": "22211" }, { "name": "Objective-C++", "bytes": "10435" }, { "name": "Perl", "bytes": "26088" }, { "name": "QMake", "bytes": "12236" }, { "name": "Shell", "bytes": "6645" } ], "symlink_target": "" }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.iceberg.nessie; import com.facebook.presto.Session; import com.facebook.presto.iceberg.IcebergQueryRunner; import com.facebook.presto.testing.MaterializedResult; import com.facebook.presto.testing.QueryRunner; import com.facebook.presto.testing.containers.NessieContainer; import com.facebook.presto.tests.AbstractTestQueryFramework; import com.google.common.collect.ImmutableMap; import org.projectnessie.client.api.NessieApiV1; import org.projectnessie.client.http.HttpClientBuilder; import org.projectnessie.error.NessieConflictException; import org.projectnessie.error.NessieNotFoundException; import org.projectnessie.model.Branch; import org.projectnessie.model.LogResponse; import org.projectnessie.model.Reference; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.util.List; import static com.facebook.presto.iceberg.nessie.NessieTestUtil.nessieConnectorProperties; import static com.facebook.presto.testing.MaterializedResult.resultBuilder; import static com.facebook.presto.tests.QueryAssertions.assertEqualsIgnoreOrder; import static org.assertj.core.api.Assertions.assertThat; public class TestNessieMultiBranching extends AbstractTestQueryFramework { private NessieContainer nessieContainer; private NessieApiV1 nessieApiV1; @BeforeClass public void init() throws Exception { nessieContainer = NessieContainer.builder().build(); nessieContainer.start(); nessieApiV1 = HttpClientBuilder.builder().withUri(nessieContainer.getRestApiUri()).build(NessieApiV1.class); super.init(); } @AfterClass public void tearDown() { if (nessieContainer != null) { nessieContainer.stop(); } if (nessieApiV1 != null) { nessieApiV1.close(); } } @Override protected QueryRunner createQueryRunner() throws Exception { return IcebergQueryRunner.createIcebergQueryRunner(ImmutableMap.of(), nessieConnectorProperties(nessieContainer.getRestApiUri())); } @Test public void testWithUnknownBranch() { assertQueryFails(sessionOnRef("unknownRef"), "CREATE SCHEMA nessie_namespace", ".*Nessie ref 'unknownRef' does not exist.*"); } @Test(enabled = false) public void testNamespaceVisibility() throws NessieConflictException, NessieNotFoundException { Reference one = createBranch("branchOne"); Reference two = createBranch("branchTwo"); Session sessionOne = sessionOnRef(one.getName()); Session sessionTwo = sessionOnRef(two.getName()); assertQuerySucceeds(sessionOne, "CREATE SCHEMA namespace_one"); assertThat(computeActual(sessionOne, "SHOW SCHEMAS FROM iceberg LIKE 'namespace_one'").getMaterializedRows()).hasSize(1); assertQuerySucceeds(sessionTwo, "CREATE SCHEMA namespace_two"); assertThat(computeActual(sessionTwo, "SHOW SCHEMAS FROM iceberg LIKE 'namespace_two'").getMaterializedRows()).hasSize(1); // namespace_two shouldn't be visible on branchOne assertThat(computeActual(sessionOne, "SHOW SCHEMAS FROM iceberg LIKE 'namespace_two'").getMaterializedRows()).isEmpty(); // namespace_one shouldn't be visible on branchTwo assertThat(computeActual(sessionTwo, "SHOW SCHEMAS FROM iceberg LIKE 'namespace_one'").getMaterializedRows()).isEmpty(); } @Test(enabled = false) public void testTableDataVisibility() throws NessieConflictException, NessieNotFoundException { assertQuerySucceeds("CREATE SCHEMA namespace_one"); assertQuerySucceeds("CREATE TABLE namespace_one.tbl (a int)"); assertQuerySucceeds("INSERT INTO namespace_one.tbl (a) VALUES (1)"); assertQuerySucceeds("INSERT INTO namespace_one.tbl (a) VALUES (2)"); Reference one = createBranch("branchOneWithTable"); Reference two = createBranch("branchTwoWithTable"); Session sessionOne = sessionOnRef(one.getName()); Session sessionTwo = sessionOnRef(two.getName()); assertQuerySucceeds(sessionOne, "INSERT INTO namespace_one.tbl (a) VALUES (3)"); assertQuerySucceeds(sessionTwo, "INSERT INTO namespace_one.tbl (a) VALUES (5)"); assertQuerySucceeds(sessionTwo, "INSERT INTO namespace_one.tbl (a) VALUES (6)"); // main branch should still have 2 entries assertThat(computeScalar("SELECT count(*) FROM namespace_one.tbl")).isEqualTo(2L); MaterializedResult rows = computeActual("SELECT * FROM namespace_one.tbl"); assertThat(rows.getMaterializedRows()).hasSize(2); assertEqualsIgnoreOrder(rows.getMaterializedRows(), resultBuilder(getSession(), rows.getTypes()).row(1).row(2).build().getMaterializedRows()); // there should be 3 entries on this branch assertThat(computeScalar(sessionOne, "SELECT count(*) FROM namespace_one.tbl")).isEqualTo(3L); rows = computeActual(sessionOne, "SELECT * FROM namespace_one.tbl"); assertThat(rows.getMaterializedRows()).hasSize(3); assertEqualsIgnoreOrder(rows.getMaterializedRows(), resultBuilder(sessionOne, rows.getTypes()).row(1).row(2).row(3).build().getMaterializedRows()); // and 4 entries on this branch assertThat(computeScalar(sessionTwo, "SELECT count(*) FROM namespace_one.tbl")).isEqualTo(4L); rows = computeActual(sessionTwo, "SELECT * FROM namespace_one.tbl"); assertThat(rows.getMaterializedRows()).hasSize(4); assertEqualsIgnoreOrder(rows.getMaterializedRows(), resultBuilder(sessionTwo, rows.getTypes()).row(1).row(2).row(5).row(6).build().getMaterializedRows()); // retrieve the second to the last commit hash and query the table with that hash List<LogResponse.LogEntry> logEntries = nessieApiV1.getCommitLog().refName(two.getName()).get().getLogEntries(); assertThat(logEntries).isNotEmpty(); String hash = logEntries.get(1).getCommitMeta().getHash(); Session sessionTwoAtHash = sessionOnRef(two.getName(), hash); // at this hash there were only 3 rows assertThat(computeScalar(sessionTwoAtHash, "SELECT count(*) FROM namespace_one.tbl")).isEqualTo(3L); rows = computeActual(sessionTwoAtHash, "SELECT * FROM namespace_one.tbl"); assertThat(rows.getMaterializedRows()).hasSize(3); assertEqualsIgnoreOrder(rows.getMaterializedRows(), resultBuilder(sessionTwoAtHash, rows.getTypes()).row(1).row(2).row(5).build().getMaterializedRows()); } private Session sessionOnRef(String reference) { return Session.builder(getSession()).setCatalogSessionProperty("iceberg", "nessie_reference_name", reference).build(); } private Session sessionOnRef(String reference, String hash) { return Session.builder(getSession()).setCatalogSessionProperty("iceberg", "nessie_reference_name", reference).setCatalogSessionProperty("iceberg", "nessie_reference_hash", hash).build(); } private Reference createBranch(String branchName) throws NessieConflictException, NessieNotFoundException { Reference main = nessieApiV1.getReference().refName("main").get(); return nessieApiV1.createReference().sourceRefName(main.getName()).reference(Branch.of(branchName, main.getHash())).create(); } }
{ "content_hash": "0a31251f0d27e7b91e0caba08ea18a9d", "timestamp": "", "source": "github", "line_count": 167, "max_line_length": 194, "avg_line_length": 47.82634730538922, "alnum_prop": 0.7254288218354826, "repo_name": "prestodb/presto", "id": "87369f3ea97bd7933ee63c5f16d971a24c7600e7", "size": "7987", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "presto-iceberg/src/test/java/com/facebook/presto/iceberg/nessie/TestNessieMultiBranching.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "33331" }, { "name": "Batchfile", "bytes": "795" }, { "name": "C++", "bytes": "640275" }, { "name": "CMake", "bytes": "31361" }, { "name": "CSS", "bytes": "28319" }, { "name": "Dockerfile", "bytes": "1266" }, { "name": "HTML", "bytes": "29601" }, { "name": "Java", "bytes": "52940440" }, { "name": "JavaScript", "bytes": "286864" }, { "name": "Makefile", "bytes": "16617" }, { "name": "Mustache", "bytes": "17803" }, { "name": "NASL", "bytes": "11965" }, { "name": "PLSQL", "bytes": "85" }, { "name": "Python", "bytes": "39357" }, { "name": "Roff", "bytes": "52281" }, { "name": "Shell", "bytes": "38937" }, { "name": "Thrift", "bytes": "14675" } ], "symlink_target": "" }
using System; using System.Threading.Tasks; using Windows.Media.Playback; namespace AudioPlay.Platform { /// <summary> /// AudioPlay Implementation /// </summary> public class AudioPlayImplementation : IAudioPlay { MediaPlayer player = null; public void InitPalyer() { player = BackgroundMediaPlayer.Current; } public void Pasue() { if (player.CurrentState == MediaPlayerState.Playing && player.CanPause) { player.Pause(); } } public async Task PlayAsync(string fileUrl) { await Task.Run(() => { if (player == null) { InitPalyer(); player.SetUriSource(new Uri(fileUrl, UriKind.Absolute)); player.Play(); } else { if (player.CurrentState != MediaPlayerState.Playing) { player.Play(); } } }); } public void Stop() { if (player.CurrentState == MediaPlayerState.Playing) { player.Pause(); player = null; } } } }
{ "content_hash": "4ea499a4b1f650de6663aa6caf05b497", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 76, "avg_line_length": 24.763636363636362, "alnum_prop": 0.43171806167400884, "repo_name": "NewBLife/NewBlife.Core", "id": "461bb7ba7d683b8fea74fa5d75cc9c57cd1dced2", "size": "1362", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "AudioPlay/AudioPlay/AudioPlay.UWP/AudioPlayImplementation.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "75661" } ], "symlink_target": "" }
using Harvest.Net.Models; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace Harvest.Net { public partial interface IHarvestRestClient { IList<Payment> ListPayments(long invoiceId); Task<IList<Payment>> ListPaymentsAsync(long invoiceId); Payment Payment(long invoiceId, long paymentId); Task<Payment> PaymentAsync(long invoiceId, long paymentId); Payment CreatePayment(long invoiceId, decimal amount, DateTime paidAt, string notes = null); Task<Payment> CreatePaymentAsync(long invoiceId, decimal amount, DateTime paidAt, string notes = null); Payment CreatePayment(long invoiceId, PaymentOptions options); Task<Payment> CreatePaymentAsync(long invoiceId, PaymentOptions options); bool DeletePayment(long invoiceId, long paymentId); Task<bool> DeletePaymentAsync(long invoiceId, long paymentId); } }
{ "content_hash": "cd25ac70d321933885db1b944f719399", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 111, "avg_line_length": 31.333333333333332, "alnum_prop": 0.7319148936170212, "repo_name": "ithielnor/harvest.net", "id": "106bc38257fa5324ce5730bd86cb023a88bfd36c", "size": "942", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Harvest.Net/ResourceInterfaces/InvoicePayments.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "419362" }, { "name": "PowerShell", "bytes": "2199" } ], "symlink_target": "" }
mocha-async-fail ================
{ "content_hash": "7736a90713620bf22a751f2602126dd3", "timestamp": "", "source": "github", "line_count": 2, "max_line_length": 16, "avg_line_length": 17, "alnum_prop": 0.4117647058823529, "repo_name": "emirotin/mocha-async-fail", "id": "3d25f079c43de1bee6d62832e9d3ad8a2a56615b", "size": "34", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "1633" } ], "symlink_target": "" }
import {Injectable, Injector} from '@angular/core'; import {NgbModalOptions, NgbModalConfig} from './modal-config'; import {NgbModalRef} from './modal-ref'; import {NgbModalStack} from './modal-stack'; /** * A service for opening modal windows. * * Creating a modal is straightforward: create a component or a template and pass it as an argument to * the `.open()` method. */ @Injectable({providedIn: 'root'}) export class NgbModal { constructor(private _injector: Injector, private _modalStack: NgbModalStack, private _config: NgbModalConfig) {} /** * Opens a new modal window with the specified content and supplied options. * * Content can be provided as a `TemplateRef` or a component type. If you pass a component type as content, * then instances of those components can be injected with an instance of the `NgbActiveModal` class. You can then * use `NgbActiveModal` methods to close / dismiss modals from "inside" of your component. * * Also see the [`NgbModalOptions`](#/components/modal/api#NgbModalOptions) for the list of supported options. */ open(content: any, options: NgbModalOptions = {}): NgbModalRef { const combinedOptions = {...this._config, animation: this._config.animation, ...options}; return this._modalStack.open(this._injector, content, combinedOptions); } /** * Returns an observable that holds the active modal instances. */ get activeInstances() { return this._modalStack.activeInstances; } /** * Dismisses all currently displayed modal windows with the supplied reason. * * @since 3.1.0 */ dismissAll(reason?: any) { this._modalStack.dismissAll(reason); } /** * Indicates if there are currently any open modal windows in the application. * * @since 3.3.0 */ hasOpenModals(): boolean { return this._modalStack.hasOpenModals(); } }
{ "content_hash": "66a0d94890a885ce11d872d27c6a6971", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 116, "avg_line_length": 37.83673469387755, "alnum_prop": 0.7098166127292341, "repo_name": "fbasso/ng-bootstrap", "id": "97e299db29f16888abaa4843bba45a14a1eb3e33", "size": "1854", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/modal/modal.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2096" }, { "name": "EJS", "bytes": "21493" }, { "name": "HTML", "bytes": "33829" }, { "name": "JavaScript", "bytes": "8229" }, { "name": "SCSS", "bytes": "4758" }, { "name": "Shell", "bytes": "2078" }, { "name": "TypeScript", "bytes": "1706122" } ], "symlink_target": "" }
%% isTransient(object) % returns (false) if object is static, (true) else % % INPUT % object : |EnsightLib| object % % OUTPUT % result : (bool) true(multiple timesteps)/false(single timestep) % % USAGE % tra = object.isTransient % %% function ok = isTransient(this) ok = length(this.timeSteps) > 1; end
{ "content_hash": "fe78d08688396a869fdea67592a8d87a", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 66, "avg_line_length": 18.176470588235293, "alnum_prop": 0.6828478964401294, "repo_name": "ITWM-TVFS/Ensight4Matlab", "id": "2d63c44320a9b98cfefd6cc72d2e96910f5b23a1", "size": "309", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "EnsightMatlab/@EnsightLib/isTransient.m", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "399986" }, { "name": "GLSL", "bytes": "1584138" }, { "name": "Matlab", "bytes": "74986" }, { "name": "QMake", "bytes": "5268" }, { "name": "TeX", "bytes": "767" } ], "symlink_target": "" }
<component name="libraryTable"> <library name="runner-0.5"> <ANNOTATIONS> <root url="jar://$PROJECT_DIR$/app/build/intermediates/exploded-aar/com.android.support.test/runner/0.5/annotations.zip!/" /> </ANNOTATIONS> <CLASSES> <root url="jar://$PROJECT_DIR$/app/build/intermediates/exploded-aar/com.android.support.test/runner/0.5/jars/classes.jar!/" /> <root url="file://$PROJECT_DIR$/app/build/intermediates/exploded-aar/com.android.support.test/runner/0.5/res" /> </CLASSES> <JAVADOC /> <SOURCES> <root url="jar://$USER_HOME$/SoftWare/Android/Sdk/extras/android/m2repository/com/android/support/test/runner/0.5/runner-0.5-sources.jar!/" /> </SOURCES> </library> </component>
{ "content_hash": "d52657687352359b6f4470cdb71332be", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 148, "avg_line_length": 48.733333333333334, "alnum_prop": 0.6839945280437757, "repo_name": "sunyb3/EasyWeather", "id": "7da9321755d713cb781201c70aedfaa36cad29c3", "size": "731", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": ".idea/libraries/runner_0_5.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "29324" } ], "symlink_target": "" }
package javaProbs; /** * Created by: david * Date: 12/31/2017, 8:21 PM */ public class Solution_557_ReverseWords3 { /* My solution below */ /** * Reverses individual words in a String * * @param s - String to have individual words reversed * @return - A String where the original has the words reversed but in the same order the words appear. */ public static String reverseWords(String s) { String[] original = s.split(" "); String reversedString = ""; for (int i = 0; i < original.length; i++) { original[i] = reverseOneWord(original[i]); if (i != (original.length - 1)) { reversedString += (original[i] + " "); } else { reversedString += (original[i]); } } return reversedString; } /** * Reverses a single String * * @param s - String word to be reversed * @return - The word reversed */ public static String reverseOneWord(String s) { String reversed = ""; for (int i = 0; i < s.length(); i++) { reversed += s.charAt(s.length() - i - 1); } return reversed; } /** * Main test * * @param args */ public static void main(String[] args) { String word = "Let's take LeetCode contest"; word = reverseWords(word); System.out.println(word); } /* My solution above */ }
{ "content_hash": "a2cc8ee4064de19cf3e115f4fe3d3f1b", "timestamp": "", "source": "github", "line_count": 67, "max_line_length": 107, "avg_line_length": 23.119402985074625, "alnum_prop": 0.5054874112330536, "repo_name": "DJ-Tai/practice-problems", "id": "1e64862010c7ae7478c6fed36e0f3df1b16b4a29", "size": "1549", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "leet-code/java/javaProbs/Solution_557_ReverseWords3.java", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "2231" }, { "name": "C++", "bytes": "1974" }, { "name": "Java", "bytes": "38839" }, { "name": "Python", "bytes": "1996" } ], "symlink_target": "" }
<?php /* Unsafe sample input : get the field userData from the variable $_GET via an object, which store it in a array sanitize : use of the function htmlentities. Sanitizes the query but has a high chance to produce unexpected results construction : concatenation with simple quote */ /*Copyright 2015 Bertrand STIVALET Permission is hereby granted, without written agreement or royalty fee, to use, copy, modify, and distribute this software and its documentation for any purpose, provided that the above copyright notice and the following three paragraphs appear in all copies of this software. IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.*/ class Input{ private $input; public function getInput(){ return $this->input[1]; } public function __construct(){ $this->input = array(); $this->input[0]= 'safe' ; $this->input[1]= $_GET['UserData'] ; $this->input[2]= 'safe' ; } } $temp = new Input(); $tainted = $temp->getInput(); $tainted = htmlentities($tainted, ENT_QUOTES); $query = "!name='". $tainted . "'"; //flaw $ds=ldap_connect("localhost"); $r=ldap_bind($ds); $sr=ldap_search($ds,"o=My Company, c=US", $query); ldap_close($ds); ?>
{ "content_hash": "8db9c28951eecc5566390baebd006fca", "timestamp": "", "source": "github", "line_count": 72, "max_line_length": 116, "avg_line_length": 24.041666666666668, "alnum_prop": 0.7273252455228192, "repo_name": "stivalet/PHP-Vulnerability-test-suite", "id": "e8e27f34b85c37e963d70c77cd1c9413b162295d", "size": "1731", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Injection/CWE_90/unsafe/CWE_90__object-Array__func_htmlentities__not_name-concatenation_simple_quote.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "64184004" } ], "symlink_target": "" }
///////////////////////////////////////////////////////////////////////////// // Copyright (c) Electronic Arts Inc. All rights reserved. ///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// // This file implements some of the primary algorithms from the C++ STL // algorithm library. These versions are just like that STL versions and so // are redundant. They are provided solely for the purpose of projects that // either cannot use standard C++ STL or want algorithms that have guaranteed // identical behaviour across platforms. /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// // Definitions // // You will notice that we are very particular about the templated typenames // we use here. You will notice that we follow the C++ standard closely in // these respects. Each of these typenames have a specific meaning; // this is why we don't just label templated arguments with just letters // such as T, U, V, A, B. Here we provide a quick reference for the typenames // we use. See the C++ standard, section 25-8 for more details. // -------------------------------------------------------------- // typename Meaning // -------------------------------------------------------------- // T The value type. // Compare A function which takes two arguments and returns the lesser of the two. // Predicate A function which takes one argument returns true if the argument meets some criteria. // BinaryPredicate A function which takes two arguments and returns true if some criteria is met (e.g. they are equal). // StrickWeakOrdering A BinaryPredicate that compares two objects, returning true if the first precedes the second. Like Compare but has additional requirements. Used for sorting routines. // Function A function which takes one argument and applies some operation to the target. // Size A count or size. // Generator A function which takes no arguments and returns a value (which will usually be assigned to an object). // UnaryOperation A function which takes one argument and returns a value (which will usually be assigned to second object). // BinaryOperation A function which takes two arguments and returns a value (which will usually be assigned to a third object). // InputIterator An input iterator (iterator you read from) which allows reading each element only once and only in a forward direction. // ForwardIterator An input iterator which is like InputIterator except it can be reset back to the beginning. // BidirectionalIterator An input iterator which is like ForwardIterator except it can be read in a backward direction as well. // RandomAccessIterator An input iterator which can be addressed like an array. It is a superset of all other input iterators. // OutputIterator An output iterator (iterator you write to) which allows writing each element only once in only in a forward direction. // // Note that with iterators that a function which takes an InputIterator will // also work with a ForwardIterator, BidirectionalIterator, or RandomAccessIterator. // The given iterator type is merely the -minimum- supported functionality the // iterator must support. /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// // Optimizations // // There are a number of opportunities for opptimizations that we take here // in this library. The most obvious kinds are those that subsitute memcpy // in the place of a conventional loop for data types with which this is // possible. The algorithms here are optimized to a higher level than currently // available C++ STL algorithms from vendors such as Microsoft. This is especially // so for game programming on console devices, as we do things such as reduce // branching relative to other STL algorithm implementations. However, the // proper implementation of these algorithm optimizations is a fairly tricky // thing. // // The various things we look to take advantage of in order to implement // optimizations include: // - Taking advantage of random access iterators. // - Taking advantage of POD (plain old data) data types. // - Taking advantage of type_traits in general. // - Reducing branching and taking advantage of likely branch predictions. // - Taking advantage of issues related to pointer and reference aliasing. // - Improving cache coherency during memory accesses. // - Making code more likely to be inlinable by the compiler. // /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// // Supported Algorithms // // Algorithms that we implement are listed here. Note that these items are not // all within this header file, as we split up the header files in order to // improve compilation performance. Items marked with '+' are items that are // extensions which don't exist in the C++ standard. // // ------------------------------------------------------------------------------- // Algorithm Notes // ------------------------------------------------------------------------------- // adjacent_find // adjacent_find<Compare> // all_of C++11 // any_of C++11 // none_of C++11 // binary_search // binary_search<Compare> // +binary_search_i // +binary_search_i<Compare> // +change_heap Found in heap.h // +change_heap<Compare> Found in heap.h // copy // copy_if C++11 // copy_n C++11 // copy_backward // count // count_if // equal // equal<Compare> // equal_range // equal_range<Compare> // fill // fill_n // find // find_end // find_end<Compare> // find_first_of // find_first_of<Compare> // +find_first_not_of // +find_first_not_of<Compare> // +find_last_of // +find_last_of<Compare> // +find_last_not_of // +find_last_not_of<Compare> // find_if // find_if_not // for_each // generate // generate_n // +identical // +identical<Compare> // iter_swap // lexicographical_compare // lexicographical_compare<Compare> // lower_bound // lower_bound<Compare> // make_heap Found in heap.h // make_heap<Compare> Found in heap.h // min // min<Compare> // max // max<Compare> // +min_alt Exists to work around the problem of conflicts with min/max #defines on some systems. // +min_alt<Compare> // +max_alt // +max_alt<Compare> // +median // +median<Compare> // merge Found in sort.h // merge<Compare> Found in sort.h // min_element // min_element<Compare> // max_element // max_element<Compare> // mismatch // mismatch<Compare> // move // move_backward // nth_element Found in sort.h // nth_element<Compare> Found in sort.h // partial_sort Found in sort.h // partial_sort<Compare> Found in sort.h // push_heap Found in heap.h // push_heap<Compare> Found in heap.h // pop_heap Found in heap.h // pop_heap<Compare> Found in heap.h // random_shuffle<Random> // remove // remove_if // remove_copy // remove_copy_if // +remove_heap Found in heap.h // +remove_heap<Compare> Found in heap.h // replace // replace_if // replace_copy // replace_copy_if // reverse_copy // reverse // rotate // rotate_copy // search // search<Compare> // search_n // set_difference // set_difference<Compare> // set_intersection // set_intersection<Compare> // set_symmetric_difference // set_symmetric_difference<Compare> // sort Found in sort.h // sort<Compare> Found in sort.h // sort_heap Found in heap.h // sort_heap<Compare> Found in heap.h // stable_sort Found in sort.h // stable_sort<Compare> Found in sort.h // swap // swap_ranges // transform // transform<Operation> // unique // unique<Compare> // upper_bound // upper_bound<Compare> // is_permutation // is_permutation<Predicate> // next_permutation // next_permutation<Compare> // // Algorithms from the C++ standard that we don't implement are listed here. // Most of these items are absent because they aren't used very often. // They also happen to be the more complicated than other algorithms. // However, we can implement any of these functions for users that might // need them. // includes // includes<Compare> // inplace_merge // inplace_merge<Compare> // partial_sort_copy // partial_sort_copy<Compare> // paritition // prev_permutation // prev_permutation<Compare> // random_shuffle // search_n<Compare> // set_union // set_union<Compare> // stable_partition // unique_copy // unique_copy<Compare> // /////////////////////////////////////////////////////////////////////////////// #ifndef EASTL_ALGORITHM_H #define EASTL_ALGORITHM_H #include <EASTL/internal/config.h> #include <EASTL/type_traits.h> #include <EASTL/internal/move_help.h> #include <EASTL/internal/copy_help.h> #include <EASTL/internal/fill_help.h> #include <EASTL/initializer_list.h> #include <EASTL/iterator.h> #include <EASTL/functional.h> #include <EASTL/utility.h> #include <EASTL/internal/generic_iterator.h> #include <EASTL/random.h> #ifdef _MSC_VER #pragma warning(push, 0) #if defined(EA_COMPILER_MICROSOFT) && (defined(EA_PROCESSOR_X86) || defined(EA_PROCESSOR_X86_64)) #include <intrin.h> #endif #endif #include <stddef.h> #include <string.h> // memcpy, memcmp, memmove #ifdef _MSC_VER #pragma warning(pop) #endif #if defined(EA_PRAGMA_ONCE_SUPPORTED) #pragma once // Some compilers (e.g. VC++) benefit significantly from using this. We've measured 3-4% build speed improvements in apps as a result. #endif /////////////////////////////////////////////////////////////////////////////// // min/max workaround // // MSVC++ has #defines for min/max which collide with the min/max algorithm // declarations. The following may still not completely resolve some kinds of // problems with MSVC++ #defines, though it deals with most cases in production // game code. // #if EASTL_NOMINMAX #ifdef min #undef min #endif #ifdef max #undef max #endif #endif namespace eastl { /// min_element /// /// min_element finds the smallest element in the range [first, last). /// It returns the first iterator i in [first, last) such that no other /// iterator in [first, last) points to a value smaller than *i. /// The return value is last if and only if [first, last) is an empty range. /// /// Returns: The first iterator i in the range [first, last) such that /// for any iterator j in the range [first, last) the following corresponding /// condition holds: !(*j < *i). /// /// Complexity: Exactly 'max((last - first) - 1, 0)' applications of the /// corresponding comparisons. /// template <typename ForwardIterator> ForwardIterator min_element(ForwardIterator first, ForwardIterator last) { if(first != last) { ForwardIterator currentMin = first; while(++first != last) { if(*first < *currentMin) currentMin = first; } return currentMin; } return first; } /// min_element /// /// min_element finds the smallest element in the range [first, last). /// It returns the first iterator i in [first, last) such that no other /// iterator in [first, last) points to a value smaller than *i. /// The return value is last if and only if [first, last) is an empty range. /// /// Returns: The first iterator i in the range [first, last) such that /// for any iterator j in the range [first, last) the following corresponding /// conditions hold: compare(*j, *i) == false. /// /// Complexity: Exactly 'max((last - first) - 1, 0)' applications of the /// corresponding comparisons. /// template <typename ForwardIterator, typename Compare> ForwardIterator min_element(ForwardIterator first, ForwardIterator last, Compare compare) { if(first != last) { ForwardIterator currentMin = first; while(++first != last) { if(compare(*first, *currentMin)) currentMin = first; } return currentMin; } return first; } /// max_element /// /// max_element finds the largest element in the range [first, last). /// It returns the first iterator i in [first, last) such that no other /// iterator in [first, last) points to a value greater than *i. /// The return value is last if and only if [first, last) is an empty range. /// /// Returns: The first iterator i in the range [first, last) such that /// for any iterator j in the range [first, last) the following corresponding /// condition holds: !(*i < *j). /// /// Complexity: Exactly 'max((last - first) - 1, 0)' applications of the /// corresponding comparisons. /// template <typename ForwardIterator> ForwardIterator max_element(ForwardIterator first, ForwardIterator last) { if(first != last) { ForwardIterator currentMax = first; while(++first != last) { if(*currentMax < *first) currentMax = first; } return currentMax; } return first; } /// max_element /// /// max_element finds the largest element in the range [first, last). /// It returns the first iterator i in [first, last) such that no other /// iterator in [first, last) points to a value greater than *i. /// The return value is last if and only if [first, last) is an empty range. /// /// Returns: The first iterator i in the range [first, last) such that /// for any iterator j in the range [first, last) the following corresponding /// condition holds: compare(*i, *j) == false. /// /// Complexity: Exactly 'max((last - first) - 1, 0)' applications of the /// corresponding comparisons. /// template <typename ForwardIterator, typename Compare> ForwardIterator max_element(ForwardIterator first, ForwardIterator last, Compare compare) { if(first != last) { ForwardIterator currentMax = first; while(++first != last) { if(compare(*currentMax, *first)) currentMax = first; } return currentMax; } return first; } #if EASTL_MINMAX_ENABLED /// min /// /// Min returns the lesser of its two arguments; it returns the first /// argument if neither is less than the other. The two arguments are /// compared with operator <. /// /// This min and our other min implementations are defined as returning: /// b < a ? b : a /// which for example may in practice result in something different than: /// b <= a ? b : a /// in the case where b is different from a (though they compare as equal). /// We choose the specific ordering here because that's the ordering /// done by other STL implementations. /// /// Some compilers (e.g. VS20003 - VS2013) generate poor code for the case of /// scalars returned by reference, so we provide a specialization for those cases. /// The specialization returns T by value instead of reference, which is /// not that the Standard specifies. The Standard allows you to use /// an expression like &max(x, y), which would be impossible in this case. /// However, we have found no actual code that uses min or max like this and /// this specialization causes no problems in practice. Microsoft has acknowledged /// the problem and may fix it for a future VS version. /// template <typename T> inline EA_CONSTEXPR typename eastl::enable_if<eastl::is_scalar<T>::value, T>::type min(T a, T b) { return b < a ? b : a; } template <typename T> inline typename eastl::enable_if<!eastl::is_scalar<T>::value, const T&>::type min(const T& a, const T& b) { return b < a ? b : a; } #if defined(_MSC_VER) && defined(EA_PROCESSOR_POWERPC) inline float min(float a, float b) { return (float)__fsel(a - b, b, a); } inline double min(double a, double b) { return (double)__fsel(a - b, b, a); } #elif defined(_MSC_VER) && defined(EA_PROCESSOR_X86) // We used to have x86 asm here, but it didn't improve performance. #elif defined(__GNUC__) && defined(EA_PROCESSOR_POWERPC) inline float min(float a, float b) { float result, test(a - b); __asm__ ("fsel %0, %1, %2, %3" : "=f" (result) : "f" (test), "f" (b), "f" (a)); return result; } inline double min(double a, double b) { double result, test(a - b); __asm__ ("fsel %0, %1, %2, %3" : "=f" (result) : "f" (test), "f" (b), "f" (a)); return result; } #else inline EA_CONSTEXPR float min(float a, float b) { return b < a ? b : a; } inline EA_CONSTEXPR double min(double a, double b) { return b < a ? b : a; } inline EA_CONSTEXPR long double min(long double a, long double b) { return b < a ? b : a; } #endif #endif // EASTL_MINMAX_ENABLED /// min_alt /// /// This is an alternative version of min that avoids any possible /// collisions with Microsoft #defines of min and max. /// /// See min(a, b) for detailed specifications. /// template <typename T> inline EA_CONSTEXPR typename eastl::enable_if<eastl::is_scalar<T>::value, T>::type min_alt(T a, T b) { return b < a ? b : a; } template <typename T> inline typename eastl::enable_if<!eastl::is_scalar<T>::value, const T&>::type min_alt(const T& a, const T& b) { return b < a ? b : a; } #if defined(_MSC_VER) && defined(EA_PROCESSOR_POWERPC) inline float min_alt(float a, float b) { return (float)__fsel(a - b, b, a); } inline double min_alt(double a, double b) { return (double)__fsel(a - b, b, a); } #elif defined(_MSC_VER) && defined(EA_PROCESSOR_X86) // We used to have x86 asm here, but it didn't improve performance. #elif defined(__GNUC__) && defined(EA_PROCESSOR_POWERPC) inline float min_alt(float a, float b) { float result, test(a - b); __asm__ ("fsel %0, %1, %2, %3" : "=f" (result) : "f" (test), "f" (b), "f" (a)); return result; } inline double min_alt(double a, double b) { double result, test(a - b); __asm__ ("fsel %0, %1, %2, %3" : "=f" (result) : "f" (test), "f" (b), "f" (a)); return result; } #else inline EA_CONSTEXPR float min_alt(float a, float b) { return b < a ? b : a; } inline EA_CONSTEXPR double min_alt(double a, double b) { return b < a ? b : a; } inline EA_CONSTEXPR long double min_alt(long double a, long double b) { return b < a ? b : a; } #endif #if EASTL_MINMAX_ENABLED /// min /// /// Min returns the lesser of its two arguments; it returns the first /// argument if neither is less than the other. The two arguments are /// compared with the Compare function (or function object), which /// takes two arguments and returns true if the first is less than /// the second. /// /// See min(a, b) for detailed specifications. /// /// Example usage: /// struct A{ int a; }; /// struct Struct{ bool operator()(const A& a1, const A& a2){ return a1.a < a2.a; } }; /// /// A a1, a2, a3; /// a3 = min(a1, a2, Struct()); /// /// Example usage: /// struct B{ int b; }; /// inline bool Function(const B& b1, const B& b2){ return b1.b < b2.b; } /// /// B b1, b2, b3; /// b3 = min(b1, b2, Function); /// template <typename T, typename Compare> inline const T& min(const T& a, const T& b, Compare compare) { return compare(b, a) ? b : a; } #endif // EASTL_MINMAX_ENABLED /// min_alt /// /// This is an alternative version of min that avoids any possible /// collisions with Microsoft #defines of min and max. /// /// See min(a, b) for detailed specifications. /// template <typename T, typename Compare> inline const T& min_alt(const T& a, const T& b, Compare compare) { return compare(b, a) ? b : a; } #if EASTL_MINMAX_ENABLED /// max /// /// Max returns the greater of its two arguments; it returns the first /// argument if neither is greater than the other. The two arguments are /// compared with operator < (and not operator >). /// /// This min and our other min implementations are defined as returning: /// a < b ? b : a /// which for example may in practice result in something different than: /// a <= b ? b : a /// in the case where b is different from a (though they compare as equal). /// We choose the specific ordering here because that's the ordering /// done by other STL implementations. /// template <typename T> inline EA_CONSTEXPR typename eastl::enable_if<eastl::is_scalar<T>::value, T>::type max(T a, T b) { return a < b ? b : a; } template <typename T> inline typename eastl::enable_if<!eastl::is_scalar<T>::value, const T&>::type max(const T& a, const T& b) { return a < b ? b : a; } #if defined(_MSC_VER) && defined(EA_PROCESSOR_POWERPC) inline float max(float a, float b) { return (float)__fsel(a - b, a, b); } inline double max(double a, double b) { return (double)__fsel(a - b, a, b); } #elif defined(_MSC_VER) && defined(EA_PROCESSOR_X86) // We used to have x86 asm here, but it didn't improve performance. #elif defined(__GNUC__) && defined(EA_PROCESSOR_POWERPC) inline float max(float a, float b) { float result, test(a - b); __asm__ ("fsel %0, %1, %2, %3" : "=f" (result) : "f" (test), "f" (a), "f" (b)); return result; } inline double max(double a, double b) { double result, test(a - b); __asm__ ("fsel %0, %1, %2, %3" : "=f" (result) : "f" (test), "f" (a), "f" (b)); return result; } #else inline EA_CONSTEXPR float max(float a, float b) { return a < b ? b : a; } inline EA_CONSTEXPR double max(double a, double b) { return a < b ? b : a; } inline EA_CONSTEXPR long double max(long double a, long double b) { return a < b ? b : a; } #endif #endif // EASTL_MINMAX_ENABLED /// max_alt /// /// This is an alternative version of max that avoids any possible /// collisions with Microsoft #defines of min and max. /// template <typename T> inline EA_CONSTEXPR typename eastl::enable_if<eastl::is_scalar<T>::value, T>::type max_alt(T a, T b) { return a < b ? b : a; } template <typename T> inline typename eastl::enable_if<!eastl::is_scalar<T>::value, const T&>::type max_alt(const T& a, const T& b) { return a < b ? b : a; } #if defined(_MSC_VER) && defined(EA_PROCESSOR_POWERPC) inline float max_alt(float a, float b) { return (float)__fsel(a - b, a, b); } inline double max_alt(double a, double b) { return (double)__fsel(a - b, a, b); } #elif defined(_MSC_VER) && defined(EA_PROCESSOR_X86) // We used to have x86 asm here, but it didn't improve performance. #elif defined(__GNUC__) && defined(EA_PROCESSOR_POWERPC) inline float max_alt(float a, float b) { float result, test(a - b); __asm__ ("fsel %0, %1, %2, %3" : "=f" (result) : "f" (test), "f" (a), "f" (b)); return result; } inline double max_alt(double a, double b) { double result, test(a - b); __asm__ ("fsel %0, %1, %2, %3" : "=f" (result) : "f" (test), "f" (a), "f" (b)); return result; } #else inline EA_CONSTEXPR float max_alt(float a, float b) { return a < b ? b : a; } inline EA_CONSTEXPR double max_alt(double a, double b) { return a < b ? b : a; } inline EA_CONSTEXPR long double max_alt(long double a, long double b) { return a < b ? b : a; } #endif #if EASTL_MINMAX_ENABLED /// max /// /// Min returns the lesser of its two arguments; it returns the first /// argument if neither is less than the other. The two arguments are /// compared with the Compare function (or function object), which /// takes two arguments and returns true if the first is less than /// the second. /// template <typename T, typename Compare> inline const T& max(const T& a, const T& b, Compare compare) { return compare(a, b) ? b : a; } #endif /// max_alt /// /// This is an alternative version of max that avoids any possible /// collisions with Microsoft #defines of min and max. /// template <typename T, typename Compare> inline const T& max_alt(const T& a, const T& b, Compare compare) { return compare(a, b) ? b : a; } /// min(std::initializer_list) /// template <typename T > T min(std::initializer_list<T> ilist) { return *eastl::min_element(ilist.begin(), ilist.end()); } /// min(std::initializer_list, Compare) /// template <typename T, typename Compare> T min(std::initializer_list<T> ilist, Compare compare) { return *eastl::min_element(ilist.begin(), ilist.end(), compare); } /// max(std::initializer_list) /// template <typename T > T max(std::initializer_list<T> ilist) { return *eastl::max_element(ilist.begin(), ilist.end()); } /// max(std::initializer_list, Compare) /// template <typename T, typename Compare> T max(std::initializer_list<T> ilist, Compare compare) { return *eastl::max_element(ilist.begin(), ilist.end(), compare); } /// minmax_element /// /// Returns: make_pair(first, first) if [first, last) is empty, otherwise make_pair(m, M), /// where m is the first iterator in [first,last) such that no iterator in the range /// refers to a smaller element, and where M is the last iterator in [first,last) such /// that no iterator in the range refers to a larger element. /// /// Complexity: At most max([(3/2)*(N - 1)], 0) applications of the corresponding predicate, /// where N is distance(first, last). /// template <typename ForwardIterator, typename Compare> eastl::pair<ForwardIterator, ForwardIterator> minmax_element(ForwardIterator first, ForwardIterator last, Compare compare) { eastl::pair<ForwardIterator, ForwardIterator> result(first, first); if(!(first == last) && !(++first == last)) { if(compare(*first, *result.first)) { result.second = result.first; result.first = first; } else result.second = first; while(++first != last) { ForwardIterator i = first; if(++first == last) { if(compare(*i, *result.first)) result.first = i; else if(!compare(*i, *result.second)) result.second = i; break; } else { if(compare(*first, *i)) { if(compare(*first, *result.first)) result.first = first; if(!compare(*i, *result.second)) result.second = i; } else { if(compare(*i, *result.first)) result.first = i; if(!compare(*first, *result.second)) result.second = first; } } } } return result; } template <typename ForwardIterator> eastl::pair<ForwardIterator, ForwardIterator> minmax_element(ForwardIterator first, ForwardIterator last) { typedef typename eastl::iterator_traits<ForwardIterator>::value_type value_type; return eastl::minmax_element(first, last, eastl::less<value_type>()); } /// minmax /// /// Requires: Type T shall be LessThanComparable. /// Returns: pair<const T&, const T&>(b, a) if b is smaller than a, and pair<const T&, const T&>(a, b) otherwise. /// Remarks: Returns pair<const T&, const T&>(a, b) when the arguments are equivalent. /// Complexity: Exactly one comparison. /// // The following optimization is a problem because it changes the return value in a way that would break // users unless they used auto (e.g. auto result = minmax(17, 33); ) // // template <typename T> // inline EA_CONSTEXPR typename eastl::enable_if<eastl::is_scalar<T>::value, eastl::pair<T, T> >::type // minmax(T a, T b) // { // return (b < a) ? eastl::make_pair(b, a) : eastl::make_pair(a, b); // } // // template <typename T> // inline typename eastl::enable_if<!eastl::is_scalar<T>::value, eastl::pair<const T&, const T&> >::type // minmax(const T& a, const T& b) // { // return (b < a) ? eastl::make_pair(b, a) : eastl::make_pair(a, b); // } // It turns out that the following conforming definition of minmax generates a warning when used with VC++ up // to at least VS2012. The VS2012 version of minmax is a broken and non-conforming definition, and we don't // want to do that. We could do it for scalars alone, though we'd have to decide if we are going to do that // for all compilers, because it changes the return value from a pair of references to a pair of values. template <typename T> inline eastl::pair<const T&, const T&> minmax(const T& a, const T& b) { return (b < a) ? eastl::make_pair(b, a) : eastl::make_pair(a, b); } template <typename T, typename Compare> eastl::pair<const T&, const T&> minmax(const T& a, const T& b, Compare compare) { return compare(b, a) ? eastl::make_pair(b, a) : eastl::make_pair(a, b); } template <typename T> eastl::pair<T, T> minmax(std::initializer_list<T> ilist) { typedef typename std::initializer_list<T>::iterator iterator_type; eastl::pair<iterator_type, iterator_type> iteratorPair = eastl::minmax_element(ilist.begin(), ilist.end()); return eastl::make_pair(*iteratorPair.first, *iteratorPair.second); } template <typename T, class Compare> eastl::pair<T, T> minmax(std::initializer_list<T> ilist, Compare compare) { typedef typename std::initializer_list<T>::iterator iterator_type; eastl::pair<iterator_type, iterator_type> iteratorPair = eastl::minmax_element(ilist.begin(), ilist.end(), compare); return eastl::make_pair(*iteratorPair.first, *iteratorPair.second); } template <typename T> inline T&& median_impl(T&& a, T&& b, T&& c) { if(a < b) { if(b < c) return eastl::forward<T>(b); else if(a < c) return eastl::forward<T>(c); else return eastl::forward<T>(a); } else if(a < c) return eastl::forward<T>(a); else if(b < c) return eastl::forward<T>(c); return eastl::forward<T>(b); } /// median /// /// median finds which element of three (a, b, d) is in-between the other two. /// If two or more elements are equal, the first (e.g. a before b) is chosen. /// /// Complexity: Either two or three comparisons will be required, depending /// on the values. /// template <typename T> inline const T& median(const T& a, const T& b, const T& c) { return median_impl(a, b, c); } /// median /// /// median finds which element of three (a, b, d) is in-between the other two. /// If two or more elements are equal, the first (e.g. a before b) is chosen. /// /// Complexity: Either two or three comparisons will be required, depending /// on the values. /// template <typename T> inline T&& median(T&& a, T&& b, T&& c) { return eastl::forward<T>(median_impl(eastl::forward<T>(a), eastl::forward<T>(b), eastl::forward<T>(c))); } template <typename T, typename Compare> inline T&& median_impl(T&& a, T&& b, T&& c, Compare compare) { if(compare(a, b)) { if(compare(b, c)) return eastl::forward<T>(b); else if(compare(a, c)) return eastl::forward<T>(c); else return eastl::forward<T>(a); } else if(compare(a, c)) return eastl::forward<T>(a); else if(compare(b, c)) return eastl::forward<T>(c); return eastl::forward<T>(b); } /// median /// /// median finds which element of three (a, b, d) is in-between the other two. /// If two or more elements are equal, the first (e.g. a before b) is chosen. /// /// Complexity: Either two or three comparisons will be required, depending /// on the values. /// template <typename T, typename Compare> inline const T& median(const T& a, const T& b, const T& c, Compare compare) { return median_impl<const T&, Compare>(a, b, c, compare); } /// median /// /// median finds which element of three (a, b, d) is in-between the other two. /// If two or more elements are equal, the first (e.g. a before b) is chosen. /// /// Complexity: Either two or three comparisons will be required, depending /// on the values. /// template <typename T, typename Compare> inline T&& median(T&& a, T&& b, T&& c, Compare compare) { return eastl::forward<T>(median_impl<T&&, Compare>(eastl::forward<T>(a), eastl::forward<T>(b), eastl::forward<T>(c), compare)); } /// all_of /// /// Returns: true if the unary predicate p returns true for all elements in the range [first, last) /// template <typename InputIterator, typename Predicate> inline bool all_of(InputIterator first, InputIterator last, Predicate p) { for(; first != last; ++first) { if(!p(*first)) return false; } return true; } /// any_of /// /// Returns: true if the unary predicate p returns true for any of the elements in the range [first, last) /// template <typename InputIterator, typename Predicate> inline bool any_of(InputIterator first, InputIterator last, Predicate p) { for(; first != last; ++first) { if(p(*first)) return true; } return false; } /// none_of /// /// Returns: true if the unary predicate p returns true for none of the elements in the range [first, last) /// template <typename InputIterator, typename Predicate> inline bool none_of(InputIterator first, InputIterator last, Predicate p) { for(; first != last; ++first) { if(p(*first)) return false; } return true; } /// adjacent_find /// /// Returns: The first iterator i such that both i and i + 1 are in the range /// [first, last) for which the following corresponding conditions hold: *i == *(i + 1). /// Returns last if no such iterator is found. /// /// Complexity: Exactly 'find(first, last, value) - first' applications of the corresponding predicate. /// template <typename ForwardIterator> inline ForwardIterator adjacent_find(ForwardIterator first, ForwardIterator last) { if(first != last) { ForwardIterator i = first; for(++i; i != last; ++i) { if(*first == *i) return first; first = i; } } return last; } /// adjacent_find /// /// Returns: The first iterator i such that both i and i + 1 are in the range /// [first, last) for which the following corresponding conditions hold: predicate(*i, *(i + 1)) != false. /// Returns last if no such iterator is found. /// /// Complexity: Exactly 'find(first, last, value) - first' applications of the corresponding predicate. /// template <typename ForwardIterator, typename BinaryPredicate> inline ForwardIterator adjacent_find(ForwardIterator first, ForwardIterator last, BinaryPredicate predicate) { if(first != last) { ForwardIterator i = first; for(++i; i != last; ++i) { if(predicate(*first, *i)) return first; first = i; } } return last; } /// shuffle /// /// New for C++11 /// Randomizes a sequence of values via a user-supplied UniformRandomNumberGenerator. /// The difference between this and the original random_shuffle function is that this uses the more /// advanced and flexible UniformRandomNumberGenerator interface as opposed to the more /// limited RandomNumberGenerator interface of random_shuffle. /// /// Effects: Shuffles the elements in the range [first, last) with uniform distribution. /// /// Complexity: Exactly '(last - first) - 1' swaps. /// /// Example usage: /// struct Rand{ eastl_size_t operator()(eastl_size_t n) { return (eastl_size_t)(rand() % n); } }; // Note: The C rand function is poor and slow. /// Rand randInstance; /// shuffle(pArrayBegin, pArrayEnd, randInstance); /// // See the C++11 Standard, 26.5.1.3, Uniform random number generator requirements. // Also http://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution template <typename RandomAccessIterator, typename UniformRandomNumberGenerator> void shuffle(RandomAccessIterator first, RandomAccessIterator last, UniformRandomNumberGenerator&& urng) { if(first != last) { typedef typename eastl::iterator_traits<RandomAccessIterator>::difference_type difference_type; typedef typename eastl::make_unsigned<difference_type>::type unsigned_difference_type; typedef typename eastl::uniform_int_distribution<unsigned_difference_type> uniform_int_distribution; typedef typename uniform_int_distribution::param_type uniform_int_distribution_param_type; uniform_int_distribution uid; for(RandomAccessIterator i = first + 1; i != last; ++i) iter_swap(i, first + uid(urng, uniform_int_distribution_param_type(0, i - first))); } } /// random_shuffle /// /// Randomizes a sequence of values. /// /// Effects: Shuffles the elements in the range [first, last) with uniform distribution. /// /// Complexity: Exactly '(last - first) - 1' swaps. /// /// Example usage: /// eastl_size_t Rand(eastl_size_t n) { return (eastl_size_t)(rand() % n); } // Note: The C rand function is poor and slow. /// pointer_to_unary_function<eastl_size_t, eastl_size_t> randInstance(Rand); /// random_shuffle(pArrayBegin, pArrayEnd, randInstance); /// /// Example usage: /// struct Rand{ eastl_size_t operator()(eastl_size_t n) { return (eastl_size_t)(rand() % n); } }; // Note: The C rand function is poor and slow. /// Rand randInstance; /// random_shuffle(pArrayBegin, pArrayEnd, randInstance); /// template <typename RandomAccessIterator, typename RandomNumberGenerator> inline void random_shuffle(RandomAccessIterator first, RandomAccessIterator last, RandomNumberGenerator&& rng) { typedef typename eastl::iterator_traits<RandomAccessIterator>::difference_type difference_type; // We must do 'rand((i - first) + 1)' here and cannot do 'rand(last - first)', // as it turns out that the latter results in unequal distribution probabilities. // http://www.cigital.com/papers/download/developer_gambling.php for(RandomAccessIterator i = first + 1; i < last; ++i) iter_swap(i, first + (difference_type)rng((eastl_size_t)((i - first) + 1))); } /// random_shuffle /// /// Randomizes a sequence of values. /// /// Effects: Shuffles the elements in the range [first, last) with uniform distribution. /// /// Complexity: Exactly '(last - first) - 1' swaps. /// /// Example usage: /// random_shuffle(pArrayBegin, pArrayEnd); /// /// *** Disabled until we decide if we want to get into the business of writing random number generators. *** /// /// template <typename RandomAccessIterator> /// inline void random_shuffle(RandomAccessIterator first, RandomAccessIterator last) /// { /// for(RandomAccessIterator i = first + 1; i < last; ++i) /// iter_swap(i, first + SomeRangedRandomNumberGenerator((i - first) + 1)); /// } /// move_n /// /// Same as move(InputIterator, InputIterator, OutputIterator) except based on count instead of iterator range. /// template <typename InputIterator, typename Size, typename OutputIterator> inline OutputIterator move_n_impl(InputIterator first, Size n, OutputIterator result, EASTL_ITC_NS::input_iterator_tag) { for(; n > 0; --n) *result++ = eastl::move(*first++); return result; } template <typename RandomAccessIterator, typename Size, typename OutputIterator> inline OutputIterator move_n_impl(RandomAccessIterator first, Size n, OutputIterator result, EASTL_ITC_NS::random_access_iterator_tag) { return eastl::move(first, first + n, result); // Take advantage of the optimizations present in the move algorithm. } template <typename InputIterator, typename Size, typename OutputIterator> inline OutputIterator move_n(InputIterator first, Size n, OutputIterator result) { typedef typename eastl::iterator_traits<InputIterator>::iterator_category IC; return eastl::move_n_impl(first, n, result, IC()); } /// copy_n /// /// Same as copy(InputIterator, InputIterator, OutputIterator) except based on count instead of iterator range. /// Effects: Copies exactly count values from the range beginning at first to the range beginning at result, if count > 0. Does nothing otherwise. /// Returns: Iterator in the destination range, pointing past the last element copied if count>0 or first otherwise. /// Complexity: Exactly count assignments, if count > 0. /// template <typename InputIterator, typename Size, typename OutputIterator> inline OutputIterator copy_n_impl(InputIterator first, Size n, OutputIterator result, EASTL_ITC_NS::input_iterator_tag) { for(; n > 0; --n) *result++ = *first++; return result; } template <typename RandomAccessIterator, typename Size, typename OutputIterator> inline OutputIterator copy_n_impl(RandomAccessIterator first, Size n, OutputIterator result, EASTL_ITC_NS::random_access_iterator_tag) { return eastl::copy(first, first + n, result); // Take advantage of the optimizations present in the copy algorithm. } template <typename InputIterator, typename Size, typename OutputIterator> inline OutputIterator copy_n(InputIterator first, Size n, OutputIterator result) { typedef typename eastl::iterator_traits<InputIterator>::iterator_category IC; return eastl::copy_n_impl(first, n, result, IC()); } /// copy_if /// /// Effects: Assigns to the result iterator only if the predicate is true. /// template <typename InputIterator, typename OutputIterator, typename Predicate> inline OutputIterator copy_if(InputIterator first, InputIterator last, OutputIterator result, Predicate predicate) { // This implementation's performance could be improved by taking a more complicated approach like with the copy algorithm. for(; first != last; ++first) { if(predicate(*first)) *result++ = *first; } return result; } // Implementation moving copying both trivial and non-trivial data via a lesser iterator than random-access. template <typename /*BidirectionalIterator1Category*/, bool /*isMove*/, bool /*canMemmove*/> struct move_and_copy_backward_helper { template <typename BidirectionalIterator1, typename BidirectionalIterator2> static BidirectionalIterator2 move_or_copy_backward(BidirectionalIterator1 first, BidirectionalIterator1 last, BidirectionalIterator2 resultEnd) { while(first != last) *--resultEnd = *--last; return resultEnd; // resultEnd now points to the beginning of the destination sequence instead of the end. } }; // Specialization for moving non-trivial data via a lesser iterator than random-access. template <typename BidirectionalIterator1Category> struct move_and_copy_backward_helper<BidirectionalIterator1Category, true, false> { template <typename BidirectionalIterator1, typename BidirectionalIterator2> static BidirectionalIterator2 move_or_copy_backward(BidirectionalIterator1 first, BidirectionalIterator1 last, BidirectionalIterator2 resultEnd) { while(first != last) *--resultEnd = eastl::move(*--last); return resultEnd; // resultEnd now points to the beginning of the destination sequence instead of the end. } }; // Specialization for moving non-trivial data via a random-access iterator. It's theoretically faster because the compiler can see the count when its a compile-time const. template<> struct move_and_copy_backward_helper<EASTL_ITC_NS::random_access_iterator_tag, true, false> { template<typename BidirectionalIterator1, typename BidirectionalIterator2> static BidirectionalIterator2 move_or_copy_backward(BidirectionalIterator1 first, BidirectionalIterator1 last, BidirectionalIterator2 resultEnd) { typedef typename eastl::iterator_traits<BidirectionalIterator1>::difference_type difference_type; for(difference_type n = (last - first); n > 0; --n) *--resultEnd = eastl::move(*--last); return resultEnd; // resultEnd now points to the beginning of the destination sequence instead of the end. } }; // Specialization for copying non-trivial data via a random-access iterator. It's theoretically faster because the compiler can see the count when its a compile-time const. // This specialization converts the random access BidirectionalIterator1 last-first to an integral type. There's simple way for us to take advantage of a random access output iterator, // as the range is specified by the input instead of the output, and distance(first, last) for a non-random-access iterator is potentially slow. template <> struct move_and_copy_backward_helper<EASTL_ITC_NS::random_access_iterator_tag, false, false> { template <typename BidirectionalIterator1, typename BidirectionalIterator2> static BidirectionalIterator2 move_or_copy_backward(BidirectionalIterator1 first, BidirectionalIterator1 last, BidirectionalIterator2 resultEnd) { typedef typename eastl::iterator_traits<BidirectionalIterator1>::difference_type difference_type; for(difference_type n = (last - first); n > 0; --n) *--resultEnd = *--last; return resultEnd; // resultEnd now points to the beginning of the destination sequence instead of the end. } }; // Specialization for when we can use memmove/memcpy. See the notes above for what conditions allow this. template <bool isMove> struct move_and_copy_backward_helper<EASTL_ITC_NS::random_access_iterator_tag, isMove, true> { template <typename T> static T* move_or_copy_backward(const T* first, const T* last, T* resultEnd) { return (T*)memmove(resultEnd - (last - first), first, (size_t)((uintptr_t)last - (uintptr_t)first)); // We could use memcpy here if there's no range overlap, but memcpy is rarely much faster than memmove. } }; template <bool isMove, typename BidirectionalIterator1, typename BidirectionalIterator2> inline BidirectionalIterator2 move_and_copy_backward_chooser(BidirectionalIterator1 first, BidirectionalIterator1 last, BidirectionalIterator2 resultEnd) { typedef typename eastl::iterator_traits<BidirectionalIterator1>::iterator_category IIC; typedef typename eastl::iterator_traits<BidirectionalIterator2>::iterator_category OIC; typedef typename eastl::iterator_traits<BidirectionalIterator1>::value_type value_type_input; typedef typename eastl::iterator_traits<BidirectionalIterator2>::value_type value_type_output; const bool canBeMemmoved = eastl::is_trivially_copyable<value_type_output>::value && eastl::is_same<value_type_input, value_type_output>::value && (eastl::is_pointer<BidirectionalIterator1>::value || eastl::is_same<IIC, eastl::contiguous_iterator_tag>::value) && (eastl::is_pointer<BidirectionalIterator2>::value || eastl::is_same<OIC, eastl::contiguous_iterator_tag>::value); return eastl::move_and_copy_backward_helper<IIC, isMove, canBeMemmoved>::move_or_copy_backward(first, last, resultEnd); // Need to chose based on the input iterator tag and not the output iterator tag, because containers accept input ranges of iterator types different than self. } // We have a second layer of unwrap_iterator calls because the original iterator might be something like move_iterator<generic_iterator<int*> > (i.e. doubly-wrapped). template <bool isMove, typename BidirectionalIterator1, typename BidirectionalIterator2> inline BidirectionalIterator2 move_and_copy_backward_unwrapper(BidirectionalIterator1 first, BidirectionalIterator1 last, BidirectionalIterator2 resultEnd) { return BidirectionalIterator2(eastl::move_and_copy_backward_chooser<isMove>(eastl::unwrap_iterator(first), eastl::unwrap_iterator(last), eastl::unwrap_iterator(resultEnd))); // Have to convert to BidirectionalIterator2 because result.base() could be a T* } /// move_backward /// /// The elements are moved in reverse order (the last element is moved first), but their relative order is preserved. /// After this operation the elements in the moved-from range will still contain valid values of the /// appropriate type, but not necessarily the same values as before the move. /// Returns the beginning of the result range. /// Note: When moving between containers, the dest range must be valid; this function doesn't resize containers. /// Note: If result is within [first, last), move must be used instead of move_backward. /// /// Example usage: /// eastl::move_backward(myArray.begin(), myArray.end(), myDestArray.end()); /// /// Reference implementation: /// template <typename BidirectionalIterator1, typename BidirectionalIterator2> /// BidirectionalIterator2 move_backward(BidirectionalIterator1 first, BidirectionalIterator1 last, BidirectionalIterator2 resultEnd) /// { /// while(last != first) /// *--resultEnd = eastl::move(*--last); /// return resultEnd; /// } /// template <typename BidirectionalIterator1, typename BidirectionalIterator2> inline BidirectionalIterator2 move_backward(BidirectionalIterator1 first, BidirectionalIterator1 last, BidirectionalIterator2 resultEnd) { return eastl::move_and_copy_backward_unwrapper<true>(eastl::unwrap_iterator(first), eastl::unwrap_iterator(last), resultEnd); } /// copy_backward /// /// copies memory in the range of [first, last) to the range *ending* with result. /// /// Effects: Copies elements in the range [first, last) into the range /// [result - (last - first), result) starting from last 1 and proceeding to first. /// For each positive integer n <= (last - first), performs *(result n) = *(last - n). /// /// Requires: result shall not be in the range [first, last). /// /// Returns: result - (last - first). That is, returns the beginning of the result range. /// /// Complexity: Exactly 'last - first' assignments. /// template <typename BidirectionalIterator1, typename BidirectionalIterator2> inline BidirectionalIterator2 copy_backward(BidirectionalIterator1 first, BidirectionalIterator1 last, BidirectionalIterator2 resultEnd) { const bool isMove = eastl::is_move_iterator<BidirectionalIterator1>::value; EA_UNUSED(isMove); return eastl::move_and_copy_backward_unwrapper<isMove>(eastl::unwrap_iterator(first), eastl::unwrap_iterator(last), resultEnd); } /// count /// /// Counts the number of items in the range of [first, last) which equal the input value. /// /// Effects: Returns the number of iterators i in the range [first, last) for which the /// following corresponding conditions hold: *i == value. /// /// Complexity: At most 'last - first' applications of the corresponding predicate. /// /// Note: The predicate version of count is count_if and not another variation of count. /// This is because both versions would have three parameters and there could be ambiguity. /// template <typename InputIterator, typename T> inline typename eastl::iterator_traits<InputIterator>::difference_type count(InputIterator first, InputIterator last, const T& value) { typename eastl::iterator_traits<InputIterator>::difference_type result = 0; for(; first != last; ++first) { if(*first == value) ++result; } return result; } // C++ doesn't define a count with predicate, as it can effectively be synthesized via count_if // with an appropriate predicate. However, it's often simpler to just have count with a predicate. template <typename InputIterator, typename T, typename Predicate> inline typename eastl::iterator_traits<InputIterator>::difference_type count(InputIterator first, InputIterator last, const T& value, Predicate predicate) { typename eastl::iterator_traits<InputIterator>::difference_type result = 0; for(; first != last; ++first) { if(predicate(*first, value)) ++result; } return result; } /// count_if /// /// Counts the number of items in the range of [first, last) which match /// the input value as defined by the input predicate function. /// /// Effects: Returns the number of iterators i in the range [first, last) for which the /// following corresponding conditions hold: predicate(*i) != false. /// /// Complexity: At most 'last - first' applications of the corresponding predicate. /// /// Note: The non-predicate version of count_if is count and not another variation of count_if. /// This is because both versions would have three parameters and there could be ambiguity. /// template <typename InputIterator, typename Predicate> inline typename eastl::iterator_traits<InputIterator>::difference_type count_if(InputIterator first, InputIterator last, Predicate predicate) { typename eastl::iterator_traits<InputIterator>::difference_type result = 0; for(; first != last; ++first) { if(predicate(*first)) ++result; } return result; } /// find /// /// finds the value within the unsorted range of [first, last). /// /// Returns: The first iterator i in the range [first, last) for which /// the following corresponding conditions hold: *i == value. /// Returns last if no such iterator is found. /// /// Complexity: At most 'last - first' applications of the corresponding predicate. /// This is a linear search and not a binary one. /// /// Note: The predicate version of find is find_if and not another variation of find. /// This is because both versions would have three parameters and there could be ambiguity. /// template <typename InputIterator, typename T> inline InputIterator find(InputIterator first, InputIterator last, const T& value) { while((first != last) && !(*first == value)) // Note that we always express value comparisons in terms of < or ==. ++first; return first; } // C++ doesn't define a find with predicate, as it can effectively be synthesized via find_if // with an appropriate predicate. However, it's often simpler to just have find with a predicate. template <typename InputIterator, typename T, typename Predicate> inline InputIterator find(InputIterator first, InputIterator last, const T& value, Predicate predicate) { while((first != last) && !predicate(*first, value)) ++first; return first; } /// find_if /// /// finds the value within the unsorted range of [first, last). /// /// Returns: The first iterator i in the range [first, last) for which /// the following corresponding conditions hold: pred(*i) != false. /// Returns last if no such iterator is found. /// If the sequence of elements to search for (i.e. first2 - last2) is empty, /// the find always fails and last1 will be returned. /// /// Complexity: At most 'last - first' applications of the corresponding predicate. /// /// Note: The non-predicate version of find_if is find and not another variation of find_if. /// This is because both versions would have three parameters and there could be ambiguity. /// template <typename InputIterator, typename Predicate> inline InputIterator find_if(InputIterator first, InputIterator last, Predicate predicate) { while((first != last) && !predicate(*first)) ++first; return first; } /// find_if_not /// /// find_if_not works the same as find_if except it tests for if the predicate /// returns false for the elements instead of true. /// template <typename InputIterator, typename Predicate> inline InputIterator find_if_not(InputIterator first, InputIterator last, Predicate predicate) { for(; first != last; ++first) { if(!predicate(*first)) return first; } return last; } /// find_first_of /// /// find_first_of is similar to find in that it performs linear search through /// a range of ForwardIterators. The difference is that while find searches /// for one particular value, find_first_of searches for any of several values. /// Specifically, find_first_of searches for the first occurrance in the /// range [first1, last1) of any of the elements in [first2, last2). /// This function is thus similar to the strpbrk standard C string function. /// If the sequence of elements to search for (i.e. first2-last2) is empty, /// the find always fails and last1 will be returned. /// /// Effects: Finds an element that matches one of a set of values. /// /// Returns: The first iterator i in the range [first1, last1) such that for some /// integer j in the range [first2, last2) the following conditions hold: *i == *j. /// Returns last1 if no such iterator is found. /// /// Complexity: At most '(last1 - first1) * (last2 - first2)' applications of the /// corresponding predicate. /// template <typename ForwardIterator1, typename ForwardIterator2> ForwardIterator1 find_first_of(ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2) { for(; first1 != last1; ++first1) { for(ForwardIterator2 i = first2; i != last2; ++i) { if(*first1 == *i) return first1; } } return last1; } /// find_first_of /// /// find_first_of is similar to find in that it performs linear search through /// a range of ForwardIterators. The difference is that while find searches /// for one particular value, find_first_of searches for any of several values. /// Specifically, find_first_of searches for the first occurrance in the /// range [first1, last1) of any of the elements in [first2, last2). /// This function is thus similar to the strpbrk standard C string function. /// /// Effects: Finds an element that matches one of a set of values. /// /// Returns: The first iterator i in the range [first1, last1) such that for some /// integer j in the range [first2, last2) the following conditions hold: pred(*i, *j) != false. /// Returns last1 if no such iterator is found. /// /// Complexity: At most '(last1 - first1) * (last2 - first2)' applications of the /// corresponding predicate. /// template <typename ForwardIterator1, typename ForwardIterator2, typename BinaryPredicate> ForwardIterator1 find_first_of(ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2, BinaryPredicate predicate) { for(; first1 != last1; ++first1) { for(ForwardIterator2 i = first2; i != last2; ++i) { if(predicate(*first1, *i)) return first1; } } return last1; } /// find_first_not_of /// /// Searches through first range for the first element that does not belong the second input range. /// This is very much like the C++ string find_first_not_of function. /// /// Returns: The first iterator i in the range [first1, last1) such that for some /// integer j in the range [first2, last2) the following conditions hold: !(*i == *j). /// Returns last1 if no such iterator is found. /// /// Complexity: At most '(last1 - first1) * (last2 - first2)' applications of the /// corresponding predicate. /// template <class ForwardIterator1, class ForwardIterator2> ForwardIterator1 find_first_not_of(ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2) { for(; first1 != last1; ++first1) { if(eastl::find(first2, last2, *first1) == last2) break; } return first1; } /// find_first_not_of /// /// Searches through first range for the first element that does not belong the second input range. /// This is very much like the C++ string find_first_not_of function. /// /// Returns: The first iterator i in the range [first1, last1) such that for some /// integer j in the range [first2, last2) the following conditions hold: pred(*i, *j) == false. /// Returns last1 if no such iterator is found. /// /// Complexity: At most '(last1 - first1) * (last2 - first2)' applications of the /// corresponding predicate. /// template <class ForwardIterator1, class ForwardIterator2, class BinaryPredicate> inline ForwardIterator1 find_first_not_of(ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2, BinaryPredicate predicate) { typedef typename eastl::iterator_traits<ForwardIterator1>::value_type value_type; for(; first1 != last1; ++first1) { if(eastl::find_if(first2, last2, eastl::bind1st<BinaryPredicate, value_type>(predicate, *first1)) == last2) break; } return first1; } template <class BidirectionalIterator1, class ForwardIterator2> inline BidirectionalIterator1 find_last_of(BidirectionalIterator1 first1, BidirectionalIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2) { if((first1 != last1) && (first2 != last2)) { BidirectionalIterator1 it1(last1); while((--it1 != first1) && (eastl::find(first2, last2, *it1) == last2)) ; // Do nothing if((it1 != first1) || (eastl::find(first2, last2, *it1) != last2)) return it1; } return last1; } template <class BidirectionalIterator1, class ForwardIterator2, class BinaryPredicate> BidirectionalIterator1 find_last_of(BidirectionalIterator1 first1, BidirectionalIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2, BinaryPredicate predicate) { typedef typename eastl::iterator_traits<BidirectionalIterator1>::value_type value_type; if((first1 != last1) && (first2 != last2)) { BidirectionalIterator1 it1(last1); while((--it1 != first1) && (eastl::find_if(first2, last2, eastl::bind1st<BinaryPredicate, value_type>(predicate, *it1)) == last2)) ; // Do nothing if((it1 != first1) || (eastl::find_if(first2, last2, eastl::bind1st<BinaryPredicate, value_type>(predicate, *it1)) != last2)) return it1; } return last1; } template <class BidirectionalIterator1, class ForwardIterator2> inline BidirectionalIterator1 find_last_not_of(BidirectionalIterator1 first1, BidirectionalIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2) { if((first1 != last1) && (first2 != last2)) { BidirectionalIterator1 it1(last1); while((--it1 != first1) && (eastl::find(first2, last2, *it1) != last2)) ; // Do nothing if((it1 != first1) || (eastl::find( first2, last2, *it1) == last2)) return it1; } return last1; } template <class BidirectionalIterator1, class ForwardIterator2, class BinaryPredicate> inline BidirectionalIterator1 find_last_not_of(BidirectionalIterator1 first1, BidirectionalIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2, BinaryPredicate predicate) { typedef typename eastl::iterator_traits<BidirectionalIterator1>::value_type value_type; if((first1 != last1) && (first2 != last2)) { BidirectionalIterator1 it1(last1); while((--it1 != first1) && (eastl::find_if(first2, last2, eastl::bind1st<BinaryPredicate, value_type>(predicate, *it1)) != last2)) ; // Do nothing if((it1 != first1) || (eastl::find_if(first2, last2, eastl::bind1st<BinaryPredicate, value_type>(predicate, *it1))) != last2) return it1; } return last1; } /// for_each /// /// Calls the Function function for each value in the range [first, last). /// Function takes a single parameter: the current value. /// /// Effects: Applies function to the result of dereferencing every iterator in /// the range [first, last), starting from first and proceeding to last 1. /// /// Returns: function. /// /// Complexity: Applies function exactly 'last - first' times. /// /// Note: If function returns a result, the result is ignored. /// template <typename InputIterator, typename Function> inline Function for_each(InputIterator first, InputIterator last, Function function) { for(; first != last; ++first) function(*first); return function; } /// for_each_n /// /// Calls the Function function for each value in the range [first, first + n). /// Function takes a single parameter: the current value. /// /// Effects: Applies function to the result of dereferencing every iterator in /// the range [first, first + n), starting from first and proceeding to last 1. /// /// Returns: first + n. /// /// Complexity: Applies function exactly 'first + n' times. /// /// Note: //// * If function returns a result, the result is ignored. //// * If n < 0, behaviour is undefined. /// template <typename InputIterator, typename Size, typename Function> EA_CPP14_CONSTEXPR inline InputIterator for_each_n(InputIterator first, Size n, Function function) { for (Size i = 0; i < n; ++first, i++) function(*first); return first; } /// generate /// /// Iterates the range of [first, last) and assigns to each element the /// result of the function generator. Generator is a function which takes /// no arguments. /// /// Complexity: Exactly 'last - first' invocations of generator and assignments. /// template <typename ForwardIterator, typename Generator> inline void generate(ForwardIterator first, ForwardIterator last, Generator generator) { for(; first != last; ++first) // We cannot call generate_n(first, last-first, generator) *first = generator(); // because the 'last-first' might not be supported by the } // given iterator. /// generate_n /// /// Iterates an interator n times and assigns the result of generator /// to each succeeding element. Generator is a function which takes /// no arguments. /// /// Complexity: Exactly n invocations of generator and assignments. /// template <typename OutputIterator, typename Size, typename Generator> inline OutputIterator generate_n(OutputIterator first, Size n, Generator generator) { for(; n > 0; --n, ++first) *first = generator(); return first; } /// transform /// /// Iterates the input range of [first, last) and the output iterator result /// and assigns the result of unaryOperation(input) to result. /// /// Effects: Assigns through every iterator i in the range [result, result + (last1 - first1)) /// a new corresponding value equal to unaryOperation(*(first1 + (i - result)). /// /// Requires: op shall not have any side effects. /// /// Returns: result + (last1 - first1). That is, returns the end of the output range. /// /// Complexity: Exactly 'last1 - first1' applications of unaryOperation. /// /// Note: result may be equal to first. /// template <typename InputIterator, typename OutputIterator, typename UnaryOperation> inline OutputIterator transform(InputIterator first, InputIterator last, OutputIterator result, UnaryOperation unaryOperation) { for(; first != last; ++first, ++result) *result = unaryOperation(*first); return result; } /// transform /// /// Iterates the input range of [first, last) and the output iterator result /// and assigns the result of binaryOperation(input1, input2) to result. /// /// Effects: Assigns through every iterator i in the range [result, result + (last1 - first1)) /// a new corresponding value equal to binaryOperation(*(first1 + (i - result), *(first2 + (i - result))). /// /// Requires: binaryOperation shall not have any side effects. /// /// Returns: result + (last1 - first1). That is, returns the end of the output range. /// /// Complexity: Exactly 'last1 - first1' applications of binaryOperation. /// /// Note: result may be equal to first1 or first2. /// template <typename InputIterator1, typename InputIterator2, typename OutputIterator, typename BinaryOperation> inline OutputIterator transform(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, OutputIterator result, BinaryOperation binaryOperation) { for(; first1 != last1; ++first1, ++first2, ++result) *result = binaryOperation(*first1, *first2); return result; } /// equal /// /// Returns: true if for every iterator i in the range [first1, last1) the /// following corresponding conditions hold: predicate(*i, *(first2 + (i - first1))) != false. /// Otherwise, returns false. /// /// Complexity: At most last1 first1 applications of the corresponding predicate. /// /// To consider: Make specializations of this for scalar types and random access /// iterators that uses memcmp or some trick memory comparison function. /// We should verify that such a thing results in an improvement. /// template <typename InputIterator1, typename InputIterator2> EA_CPP14_CONSTEXPR inline bool equal(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2) { for(; first1 != last1; ++first1, ++first2) { if(!(*first1 == *first2)) // Note that we always express value comparisons in terms of < or ==. return false; } return true; } /* Enable the following if there was shown to be some benefit. A glance and Microsoft VC++ memcmp shows that it is not optimized in any way, much less one that would benefit us here. inline bool equal(const bool* first1, const bool* last1, const bool* first2) { return (memcmp(first1, first2, (size_t)((uintptr_t)last1 - (uintptr_t)first1)) == 0); } inline bool equal(const char* first1, const char* last1, const char* first2) { return (memcmp(first1, first2, (size_t)((uintptr_t)last1 - (uintptr_t)first1)) == 0); } inline bool equal(const unsigned char* first1, const unsigned char* last1, const unsigned char* first2) { return (memcmp(first1, first2, (size_t)((uintptr_t)last1 - (uintptr_t)first1)) == 0); } inline bool equal(const signed char* first1, const signed char* last1, const signed char* first2) { return (memcmp(first1, first2, (size_t)((uintptr_t)last1 - (uintptr_t)first1)) == 0); } #ifndef EA_WCHAR_T_NON_NATIVE inline bool equal(const wchar_t* first1, const wchar_t* last1, const wchar_t* first2) { return (memcmp(first1, first2, (size_t)((uintptr_t)last1 - (uintptr_t)first1)) == 0); } #endif inline bool equal(const int16_t* first1, const int16_t* last1, const int16_t* first2) { return (memcmp(first1, first2, (size_t)((uintptr_t)last1 - (uintptr_t)first1)) == 0); } inline bool equal(const uint16_t* first1, const uint16_t* last1, const uint16_t* first2) { return (memcmp(first1, first2, (size_t)((uintptr_t)last1 - (uintptr_t)first1)) == 0); } inline bool equal(const int32_t* first1, const int32_t* last1, const int32_t* first2) { return (memcmp(first1, first2, (size_t)((uintptr_t)last1 - (uintptr_t)first1)) == 0); } inline bool equal(const uint32_t* first1, const uint32_t* last1, const uint32_t* first2) { return (memcmp(first1, first2, (size_t)((uintptr_t)last1 - (uintptr_t)first1)) == 0); } inline bool equal(const int64_t* first1, const int64_t* last1, const int64_t* first2) { return (memcmp(first1, first2, (size_t)((uintptr_t)last1 - (uintptr_t)first1)) == 0); } inline bool equal(const uint64_t* first1, const uint64_t* last1, const uint64_t* first2) { return (memcmp(first1, first2, (size_t)((uintptr_t)last1 - (uintptr_t)first1)) == 0); } */ /// equal /// /// Returns: true if for every iterator i in the range [first1, last1) the /// following corresponding conditions hold: pred(*i, *(first2 + (i first1))) != false. /// Otherwise, returns false. /// /// Complexity: At most last1 first1 applications of the corresponding predicate. /// template <typename InputIterator1, typename InputIterator2, typename BinaryPredicate> inline bool equal(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, BinaryPredicate predicate) { for(; first1 != last1; ++first1, ++first2) { if(!predicate(*first1, *first2)) return false; } return true; } /// identical /// /// Returns true if the two input ranges are equivalent. /// There is a subtle difference between this algorithm and /// the 'equal' algorithm. The equal algorithm assumes the /// two ranges are of equal length. This algorithm efficiently /// compares two ranges for both length equality and for /// element equality. There is no other standard algorithm /// that can do this. /// /// Returns: true if the sequence of elements defined by the range /// [first1, last1) is of the same length as the sequence of /// elements defined by the range of [first2, last2) and if /// the elements in these ranges are equal as per the /// equal algorithm. /// /// Complexity: At most 'min((last1 - first1), (last2 - first2))' applications /// of the corresponding comparison. /// template <typename InputIterator1, typename InputIterator2> bool identical(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2) { while((first1 != last1) && (first2 != last2) && (*first1 == *first2)) { ++first1; ++first2; } return (first1 == last1) && (first2 == last2); } /// identical /// template <typename InputIterator1, typename InputIterator2, typename BinaryPredicate> bool identical(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, BinaryPredicate predicate) { while((first1 != last1) && (first2 != last2) && predicate(*first1, *first2)) { ++first1; ++first2; } return (first1 == last1) && (first2 == last2); } /// lexicographical_compare /// /// Returns: true if the sequence of elements defined by the range /// [first1, last1) is lexicographically less than the sequence of /// elements defined by the range [first2, last2). Returns false otherwise. /// /// Complexity: At most 'min((last1 - first1), (last2 - first2))' applications /// of the corresponding comparison. /// /// Note: If two sequences have the same number of elements and their /// corresponding elements are equivalent, then neither sequence is /// lexicographically less than the other. If one sequence is a prefix /// of the other, then the shorter sequence is lexicographically less /// than the longer sequence. Otherwise, the lexicographical comparison /// of the sequences yields the same result as the comparison of the first /// corresponding pair of elements that are not equivalent. /// template <typename InputIterator1, typename InputIterator2> inline bool lexicographical_compare(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2) { for(; (first1 != last1) && (first2 != last2); ++first1, ++first2) { if(*first1 < *first2) return true; if(*first2 < *first1) return false; } return (first1 == last1) && (first2 != last2); } inline bool // Specialization for const char*. lexicographical_compare(const char* first1, const char* last1, const char* first2, const char* last2) { const ptrdiff_t n1(last1 - first1), n2(last2 - first2); const int result = memcmp(first1, first2, (size_t)eastl::min_alt(n1, n2)); return result ? (result < 0) : (n1 < n2); } inline bool // Specialization for char*. lexicographical_compare(char* first1, char* last1, char* first2, char* last2) { const ptrdiff_t n1(last1 - first1), n2(last2 - first2); const int result = memcmp(first1, first2, (size_t)eastl::min_alt(n1, n2)); return result ? (result < 0) : (n1 < n2); } inline bool // Specialization for const unsigned char*. lexicographical_compare(const unsigned char* first1, const unsigned char* last1, const unsigned char* first2, const unsigned char* last2) { const ptrdiff_t n1(last1 - first1), n2(last2 - first2); const int result = memcmp(first1, first2, (size_t)eastl::min_alt(n1, n2)); return result ? (result < 0) : (n1 < n2); } inline bool // Specialization for unsigned char*. lexicographical_compare(unsigned char* first1, unsigned char* last1, unsigned char* first2, unsigned char* last2) { const ptrdiff_t n1(last1 - first1), n2(last2 - first2); const int result = memcmp(first1, first2, (size_t)eastl::min_alt(n1, n2)); return result ? (result < 0) : (n1 < n2); } inline bool // Specialization for const signed char*. lexicographical_compare(const signed char* first1, const signed char* last1, const signed char* first2, const signed char* last2) { const ptrdiff_t n1(last1 - first1), n2(last2 - first2); const int result = memcmp(first1, first2, (size_t)eastl::min_alt(n1, n2)); return result ? (result < 0) : (n1 < n2); } inline bool // Specialization for signed char*. lexicographical_compare(signed char* first1, signed char* last1, signed char* first2, signed char* last2) { const ptrdiff_t n1(last1 - first1), n2(last2 - first2); const int result = memcmp(first1, first2, (size_t)eastl::min_alt(n1, n2)); return result ? (result < 0) : (n1 < n2); } #if defined(_MSC_VER) // If using the VC++ compiler (and thus bool is known to be a single byte)... //Not sure if this is a good idea. //inline bool // Specialization for const bool*. //lexicographical_compare(const bool* first1, const bool* last1, const bool* first2, const bool* last2) //{ // const ptrdiff_t n1(last1 - first1), n2(last2 - first2); // const int result = memcmp(first1, first2, (size_t)eastl::min_alt(n1, n2)); // return result ? (result < 0) : (n1 < n2); //} // //inline bool // Specialization for bool*. //lexicographical_compare(bool* first1, bool* last1, bool* first2, bool* last2) //{ // const ptrdiff_t n1(last1 - first1), n2(last2 - first2); // const int result = memcmp(first1, first2, (size_t)eastl::min_alt(n1, n2)); // return result ? (result < 0) : (n1 < n2); //} #endif /// lexicographical_compare /// /// Returns: true if the sequence of elements defined by the range /// [first1, last1) is lexicographically less than the sequence of /// elements defined by the range [first2, last2). Returns false otherwise. /// /// Complexity: At most 'min((last1 -first1), (last2 - first2))' applications /// of the corresponding comparison. /// /// Note: If two sequences have the same number of elements and their /// corresponding elements are equivalent, then neither sequence is /// lexicographically less than the other. If one sequence is a prefix /// of the other, then the shorter sequence is lexicographically less /// than the longer sequence. Otherwise, the lexicographical comparison /// of the sequences yields the same result as the comparison of the first /// corresponding pair of elements that are not equivalent. /// /// Note: False is always returned if range 1 is exhausted before range 2. /// The result of this is that you can't do a successful reverse compare /// (e.g. use greater<> as the comparison instead of less<>) unless the /// two sequences are of identical length. What you want to do is reverse /// the order of the arguments in order to get the desired effect. /// template <typename InputIterator1, typename InputIterator2, typename Compare> inline bool lexicographical_compare(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, Compare compare) { for(; (first1 != last1) && (first2 != last2); ++first1, ++first2) { if(compare(*first1, *first2)) return true; if(compare(*first2, *first1)) return false; } return (first1 == last1) && (first2 != last2); } /// mismatch /// /// Finds the first position where the two ranges [first1, last1) and /// [first2, first2 + (last1 - first1)) differ. The two versions of /// mismatch use different tests for whether elements differ. /// /// Returns: A pair of iterators i and j such that j == first2 + (i - first1) /// and i is the first iterator in the range [first1, last1) for which the /// following corresponding condition holds: !(*i == *(first2 + (i - first1))). /// Returns the pair last1 and first2 + (last1 - first1) if such an iterator /// i is not found. /// /// Complexity: At most last1 first1 applications of the corresponding predicate. /// template <class InputIterator1, class InputIterator2> inline eastl::pair<InputIterator1, InputIterator2> mismatch(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2) // , InputIterator2 last2) { while((first1 != last1) && (*first1 == *first2)) // && (first2 != last2) <- C++ standard mismatch function doesn't check first2/last2. { ++first1; ++first2; } return eastl::pair<InputIterator1, InputIterator2>(first1, first2); } /// mismatch /// /// Finds the first position where the two ranges [first1, last1) and /// [first2, first2 + (last1 - first1)) differ. The two versions of /// mismatch use different tests for whether elements differ. /// /// Returns: A pair of iterators i and j such that j == first2 + (i - first1) /// and i is the first iterator in the range [first1, last1) for which the /// following corresponding condition holds: pred(*i, *(first2 + (i - first1))) == false. /// Returns the pair last1 and first2 + (last1 - first1) if such an iterator /// i is not found. /// /// Complexity: At most last1 first1 applications of the corresponding predicate. /// template <class InputIterator1, class InputIterator2, class BinaryPredicate> inline eastl::pair<InputIterator1, InputIterator2> mismatch(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, // InputIterator2 last2, BinaryPredicate predicate) { while((first1 != last1) && predicate(*first1, *first2)) // && (first2 != last2) <- C++ standard mismatch function doesn't check first2/last2. { ++first1; ++first2; } return eastl::pair<InputIterator1, InputIterator2>(first1, first2); } /// lower_bound /// /// Finds the position of the first element in a sorted range that has a value /// greater than or equivalent to a specified value. /// /// Effects: Finds the first position into which value can be inserted without /// violating the ordering. /// /// Returns: The furthermost iterator i in the range [first, last) such that /// for any iterator j in the range [first, i) the following corresponding /// condition holds: *j < value. /// /// Complexity: At most 'log(last - first) + 1' comparisons. /// /// Optimizations: We have no need to specialize this implementation for random /// access iterators (e.g. contiguous array), as the code below will already /// take advantage of them. /// template <typename ForwardIterator, typename T> ForwardIterator lower_bound(ForwardIterator first, ForwardIterator last, const T& value) { typedef typename eastl::iterator_traits<ForwardIterator>::difference_type DifferenceType; DifferenceType d = eastl::distance(first, last); // This will be efficient for a random access iterator such as an array. while(d > 0) { ForwardIterator i = first; DifferenceType d2 = d >> 1; // We use '>>1' here instead of '/2' because MSVC++ for some reason generates significantly worse code for '/2'. Go figure. eastl::advance(i, d2); // This will be efficient for a random access iterator such as an array. if(*i < value) { // Disabled because std::lower_bound doesn't specify (23.3.3.3, p3) this can be done: EASTL_VALIDATE_COMPARE(!(value < *i)); // Validate that the compare function is sane. first = ++i; d -= d2 + 1; } else d = d2; } return first; } /// lower_bound /// /// Finds the position of the first element in a sorted range that has a value /// greater than or equivalent to a specified value. The input Compare function /// takes two arguments and returns true if the first argument is less than /// the second argument. /// /// Effects: Finds the first position into which value can be inserted without /// violating the ordering. /// /// Returns: The furthermost iterator i in the range [first, last) such that /// for any iterator j in the range [first, i) the following corresponding /// condition holds: compare(*j, value) != false. /// /// Complexity: At most 'log(last - first) + 1' comparisons. /// /// Optimizations: We have no need to specialize this implementation for random /// access iterators (e.g. contiguous array), as the code below will already /// take advantage of them. /// template <typename ForwardIterator, typename T, typename Compare> ForwardIterator lower_bound(ForwardIterator first, ForwardIterator last, const T& value, Compare compare) { typedef typename eastl::iterator_traits<ForwardIterator>::difference_type DifferenceType; DifferenceType d = eastl::distance(first, last); // This will be efficient for a random access iterator such as an array. while(d > 0) { ForwardIterator i = first; DifferenceType d2 = d >> 1; // We use '>>1' here instead of '/2' because MSVC++ for some reason generates significantly worse code for '/2'. Go figure. eastl::advance(i, d2); // This will be efficient for a random access iterator such as an array. if(compare(*i, value)) { // Disabled because std::lower_bound doesn't specify (23.3.3.1, p3) this can be done: EASTL_VALIDATE_COMPARE(!compare(value, *i)); // Validate that the compare function is sane. first = ++i; d -= d2 + 1; } else d = d2; } return first; } /// upper_bound /// /// Finds the position of the first element in a sorted range that has a /// value that is greater than a specified value. /// /// Effects: Finds the furthermost position into which value can be inserted /// without violating the ordering. /// /// Returns: The furthermost iterator i in the range [first, last) such that /// for any iterator j in the range [first, i) the following corresponding /// condition holds: !(value < *j). /// /// Complexity: At most 'log(last - first) + 1' comparisons. /// template <typename ForwardIterator, typename T> ForwardIterator upper_bound(ForwardIterator first, ForwardIterator last, const T& value) { typedef typename eastl::iterator_traits<ForwardIterator>::difference_type DifferenceType; DifferenceType len = eastl::distance(first, last); while(len > 0) { ForwardIterator i = first; DifferenceType len2 = len >> 1; // We use '>>1' here instead of '/2' because MSVC++ for some reason generates significantly worse code for '/2'. Go figure. eastl::advance(i, len2); if(!(value < *i)) // Note that we always express value comparisons in terms of < or ==. { first = ++i; len -= len2 + 1; } else { // Disabled because std::upper_bound doesn't specify (23.3.3.2, p3) this can be done: EASTL_VALIDATE_COMPARE(!(*i < value)); // Validate that the compare function is sane. len = len2; } } return first; } /// upper_bound /// /// Finds the position of the first element in a sorted range that has a /// value that is greater than a specified value. The input Compare function /// takes two arguments and returns true if the first argument is less than /// the second argument. /// /// Effects: Finds the furthermost position into which value can be inserted /// without violating the ordering. /// /// Returns: The furthermost iterator i in the range [first, last) such that /// for any iterator j in the range [first, i) the following corresponding /// condition holds: compare(value, *j) == false. /// /// Complexity: At most 'log(last - first) + 1' comparisons. /// template <typename ForwardIterator, typename T, typename Compare> ForwardIterator upper_bound(ForwardIterator first, ForwardIterator last, const T& value, Compare compare) { typedef typename eastl::iterator_traits<ForwardIterator>::difference_type DifferenceType; DifferenceType len = eastl::distance(first, last); while(len > 0) { ForwardIterator i = first; DifferenceType len2 = len >> 1; // We use '>>1' here instead of '/2' because MSVC++ for some reason generates significantly worse code for '/2'. Go figure. eastl::advance(i, len2); if(!compare(value, *i)) { first = ++i; len -= len2 + 1; } else { // Disabled because std::upper_bound doesn't specify (23.3.3.2, p3) this can be done: EASTL_VALIDATE_COMPARE(!compare(*i, value)); // Validate that the compare function is sane. len = len2; } } return first; } /// equal_range /// /// Effects: Finds the largest subrange [i, j) such that the value can be inserted /// at any iterator k in it without violating the ordering. k satisfies the /// corresponding conditions: !(*k < value) && !(value < *k). /// /// Complexity: At most '2 * log(last - first) + 1' comparisons. /// template <typename ForwardIterator, typename T> pair<ForwardIterator, ForwardIterator> equal_range(ForwardIterator first, ForwardIterator last, const T& value) { typedef pair<ForwardIterator, ForwardIterator> ResultType; typedef typename eastl::iterator_traits<ForwardIterator>::difference_type DifferenceType; DifferenceType d = eastl::distance(first, last); while(d > 0) { ForwardIterator i(first); DifferenceType d2 = d >> 1; // We use '>>1' here instead of '/2' because MSVC++ for some reason generates significantly worse code for '/2'. Go figure. eastl::advance(i, d2); if(*i < value) { EASTL_VALIDATE_COMPARE(!(value < *i)); // Validate that the compare function is sane. first = ++i; d -= d2 + 1; } else if(value < *i) { EASTL_VALIDATE_COMPARE(!(*i < value)); // Validate that the compare function is sane. d = d2; last = i; } else { ForwardIterator j(i); return ResultType(eastl::lower_bound(first, i, value), eastl::upper_bound(++j, last, value)); } } return ResultType(first, first); } /// equal_range /// /// Effects: Finds the largest subrange [i, j) such that the value can be inserted /// at any iterator k in it without violating the ordering. k satisfies the /// corresponding conditions: compare(*k, value) == false && compare(value, *k) == false. /// /// Complexity: At most '2 * log(last - first) + 1' comparisons. /// template <typename ForwardIterator, typename T, typename Compare> pair<ForwardIterator, ForwardIterator> equal_range(ForwardIterator first, ForwardIterator last, const T& value, Compare compare) { typedef pair<ForwardIterator, ForwardIterator> ResultType; typedef typename eastl::iterator_traits<ForwardIterator>::difference_type DifferenceType; DifferenceType d = eastl::distance(first, last); while(d > 0) { ForwardIterator i(first); DifferenceType d2 = d >> 1; // We use '>>1' here instead of '/2' because MSVC++ for some reason generates significantly worse code for '/2'. Go figure. eastl::advance(i, d2); if(compare(*i, value)) { EASTL_VALIDATE_COMPARE(!compare(value, *i)); // Validate that the compare function is sane. first = ++i; d -= d2 + 1; } else if(compare(value, *i)) { EASTL_VALIDATE_COMPARE(!compare(*i, value)); // Validate that the compare function is sane. d = d2; last = i; } else { ForwardIterator j(i); return ResultType(eastl::lower_bound(first, i, value, compare), eastl::upper_bound(++j, last, value, compare)); } } return ResultType(first, first); } /// replace /// /// Effects: Substitutes elements referred by the iterator i in the range [first, last) /// with new_value, when the following corresponding conditions hold: *i == old_value. /// /// Complexity: Exactly 'last - first' applications of the corresponding predicate. /// /// Note: The predicate version of replace is replace_if and not another variation of replace. /// This is because both versions would have the same parameter count and there could be ambiguity. /// template <typename ForwardIterator, typename T> inline void replace(ForwardIterator first, ForwardIterator last, const T& old_value, const T& new_value) { for(; first != last; ++first) { if(*first == old_value) *first = new_value; } } /// replace_if /// /// Effects: Substitutes elements referred by the iterator i in the range [first, last) /// with new_value, when the following corresponding conditions hold: predicate(*i) != false. /// /// Complexity: Exactly 'last - first' applications of the corresponding predicate. /// /// Note: The predicate version of replace_if is replace and not another variation of replace_if. /// This is because both versions would have the same parameter count and there could be ambiguity. /// template <typename ForwardIterator, typename Predicate, typename T> inline void replace_if(ForwardIterator first, ForwardIterator last, Predicate predicate, const T& new_value) { for(; first != last; ++first) { if(predicate(*first)) *first = new_value; } } /// remove_copy /// /// Effects: Copies all the elements referred to by the iterator i in the range /// [first, last) for which the following corresponding condition does not hold: /// *i == value. /// /// Requires: The ranges [first, last) and [result, result + (last - first)) shall not overlap. /// /// Returns: The end of the resulting range. /// /// Complexity: Exactly 'last - first' applications of the corresponding predicate. /// template <typename InputIterator, typename OutputIterator, typename T> inline OutputIterator remove_copy(InputIterator first, InputIterator last, OutputIterator result, const T& value) { for(; first != last; ++first) { if(!(*first == value)) // Note that we always express value comparisons in terms of < or ==. { *result = move(*first); ++result; } } return result; } /// remove_copy_if /// /// Effects: Copies all the elements referred to by the iterator i in the range /// [first, last) for which the following corresponding condition does not hold: /// predicate(*i) != false. /// /// Requires: The ranges [first, last) and [result, result + (last - first)) shall not overlap. /// /// Returns: The end of the resulting range. /// /// Complexity: Exactly 'last - first' applications of the corresponding predicate. /// template <typename InputIterator, typename OutputIterator, typename Predicate> inline OutputIterator remove_copy_if(InputIterator first, InputIterator last, OutputIterator result, Predicate predicate) { for(; first != last; ++first) { if(!predicate(*first)) { *result = eastl::move(*first); ++result; } } return result; } /// remove /// /// Effects: Eliminates all the elements referred to by iterator i in the /// range [first, last) for which the following corresponding condition /// holds: *i == value. /// /// Returns: The end of the resulting range. /// /// Complexity: Exactly 'last - first' applications of the corresponding predicate. /// /// Note: The predicate version of remove is remove_if and not another variation of remove. /// This is because both versions would have the same parameter count and there could be ambiguity. /// /// Note: Since this function moves the element to the back of the heap and /// doesn't actually remove it from the given container, the user must call /// the container erase function if the user wants to erase the element /// from the container. /// /// Example usage: /// vector<int> intArray; /// ... /// intArray.erase(remove(intArray.begin(), intArray.end(), 4), intArray.end()); // Erase all elements of value 4. /// template <typename ForwardIterator, typename T> inline ForwardIterator remove(ForwardIterator first, ForwardIterator last, const T& value) { first = eastl::find(first, last, value); if(first != last) { ForwardIterator i(first); return eastl::remove_copy(++i, last, first, value); } return first; } /// remove_if /// /// Effects: Eliminates all the elements referred to by iterator i in the /// range [first, last) for which the following corresponding condition /// holds: predicate(*i) != false. /// /// Returns: The end of the resulting range. /// /// Complexity: Exactly 'last - first' applications of the corresponding predicate. /// /// Note: The predicate version of remove_if is remove and not another variation of remove_if. /// This is because both versions would have the same parameter count and there could be ambiguity. /// /// Note: Since this function moves the element to the back of the heap and /// doesn't actually remove it from the given container, the user must call /// the container erase function if the user wants to erase the element /// from the container. /// /// Example usage: /// vector<int> intArray; /// ... /// intArray.erase(remove(intArray.begin(), intArray.end(), bind2nd(less<int>(), (int)3)), intArray.end()); // Erase all elements less than 3. /// template <typename ForwardIterator, typename Predicate> inline ForwardIterator remove_if(ForwardIterator first, ForwardIterator last, Predicate predicate) { first = eastl::find_if(first, last, predicate); if(first != last) { ForwardIterator i(first); return eastl::remove_copy_if<ForwardIterator, ForwardIterator, Predicate>(++i, last, first, predicate); } return first; } /// replace_copy /// /// Effects: Assigns to every iterator i in the range [result, result + (last - first)) /// either new_value or *(first + (i - result)) depending on whether the following /// corresponding conditions hold: *(first + (i - result)) == old_value. /// /// Requires: The ranges [first, last) and [result, result + (last - first)) shall not overlap. /// /// Returns: result + (last - first). /// /// Complexity: Exactly 'last - first' applications of the corresponding predicate. /// /// Note: The predicate version of replace_copy is replace_copy_if and not another variation of replace_copy. /// This is because both versions would have the same parameter count and there could be ambiguity. /// template <typename InputIterator, typename OutputIterator, typename T> inline OutputIterator replace_copy(InputIterator first, InputIterator last, OutputIterator result, const T& old_value, const T& new_value) { for(; first != last; ++first, ++result) *result = (*first == old_value) ? new_value : *first; return result; } /// replace_copy_if /// /// Effects: Assigns to every iterator i in the range [result, result + (last - first)) /// either new_value or *(first + (i - result)) depending on whether the following /// corresponding conditions hold: predicate(*(first + (i - result))) != false. /// /// Requires: The ranges [first, last) and [result, result+(lastfirst)) shall not overlap. /// /// Returns: result + (last - first). /// /// Complexity: Exactly 'last - first' applications of the corresponding predicate. /// /// Note: The predicate version of replace_copy_if is replace_copy and not another variation of replace_copy_if. /// This is because both versions would have the same parameter count and there could be ambiguity. /// template <typename InputIterator, typename OutputIterator, typename Predicate, typename T> inline OutputIterator replace_copy_if(InputIterator first, InputIterator last, OutputIterator result, Predicate predicate, const T& new_value) { for(; first != last; ++first, ++result) *result = predicate(*first) ? new_value : *first; return result; } // reverse // // We provide helper functions which allow reverse to be implemented more // efficiently for some types of iterators and types. // template <typename BidirectionalIterator> inline void reverse_impl(BidirectionalIterator first, BidirectionalIterator last, EASTL_ITC_NS::bidirectional_iterator_tag) { for(; (first != last) && (first != --last); ++first) // We are not allowed to use operator <, <=, >, >= with a eastl::iter_swap(first, last); // generic (bidirectional or otherwise) iterator. } template <typename RandomAccessIterator> inline void reverse_impl(RandomAccessIterator first, RandomAccessIterator last, EASTL_ITC_NS::random_access_iterator_tag) { if(first != last) { for(; first < --last; ++first) // With a random access iterator, we can use operator < to more efficiently implement eastl::iter_swap(first, last); // this algorithm. A generic iterator doesn't necessarily have an operator < defined. } } /// reverse /// /// Reverses the values within the range [first, last). /// /// Effects: For each nonnegative integer i <= (last - first) / 2, /// applies swap to all pairs of iterators first + i, (last i) - 1. /// /// Complexity: Exactly '(last - first) / 2' swaps. /// template <typename BidirectionalIterator> inline void reverse(BidirectionalIterator first, BidirectionalIterator last) { typedef typename eastl::iterator_traits<BidirectionalIterator>::iterator_category IC; eastl::reverse_impl(first, last, IC()); } /// reverse_copy /// /// Copies the range [first, last) in reverse order to the result. /// /// Effects: Copies the range [first, last) to the range /// [result, result + (last - first)) such that for any nonnegative /// integer i < (last - first) the following assignment takes place: /// *(result + (last - first) - i) = *(first + i) /// /// Requires: The ranges [first, last) and [result, result + (last - first)) /// shall not overlap. /// /// Returns: result + (last - first). That is, returns the end of the output range. /// /// Complexity: Exactly 'last - first' assignments. /// template <typename BidirectionalIterator, typename OutputIterator> inline OutputIterator reverse_copy(BidirectionalIterator first, BidirectionalIterator last, OutputIterator result) { for(; first != last; ++result) *result = *--last; return result; } /// search /// /// Search finds a subsequence within the range [first1, last1) that is identical to [first2, last2) /// when compared element-by-element. It returns an iterator pointing to the beginning of that /// subsequence, or else last1 if no such subsequence exists. As such, it is very much like /// the C strstr function, with the primary difference being that strstr uses 0-terminated strings /// whereas search uses an end iterator to specify the end of a string. /// /// Returns: The first iterator i in the range [first1, last1 - (last2 - first2)) such that for /// any nonnegative integer n less than 'last2 - first2' the following corresponding condition holds: /// *(i + n) == *(first2 + n). Returns last1 if no such iterator is found. /// /// Complexity: At most (last1 first1) * (last2 first2) applications of the corresponding predicate. /// template <typename ForwardIterator1, typename ForwardIterator2> ForwardIterator1 search(ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2) { if(first2 != last2) // If there is anything to search for... { // We need to make a special case for a pattern of one element, // as the logic below prevents one element patterns from working. ForwardIterator2 temp2(first2); ++temp2; if(temp2 != last2) // If what we are searching for has a length > 1... { ForwardIterator1 cur1(first1); ForwardIterator2 p2; while(first1 != last1) { // The following loop is the equivalent of eastl::find(first1, last1, *first2) while((first1 != last1) && !(*first1 == *first2)) ++first1; if(first1 != last1) { p2 = temp2; cur1 = first1; if(++cur1 != last1) { while(*cur1 == *p2) { if(++p2 == last2) return first1; if(++cur1 == last1) return last1; } ++first1; continue; } } return last1; } // Fall through to the end. } else return eastl::find(first1, last1, *first2); } return first1; #if 0 /* Another implementation which is a little more simpler but executes a little slower on average. typedef typename eastl::iterator_traits<ForwardIterator1>::difference_type difference_type_1; typedef typename eastl::iterator_traits<ForwardIterator2>::difference_type difference_type_2; const difference_type_2 d2 = eastl::distance(first2, last2); for(difference_type_1 d1 = eastl::distance(first1, last1); d1 >= d2; ++first1, --d1) { ForwardIterator1 temp1 = first1; for(ForwardIterator2 temp2 = first2; ; ++temp1, ++temp2) { if(temp2 == last2) return first1; if(!(*temp1 == *temp2)) break; } } return last1; */ #endif } /// search /// /// Search finds a subsequence within the range [first1, last1) that is identical to [first2, last2) /// when compared element-by-element. It returns an iterator pointing to the beginning of that /// subsequence, or else last1 if no such subsequence exists. As such, it is very much like /// the C strstr function, with the only difference being that strstr uses 0-terminated strings /// whereas search uses an end iterator to specify the end of a string. /// /// Returns: The first iterator i in the range [first1, last1 - (last2 - first2)) such that for /// any nonnegative integer n less than 'last2 - first2' the following corresponding condition holds: /// predicate(*(i + n), *(first2 + n)) != false. Returns last1 if no such iterator is found. /// /// Complexity: At most (last1 first1) * (last2 first2) applications of the corresponding predicate. /// template <typename ForwardIterator1, typename ForwardIterator2, typename BinaryPredicate> ForwardIterator1 search(ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2, BinaryPredicate predicate) { typedef typename eastl::iterator_traits<ForwardIterator1>::difference_type difference_type_1; typedef typename eastl::iterator_traits<ForwardIterator2>::difference_type difference_type_2; difference_type_2 d2 = eastl::distance(first2, last2); if(d2 != 0) { ForwardIterator1 i(first1); eastl::advance(i, d2); for(difference_type_1 d1 = eastl::distance(first1, last1); d1 >= d2; --d1) { if(eastl::equal<ForwardIterator1, ForwardIterator2, BinaryPredicate>(first1, i, first2, predicate)) return first1; if(d1 > d2) // To do: Find a way to make the algorithm more elegant. { ++first1; ++i; } } return last1; } return first1; // Just like with strstr, we return first1 if the match string is empty. } // search_n helper functions // template <typename ForwardIterator, typename Size, typename T> ForwardIterator // Generic implementation. search_n_impl(ForwardIterator first, ForwardIterator last, Size count, const T& value, EASTL_ITC_NS::forward_iterator_tag) { if(count <= 0) return first; Size d1 = (Size)eastl::distance(first, last); // Should d1 be of type Size, ptrdiff_t, or iterator_traits<ForwardIterator>::difference_type? // The problem with using iterator_traits<ForwardIterator>::difference_type is that if(count > d1) // ForwardIterator may not be a true iterator but instead something like a pointer. return last; for(; d1 >= count; ++first, --d1) { ForwardIterator i(first); for(Size n = 0; n < count; ++n, ++i, --d1) { if(!(*i == value)) // Note that we always express value comparisons in terms of < or ==. goto not_found; } return first; not_found: first = i; } return last; } template <typename RandomAccessIterator, typename Size, typename T> inline RandomAccessIterator // Random access iterator implementation. Much faster than generic implementation. search_n_impl(RandomAccessIterator first, RandomAccessIterator last, Size count, const T& value, EASTL_ITC_NS::random_access_iterator_tag) { if(count <= 0) return first; else if(count == 1) return find(first, last, value); else if(last > first) { RandomAccessIterator lookAhead; RandomAccessIterator backTrack; Size skipOffset = (count - 1); Size tailSize = (Size)(last - first); Size remainder; Size prevRemainder; for(lookAhead = first + skipOffset; tailSize >= count; lookAhead += count) { tailSize -= count; if(*lookAhead == value) { remainder = skipOffset; for(backTrack = lookAhead - 1; *backTrack == value; --backTrack) { if(--remainder == 0) return (lookAhead - skipOffset); // success } if(remainder <= tailSize) { prevRemainder = remainder; while(*(++lookAhead) == value) { if(--remainder == 0) return (backTrack + 1); // success } tailSize -= (prevRemainder - remainder); } else return last; // failure } // lookAhead here is always pointing to the element of the last mismatch. } } return last; // failure } /// search_n /// /// Returns: The first iterator i in the range [first, last count) such that /// for any nonnegative integer n less than count the following corresponding /// conditions hold: *(i + n) == value, pred(*(i + n),value) != false. /// Returns last if no such iterator is found. /// /// Complexity: At most '(last1 - first1) * count' applications of the corresponding predicate. /// template <typename ForwardIterator, typename Size, typename T> ForwardIterator search_n(ForwardIterator first, ForwardIterator last, Size count, const T& value) { typedef typename eastl::iterator_traits<ForwardIterator>::iterator_category IC; return eastl::search_n_impl(first, last, count, value, IC()); } /// binary_search /// /// Returns: true if there is an iterator i in the range [first last) that /// satisfies the corresponding conditions: !(*i < value) && !(value < *i). /// /// Complexity: At most 'log(last - first) + 2' comparisons. /// /// Note: The reason binary_search returns bool instead of an iterator is /// that search_n, lower_bound, or equal_range already return an iterator. /// However, there are arguments that binary_search should return an iterator. /// Note that we provide binary_search_i (STL extension) to return an iterator. /// /// To use search_n to find an item, do this: /// iterator i = search_n(begin, end, 1, value); /// To use lower_bound to find an item, do this: /// iterator i = lower_bound(begin, end, value); /// if((i != last) && !(value < *i)) /// <use the iterator> /// It turns out that the above lower_bound method is as fast as binary_search /// would be if it returned an iterator. /// template <typename ForwardIterator, typename T> inline bool binary_search(ForwardIterator first, ForwardIterator last, const T& value) { // To do: This can be made slightly faster by not using lower_bound. ForwardIterator i(eastl::lower_bound<ForwardIterator, T>(first, last, value)); return ((i != last) && !(value < *i)); // Note that we always express value comparisons in terms of < or ==. } /// binary_search /// /// Returns: true if there is an iterator i in the range [first last) that /// satisfies the corresponding conditions: compare(*i, value) == false && /// compare(value, *i) == false. /// /// Complexity: At most 'log(last - first) + 2' comparisons. /// /// Note: See comments above regarding the bool return value of binary_search. /// template <typename ForwardIterator, typename T, typename Compare> inline bool binary_search(ForwardIterator first, ForwardIterator last, const T& value, Compare compare) { // To do: This can be made slightly faster by not using lower_bound. ForwardIterator i(eastl::lower_bound<ForwardIterator, T, Compare>(first, last, value, compare)); return ((i != last) && !compare(value, *i)); } /// binary_search_i /// /// Returns: iterator if there is an iterator i in the range [first last) that /// satisfies the corresponding conditions: !(*i < value) && !(value < *i). /// Returns last if the value is not found. /// /// Complexity: At most 'log(last - first) + 2' comparisons. /// template <typename ForwardIterator, typename T> inline ForwardIterator binary_search_i(ForwardIterator first, ForwardIterator last, const T& value) { // To do: This can be made slightly faster by not using lower_bound. ForwardIterator i(eastl::lower_bound<ForwardIterator, T>(first, last, value)); if((i != last) && !(value < *i)) // Note that we always express value comparisons in terms of < or ==. return i; return last; } /// binary_search_i /// /// Returns: iterator if there is an iterator i in the range [first last) that /// satisfies the corresponding conditions: !(*i < value) && !(value < *i). /// Returns last if the value is not found. /// /// Complexity: At most 'log(last - first) + 2' comparisons. /// template <typename ForwardIterator, typename T, typename Compare> inline ForwardIterator binary_search_i(ForwardIterator first, ForwardIterator last, const T& value, Compare compare) { // To do: This can be made slightly faster by not using lower_bound. ForwardIterator i(eastl::lower_bound<ForwardIterator, T, Compare>(first, last, value, compare)); if((i != last) && !compare(value, *i)) return i; return last; } /// unique /// /// Given a sorted range, this function removes duplicated items. /// Note that if you have a container then you will probably want /// to call erase on the container with the return value if your /// goal is to remove the duplicated items from the container. /// /// Effects: Eliminates all but the first element from every consecutive /// group of equal elements referred to by the iterator i in the range /// [first, last) for which the following corresponding condition holds: /// *i == *(i - 1). /// /// Returns: The end of the resulting range. /// /// Complexity: If the range (last - first) is not empty, exactly (last - first) /// applications of the corresponding predicate, otherwise no applications of the predicate. /// /// Example usage: /// vector<int> intArray; /// ... /// intArray.erase(unique(intArray.begin(), intArray.end()), intArray.end()); /// template <typename ForwardIterator> ForwardIterator unique(ForwardIterator first, ForwardIterator last) { first = eastl::adjacent_find<ForwardIterator>(first, last); if(first != last) // We expect that there are duplicated items, else the user wouldn't be calling this function. { ForwardIterator dest(first); for(++first; first != last; ++first) { if(!(*dest == *first)) // Note that we always express value comparisons in terms of < or ==. *++dest = *first; } return ++dest; } return last; } /// unique /// /// Given a sorted range, this function removes duplicated items. /// Note that if you have a container then you will probably want /// to call erase on the container with the return value if your /// goal is to remove the duplicated items from the container. /// /// Effects: Eliminates all but the first element from every consecutive /// group of equal elements referred to by the iterator i in the range /// [first, last) for which the following corresponding condition holds: /// predicate(*i, *(i - 1)) != false. /// /// Returns: The end of the resulting range. /// /// Complexity: If the range (last - first) is not empty, exactly (last - first) /// applications of the corresponding predicate, otherwise no applications of the predicate. /// template <typename ForwardIterator, typename BinaryPredicate> ForwardIterator unique(ForwardIterator first, ForwardIterator last, BinaryPredicate predicate) { first = eastl::adjacent_find<ForwardIterator, BinaryPredicate>(first, last, predicate); if(first != last) // We expect that there are duplicated items, else the user wouldn't be calling this function. { ForwardIterator dest(first); for(++first; first != last; ++first) { if(!predicate(*dest, *first)) *++dest = *first; } return ++dest; } return last; } // find_end // // We provide two versions here, one for a bidirectional iterators and one for // regular forward iterators. Given that we are searching backward, it's a bit // more efficient if we can use backwards iteration to implement our search, // though this requires an iterator that can be reversed. // template <typename ForwardIterator1, typename ForwardIterator2> ForwardIterator1 find_end_impl(ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2, EASTL_ITC_NS::forward_iterator_tag, EASTL_ITC_NS::forward_iterator_tag) { if(first2 != last2) // We have to do this check because the search algorithm below will return first1 (and not last1) if the first2/last2 range is empty. { for(ForwardIterator1 result(last1); ; ) { const ForwardIterator1 resultNext(eastl::search(first1, last1, first2, last2)); if(resultNext != last1) // If another sequence was found... { first1 = result = resultNext; ++first1; } else return result; } } return last1; } template <typename BidirectionalIterator1, typename BidirectionalIterator2> BidirectionalIterator1 find_end_impl(BidirectionalIterator1 first1, BidirectionalIterator1 last1, BidirectionalIterator2 first2, BidirectionalIterator2 last2, EASTL_ITC_NS::bidirectional_iterator_tag, EASTL_ITC_NS::bidirectional_iterator_tag) { typedef eastl::reverse_iterator<BidirectionalIterator1> reverse_iterator1; typedef eastl::reverse_iterator<BidirectionalIterator2> reverse_iterator2; reverse_iterator1 rresult(eastl::search(reverse_iterator1(last1), reverse_iterator1(first1), reverse_iterator2(last2), reverse_iterator2(first2))); if(rresult.base() != first1) // If we found something... { BidirectionalIterator1 result(rresult.base()); eastl::advance(result, -eastl::distance(first2, last2)); // We have an opportunity to optimize this, as the return result; // search function already calculates this distance. } return last1; } /// find_end /// /// Finds the last occurrence of the second sequence in the first sequence. /// As such, this function is much like the C string function strrstr and it /// is also the same as a reversed version of 'search'. It is called find_end /// instead of the possibly more consistent search_end simply because the C++ /// standard algorithms have such naming. /// /// Returns an iterator between first1 and last1 if the sequence is found. /// returns last1 (the end of the first seqence) if the sequence is not found. /// template <typename ForwardIterator1, typename ForwardIterator2> inline ForwardIterator1 find_end(ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2) { typedef typename eastl::iterator_traits<ForwardIterator1>::iterator_category IC1; typedef typename eastl::iterator_traits<ForwardIterator2>::iterator_category IC2; return eastl::find_end_impl(first1, last1, first2, last2, IC1(), IC2()); } // To consider: Fold the predicate and non-predicate versions of // this algorithm into a single function. template <typename ForwardIterator1, typename ForwardIterator2, typename BinaryPredicate> ForwardIterator1 find_end_impl(ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2, BinaryPredicate predicate, EASTL_ITC_NS::forward_iterator_tag, EASTL_ITC_NS::forward_iterator_tag) { if(first2 != last2) // We have to do this check because the search algorithm below will return first1 (and not last1) if the first2/last2 range is empty. { for(ForwardIterator1 result = last1; ; ) { const ForwardIterator1 resultNext(eastl::search<ForwardIterator1, ForwardIterator2, BinaryPredicate>(first1, last1, first2, last2, predicate)); if(resultNext != last1) // If another sequence was found... { first1 = result = resultNext; ++first1; } else return result; } } return last1; } template <typename BidirectionalIterator1, typename BidirectionalIterator2, typename BinaryPredicate> BidirectionalIterator1 find_end_impl(BidirectionalIterator1 first1, BidirectionalIterator1 last1, BidirectionalIterator2 first2, BidirectionalIterator2 last2, BinaryPredicate predicate, EASTL_ITC_NS::bidirectional_iterator_tag, EASTL_ITC_NS::bidirectional_iterator_tag) { typedef eastl::reverse_iterator<BidirectionalIterator1> reverse_iterator1; typedef eastl::reverse_iterator<BidirectionalIterator2> reverse_iterator2; reverse_iterator1 rresult(eastl::search<reverse_iterator1, reverse_iterator2, BinaryPredicate> (reverse_iterator1(last1), reverse_iterator1(first1), reverse_iterator2(last2), reverse_iterator2(first2), predicate)); if(rresult.base() != first1) // If we found something... { BidirectionalIterator1 result(rresult.base()); eastl::advance(result, -eastl::distance(first2, last2)); return result; } return last1; } /// find_end /// /// Effects: Finds a subsequence of equal values in a sequence. /// /// Returns: The last iterator i in the range [first1, last1 - (last2 - first2)) /// such that for any nonnegative integer n < (last2 - first2), the following /// corresponding conditions hold: pred(*(i+n),*(first2+n)) != false. Returns /// last1 if no such iterator is found. /// /// Complexity: At most (last2 - first2) * (last1 - first1 - (last2 - first2) + 1) /// applications of the corresponding predicate. /// template <typename ForwardIterator1, typename ForwardIterator2, typename BinaryPredicate> inline ForwardIterator1 find_end(ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2, BinaryPredicate predicate) { typedef typename eastl::iterator_traits<ForwardIterator1>::iterator_category IC1; typedef typename eastl::iterator_traits<ForwardIterator2>::iterator_category IC2; return eastl::find_end_impl<ForwardIterator1, ForwardIterator2, BinaryPredicate> (first1, last1, first2, last2, predicate, IC1(), IC2()); } /// set_difference /// /// set_difference iterates over both input ranges and copies elements present /// in the first range but not the second to the output range. /// /// Effects: Copies the elements of the range [first1, last1) which are not /// present in the range [first2, last2) to the range beginning at result. /// The elements in the constructed range are sorted. /// /// Requires: The input ranges must be sorted. /// Requires: The output range shall not overlap with either of the original ranges. /// /// Returns: The end of the output range. /// /// Complexity: At most (2 * ((last1 - first1) + (last2 - first2)) - 1) comparisons. /// template <typename InputIterator1, typename InputIterator2, typename OutputIterator> OutputIterator set_difference(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result) { while((first1 != last1) && (first2 != last2)) { if(*first1 < *first2) { *result = *first1; ++first1; ++result; } else if(*first2 < *first1) ++first2; else { ++first1; ++first2; } } return eastl::copy(first1, last1, result); } template <typename InputIterator1, typename InputIterator2, typename OutputIterator, typename Compare> OutputIterator set_difference(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result, Compare compare) { while((first1 != last1) && (first2 != last2)) { if(compare(*first1, *first2)) { EASTL_VALIDATE_COMPARE(!compare(*first2, *first1)); // Validate that the compare function is sane. *result = *first1; ++first1; ++result; } else if(compare(*first2, *first1)) { EASTL_VALIDATE_COMPARE(!compare(*first1, *first2)); // Validate that the compare function is sane. ++first2; } else { ++first1; ++first2; } } return eastl::copy(first1, last1, result); } /// set_symmetric_difference /// /// set_difference iterates over both input ranges and copies elements present /// in the either range but not the other to the output range. /// /// Effects: Copies the elements of the range [first1, last1) which are not /// present in the range [first2, last2), and the elements of the range [first2, last2) /// which are not present in the range [first1, last1) to the range beginning at result. /// The elements in the constructed range are sorted. /// /// Requires: The input ranges must be sorted. /// Requires: The resulting range shall not overlap with either of the original ranges. /// /// Returns: The end of the constructed range. /// /// Complexity: At most (2 * ((last1 - first1) + (last2 - first2)) - 1) comparisons. /// template <typename InputIterator1, typename InputIterator2, typename OutputIterator> OutputIterator set_symmetric_difference(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result) { while((first1 != last1) && (first2 != last2)) { if(*first1 < *first2) { *result = *first1; ++first1; ++result; } else if(*first2 < *first1) { *result = *first2; ++first2; ++result; } else { ++first1; ++first2; } } return eastl::copy(first2, last2, eastl::copy(first1, last1, result)); } template <typename InputIterator1, typename InputIterator2, typename OutputIterator, typename Compare> OutputIterator set_symmetric_difference(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result, Compare compare) { while((first1 != last1) && (first2 != last2)) { if(compare(*first1, *first2)) { EASTL_VALIDATE_COMPARE(!compare(*first2, *first1)); // Validate that the compare function is sane. *result = *first1; ++first1; ++result; } else if(compare(*first2, *first1)) { EASTL_VALIDATE_COMPARE(!compare(*first1, *first2)); // Validate that the compare function is sane. *result = *first2; ++first2; ++result; } else { ++first1; ++first2; } } return eastl::copy(first2, last2, eastl::copy(first1, last1, result)); } /// set_intersection /// /// set_intersection over both ranges and copies elements present in /// both ranges to the output range. /// /// Effects: Constructs a sorted intersection of the elements from the /// two ranges; that is, the set of elements that are present in both of the ranges. /// /// Requires: The input ranges must be sorted. /// Requires: The resulting range shall not overlap with either of the original ranges. /// /// Returns: The end of the constructed range. /// /// Complexity: At most 2 * ((last1 - first1) + (last2 - first2)) - 1) comparisons. /// /// Note: The copying operation is stable; if an element is present in both ranges, /// the one from the first range is copied. /// template <typename InputIterator1, typename InputIterator2, typename OutputIterator> OutputIterator set_intersection(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result) { while((first1 != last1) && (first2 != last2)) { if(*first1 < *first2) ++first1; else if(*first2 < *first1) ++first2; else { *result = *first1; ++first1; ++first2; ++result; } } return result; } template <typename InputIterator1, typename InputIterator2, typename OutputIterator, typename Compare> OutputIterator set_intersection(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result, Compare compare) { while((first1 != last1) && (first2 != last2)) { if(compare(*first1, *first2)) { EASTL_VALIDATE_COMPARE(!compare(*first2, *first1)); // Validate that the compare function is sane. ++first1; } else if(compare(*first2, *first1)) { EASTL_VALIDATE_COMPARE(!compare(*first1, *first2)); // Validate that the compare function is sane. ++first2; } else { *result = *first1; ++first1; ++first2; ++result; } } return result; } /// set_union /// /// set_union iterators over both ranges and copies elements present in /// both ranges to the output range. /// /// Effects: Constructs a sorted union of the elements from the two ranges; /// that is, the set of elements that are present in one or both of the ranges. /// /// Requires: The input ranges must be sorted. /// Requires: The resulting range shall not overlap with either of the original ranges. /// /// Returns: The end of the constructed range. /// /// Complexity: At most (2 * ((last1 - first1) + (last2 - first2)) - 1) comparisons. /// /// Note: The copying operation is stable; if an element is present in both ranges, /// the one from the first range is copied. /// template <typename InputIterator1, typename InputIterator2, typename OutputIterator> OutputIterator set_union(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result) { while((first1 != last1) && (first2 != last2)) { if(*first1 < *first2) { *result = *first1; ++first1; } else if(*first2 < *first1) { *result = *first2; ++first2; } else { *result = *first1; ++first1; ++first2; } ++result; } return eastl::copy(first2, last2, eastl::copy(first1, last1, result)); } template <typename InputIterator1, typename InputIterator2, typename OutputIterator, typename Compare> OutputIterator set_union(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result, Compare compare) { while((first1 != last1) && (first2 != last2)) { if(compare(*first1, *first2)) { EASTL_VALIDATE_COMPARE(!compare(*first2, *first1)); // Validate that the compare function is sane. *result = *first1; ++first1; } else if(compare(*first2, *first1)) { EASTL_VALIDATE_COMPARE(!compare(*first1, *first2)); // Validate that the compare function is sane. *result = *first2; ++first2; } else { *result = *first1; ++first1; ++first2; } ++result; } return eastl::copy(first2, last2, eastl::copy(first1, last1, result)); } /// is_permutation /// template<typename ForwardIterator1, typename ForwardIterator2> bool is_permutation(ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2) { typedef typename eastl::iterator_traits<ForwardIterator1>::difference_type difference_type; // Skip past any equivalent initial elements. while((first1 != last1) && (*first1 == *first2)) { ++first1; ++first2; } if(first1 != last1) { const difference_type first1Size = eastl::distance(first1, last1); ForwardIterator2 last2 = first2; eastl::advance(last2, first1Size); for(ForwardIterator1 i = first1; i != last1; ++i) { if(i == eastl::find(first1, i, *i)) { const difference_type c = eastl::count(first2, last2, *i); if((c == 0) || (c != eastl::count(i, last1, *i))) return false; } } } return true; } /// is_permutation /// template<typename ForwardIterator1, typename ForwardIterator2, class BinaryPredicate> bool is_permutation(ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, BinaryPredicate predicate) { typedef typename eastl::iterator_traits<ForwardIterator1>::difference_type difference_type; // Skip past any equivalent initial elements. while((first1 != last1) && predicate(*first1, *first2)) { ++first1; ++first2; } if(first1 != last1) { const difference_type first1Size = eastl::distance(first1, last1); ForwardIterator2 last2 = first2; eastl::advance(last2, first1Size); for(ForwardIterator1 i = first1; i != last1; ++i) { if(i == eastl::find(first1, i, *i, predicate)) { const difference_type c = eastl::count(first2, last2, *i, predicate); if((c == 0) || (c != eastl::count(i, last1, *i, predicate))) return false; } } } return true; } /// next_permutation /// /// mutates the range [first, last) to the next permutation. Returns true if the /// new range is not the final permutation (sorted like the starting permutation). /// Permutations start with a sorted range, and false is returned when next_permutation /// results in the initial sorted range, or if the range has <= 1 element. /// Note that elements are compared by operator < (as usual) and that elements deemed /// equal via this are not rearranged. /// /// http://marknelson.us/2002/03/01/next-permutation/ /// Basically we start with an ordered range and reverse it's order one specifically /// chosen swap and reverse at a time. It happens that this require going through every /// permutation of the range. We use the same variable names as the document above. /// /// To consider: Significantly improved permutation/combination functionality: /// http://home.roadrunner.com/~hinnant/combinations.html /// /// Example usage: /// vector<int> intArray; /// // <populate intArray> /// sort(intArray.begin(), intArray.end()); /// do { /// // <do something with intArray> /// } while(next_permutation(intArray.begin(), intArray.end())); /// template<typename BidirectionalIterator, typename Compare> bool next_permutation(BidirectionalIterator first, BidirectionalIterator last, Compare compare) { if(first != last) // If there is anything in the range... { BidirectionalIterator i = last; if(first != --i) // If the range has more than one item... { for(;;) { BidirectionalIterator ii(i), j; if(compare(*--i, *ii)) // Find two consecutive values where the first is less than the second. { j = last; while(!compare(*i, *--j)) // Find the final value that's greater than the first (it may be equal to the second). {} eastl::iter_swap(i, j); // Swap the first and the final. eastl::reverse(ii, last); // Reverse the ranget from second to last. return true; } if(i == first) // There are no two consecutive values where the first is less than the second, meaning the range is in reverse order. The reverse ordered range is always the last permutation. { eastl::reverse(first, last); break; // We are done. } } } } return false; } template<typename BidirectionalIterator> bool next_permutation(BidirectionalIterator first, BidirectionalIterator last) { typedef typename eastl::iterator_traits<BidirectionalIterator>::value_type value_type; return next_permutation(first, last, eastl::less<value_type>()); } /// rotate /// /// Effects: For each non-negative integer i < (last - first), places the element from the /// position first + i into position first + (i + (last - middle)) % (last - first). /// /// Returns: first + (last - middle). That is, returns where first went to. /// /// Remarks: This is a left rotate. /// /// Requires: [first,middle) and [middle,last) shall be valid ranges. ForwardIterator shall /// satisfy the requirements of ValueSwappable (17.6.3.2). The type of *first shall satisfy /// the requirements of MoveConstructible (Table 20) and the requirements of MoveAssignable. /// /// Complexity: At most last - first swaps. /// /// Note: While rotate works on ForwardIterators (e.g. slist) and BidirectionalIterators (e.g. list), /// you can get much better performance (O(1) instead of O(n)) with slist and list rotation by /// doing splice operations on those lists instead of calling this rotate function. /// /// http://www.cs.bell-labs.com/cm/cs/pearls/s02b.pdf / http://books.google.com/books?id=kse_7qbWbjsC&pg=PA14&lpg=PA14&dq=Programming+Pearls+flipping+hands /// http://books.google.com/books?id=tjOlkl7ecVQC&pg=PA189&lpg=PA189&dq=stepanov+Elements+of+Programming+rotate /// http://stackoverflow.com/questions/21160875/why-is-stdrotate-so-fast /// /// Strategy: /// - We handle the special case of (middle == first) and (middle == last) no-ops /// up front in the main rotate entry point. /// - There's a basic ForwardIterator implementation (rotate_general_impl) which is /// a fallback implementation that's not as fast as others but works for all cases. /// - There's a slightly better BidirectionalIterator implementation. /// - We have specialized versions for rotating elements that are is_trivially_move_assignable. /// These versions will use memmove for when we have a RandomAccessIterator. /// - We have a specialized version for rotating by only a single position, as that allows us /// (with any iterator type) to avoid a lot of logic involved with algorithms like "flipping hands" /// and achieve near optimal O(n) behavior. it turns out that rotate-by-one is a common use /// case in practice. /// namespace Internal { template<typename ForwardIterator> ForwardIterator rotate_general_impl(ForwardIterator first, ForwardIterator middle, ForwardIterator last) { using eastl::swap; ForwardIterator current = middle; do { swap(*first++, *current++); if(first == middle) middle = current; } while(current != last); ForwardIterator result = first; current = middle; while(current != last) { swap(*first++, *current++); if(first == middle) middle = current; else if(current == last) current = middle; } return result; // result points to first + (last - middle). } template <typename ForwardIterator> ForwardIterator move_rotate_left_by_one(ForwardIterator first, ForwardIterator last) { typedef typename eastl::iterator_traits<ForwardIterator>::value_type value_type; value_type temp(eastl::move(*first)); ForwardIterator result = eastl::move(eastl::next(first), last, first); // Note that while our template type is BidirectionalIterator, if the actual *result = eastl::move(temp); // iterator is a RandomAccessIterator then this move will be a memmove for trivial types. return result; // result points to the final element in the range. } template <typename BidirectionalIterator> BidirectionalIterator move_rotate_right_by_one(BidirectionalIterator first, BidirectionalIterator last) { typedef typename eastl::iterator_traits<BidirectionalIterator>::value_type value_type; BidirectionalIterator beforeLast = eastl::prev(last); value_type temp(eastl::move(*beforeLast)); BidirectionalIterator result = eastl::move_backward(first, beforeLast, last); // Note that while our template type is BidirectionalIterator, if the actual *first = eastl::move(temp); // iterator is a RandomAccessIterator then this move will be a memmove for trivial types. return result; // result points to the first element in the range. } template <typename /*IteratorCategory*/, bool /*is_trivially_move_assignable*/> struct rotate_helper { template <typename ForwardIterator> static ForwardIterator rotate_impl(ForwardIterator first, ForwardIterator middle, ForwardIterator last) { return Internal::rotate_general_impl(first, middle, last); } }; template <> struct rotate_helper<EASTL_ITC_NS::forward_iterator_tag, true> { template <typename ForwardIterator> static ForwardIterator rotate_impl(ForwardIterator first, ForwardIterator middle, ForwardIterator last) { if(eastl::next(first) == middle) // If moving trivial types by a single element, memcpy is fast for that case. return Internal::move_rotate_left_by_one(first, last); return Internal::rotate_general_impl(first, middle, last); } }; template <> struct rotate_helper<EASTL_ITC_NS::bidirectional_iterator_tag, false> { template <typename BidirectionalIterator> static BidirectionalIterator rotate_impl(BidirectionalIterator first, BidirectionalIterator middle, BidirectionalIterator last) { return Internal::rotate_general_impl(first, middle, last); } // rotate_general_impl outperforms the flipping hands algorithm. /* // Simplest "flipping hands" implementation. Disabled because it's slower on average than rotate_general_impl. template <typename BidirectionalIterator> static BidirectionalIterator rotate_impl(BidirectionalIterator first, BidirectionalIterator middle, BidirectionalIterator last) { eastl::reverse(first, middle); eastl::reverse(middle, last); eastl::reverse(first, last); return first + (last - middle); // This can be slow for large ranges because operator + and - are O(n). } // Smarter "flipping hands" implementation, but still disabled because benchmarks are showing it to be slower than rotate_general_impl. template <typename BidirectionalIterator> static BidirectionalIterator rotate_impl(BidirectionalIterator first, BidirectionalIterator middle, BidirectionalIterator last) { // This is the "flipping hands" algorithm. eastl::reverse_impl(first, middle, EASTL_ITC_NS::bidirectional_iterator_tag()); // Reverse the left side. eastl::reverse_impl(middle, last, EASTL_ITC_NS::bidirectional_iterator_tag()); // Reverse the right side. // Reverse the entire range. while((first != middle) && (middle != last)) { eastl::iter_swap(first, --last); ++first; } if(first == middle) // Finish reversing the entire range. { eastl::reverse_impl(middle, last, bidirectional_iterator_tag()); return last; } else { eastl::reverse_impl(first, middle, bidirectional_iterator_tag()); return first; } } */ }; template <> struct rotate_helper<EASTL_ITC_NS::bidirectional_iterator_tag, true> { template <typename BidirectionalIterator> static BidirectionalIterator rotate_impl(BidirectionalIterator first, BidirectionalIterator middle, BidirectionalIterator last) { if(eastl::next(first) == middle) // If moving trivial types by a single element, memcpy is fast for that case. return Internal::move_rotate_left_by_one(first, last); if(eastl::next(middle) == last) return Internal::move_rotate_right_by_one(first, last); return Internal::rotate_general_impl(first, middle, last); } }; template <typename Integer> inline Integer greatest_common_divisor(Integer x, Integer y) { do { Integer t = (x % y); x = y; y = t; } while(y); return x; } template <> struct rotate_helper<EASTL_ITC_NS::random_access_iterator_tag, false> { // This is the juggling algorithm, using move operations. // In practice this implementation is about 25% faster than rotate_general_impl. We may want to // consider sticking with just rotate_general_impl and avoid the code generation of this function. template <typename RandomAccessIterator> static RandomAccessIterator rotate_impl(RandomAccessIterator first, RandomAccessIterator middle, RandomAccessIterator last) { typedef typename iterator_traits<RandomAccessIterator>::difference_type difference_type; typedef typename iterator_traits<RandomAccessIterator>::value_type value_type; const difference_type m1 = (middle - first); const difference_type m2 = (last - middle); const difference_type g = Internal::greatest_common_divisor(m1, m2); value_type temp; for(RandomAccessIterator p = first + g; p != first;) { temp = eastl::move(*--p); RandomAccessIterator p1 = p; RandomAccessIterator p2 = p + m1; do { *p1 = eastl::move(*p2); p1 = p2; const difference_type d = (last - p2); if(m1 < d) p2 += m1; else p2 = first + (m1 - d); } while(p2 != p); *p1 = eastl::move(temp); } return first + m2; } }; template <> struct rotate_helper<EASTL_ITC_NS::random_access_iterator_tag, true> { // Experiments were done which tested the performance of using an intermediate buffer // to do memcpy's to as opposed to executing a swapping algorithm. It turns out this is // actually slower than even rotate_general_impl, partly because the average case involves // memcpy'ing a quarter of the element range twice. Experiments were done with various kinds // of PODs with various element counts. template <typename RandomAccessIterator> static RandomAccessIterator rotate_impl(RandomAccessIterator first, RandomAccessIterator middle, RandomAccessIterator last) { if(eastl::next(first) == middle) // If moving trivial types by a single element, memcpy is fast for that case. return Internal::move_rotate_left_by_one(first, last); if(eastl::next(middle) == last) return Internal::move_rotate_right_by_one(first, last); if((last - first) < 32) // For small ranges rotate_general_impl is faster. return Internal::rotate_general_impl(first, middle, last); return Internal::rotate_helper<EASTL_ITC_NS::random_access_iterator_tag, false>::rotate_impl(first, middle, last); } }; } // namespace Internal template <typename ForwardIterator> ForwardIterator rotate(ForwardIterator first, ForwardIterator middle, ForwardIterator last) { if(middle != first) { if(middle != last) { typedef typename eastl::iterator_traits<ForwardIterator>::iterator_category IC; typedef typename eastl::iterator_traits<ForwardIterator>::value_type value_type; return Internal::rotate_helper<IC, eastl::is_trivially_move_assignable<value_type>::value || // This is the best way of telling if we can move types via memmove, but without a conforming C++11 compiler it usually returns false. eastl::is_pod<value_type>::value || // This is a more conservative way of telling if we can move types via memmove, and most compilers support it, but it doesn't have as full of coverage as is_trivially_move_assignable. eastl::is_scalar<value_type>::value> // This is the most conservative means and works with all compilers, but works only for scalars. ::rotate_impl(first, middle, last); } return first; } return last; } /// rotate_copy /// /// Similar to rotate except writes the output to the OutputIterator and /// returns an OutputIterator to the element past the last element copied /// (i.e. result + (last - first)) /// template <typename ForwardIterator, typename OutputIterator> OutputIterator rotate_copy(ForwardIterator first, ForwardIterator middle, ForwardIterator last, OutputIterator result) { return eastl::copy(first, middle, eastl::copy(middle, last, result)); } /// clamp /// /// Returns a reference to a clamped value within the range of [lo, hi]. /// /// http://en.cppreference.com/w/cpp/algorithm/clamp /// template <class T> EA_CONSTEXPR const T& clamp(const T& v, const T& lo, const T& hi) { return clamp(v, lo, hi, eastl::less<>()); } template <class T, class Compare> EA_CONSTEXPR const T& clamp(const T& v, const T& lo, const T& hi, Compare comp) { // code collapsed to a single line due to constexpr requirements return [&] { EASTL_ASSERT(!comp(hi, lo)); }(), comp(v, lo) ? lo : comp(hi, v) ? hi : v; } } // namespace eastl #endif // Header include guard
{ "content_hash": "d3cc7ce7a7caa4adf2d9a0f5d13ebd70", "timestamp": "", "source": "github", "line_count": 4238, "max_line_length": 281, "avg_line_length": 35.097923548843795, "alnum_prop": 0.6717671182224613, "repo_name": "exnotime/Tephra", "id": "bd9189eaa36d230c1bbad1802513ef8290372634", "size": "148745", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "include/EASTL/algorithm.h", "mode": "33188", "license": "mit", "language": [ { "name": "AngelScript", "bytes": "3031" }, { "name": "Batchfile", "bytes": "18" }, { "name": "C", "bytes": "4020612" }, { "name": "C++", "bytes": "7661756" }, { "name": "CMake", "bytes": "3820" }, { "name": "GLSL", "bytes": "82072" }, { "name": "Lua", "bytes": "5799" }, { "name": "Makefile", "bytes": "286" }, { "name": "Objective-C", "bytes": "53563" }, { "name": "Scheme", "bytes": "584" }, { "name": "ShaderLab", "bytes": "231" }, { "name": "Shell", "bytes": "1067" } ], "symlink_target": "" }
package xyz.appint.union.dao.page; import java.util.ArrayList; import java.util.List; /** * Created by Justin */ public class NavPage<E> extends DefaultPage<E> { private static final int DEFAULT_NAVI_PAGE_SIZE = 10; private int naviPageSize = DEFAULT_NAVI_PAGE_SIZE; // 导航上最多可展示的页数 默认是10 private int startPage; // 导航上开始页号码 private int endPage; // 导航上结束页号码 private String pageBar; public NavPage(int pageNumber, int pageSize, int totalCount, int naviPageSize) { this(pageNumber, pageSize, totalCount, new ArrayList<E>(0), naviPageSize); } public NavPage(int pageNumber, int pageSize, int totalCount, List<E> result, int naviPageSize) { super(pageNumber, pageSize, totalCount, result); this.naviPageSize = naviPageSize; if (this.naviPageSize == 0) { this.naviPageSize = DEFAULT_NAVI_PAGE_SIZE; } execute(); } public NavPage(int pageNumber, int pageSize) { this(pageNumber, pageSize, -1, DEFAULT_NAVI_PAGE_SIZE); } public NavPage(PageRequest pageRequest, int totalCount, int naviPageSize) { this(pageRequest.getPageNumber(), pageRequest.getPageSize(), totalCount, naviPageSize); } public NavPage(PageRequest pageRequest, int totalCount) { this(pageRequest.getPageNumber(), pageRequest.getPageSize(), totalCount, DEFAULT_NAVI_PAGE_SIZE); } @Override public void setTotalCount(int totalCount) { super.setTotalCount(totalCount); execute(); } protected void execute() { // 导航上开始页号码 startPage = getPageNumber() % getNaviPageSize() == 0 ? ((getPageNumber() - 1) / getNaviPageSize()) * getNaviPageSize() + 1 : (getPageNumber() / getNaviPageSize()) * getNaviPageSize() + 1; // 导航上结束页号码 endPage = startPage + getNaviPageSize() - 1 >= getPages() ? getPages() : startPage + getNaviPageSize() - 1; } public int getNaviPageSize() { if (this.naviPageSize == 0) { this.naviPageSize = DEFAULT_NAVI_PAGE_SIZE; } return naviPageSize; } public int getStartPage() { return startPage; } public int getEndPage() { return endPage; } }
{ "content_hash": "3e52ab96ff2e0a80b962691410b8b129", "timestamp": "", "source": "github", "line_count": 76, "max_line_length": 106, "avg_line_length": 29.789473684210527, "alnum_prop": 0.6360424028268551, "repo_name": "xyz-appint/union", "id": "c2730bbe31bdbf248c53f07c5672421ab9e3409a", "size": "2356", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "union-dao/src/main/java/xyz/appint/union/dao/page/NavPage.java", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "388596" } ], "symlink_target": "" }
$(document).ready(function() { // Add Close Button $('.contact .wrapper').append('<a class="btn-close button circle light"><i class="i-cancel"></i><span class="element-invisible">Close</span></a>'); //Close Toggle $('.btn-close').click(function(e){ if ($('#page').attr('data-state') == 'slide-open') { $('#page').attr('data-state', 'slide-closed'); } else { $('#page').attr('data-state', 'slide-open'); } e.preventDefault(); }); // Menu Toggle $('.contact-btn').click(function(e){ if ($('#page').attr('data-state') == 'slide-open') { $('#page').attr('data-state', 'slide-closed'); } else { $('#page').attr('data-state', 'slide-open'); $('body').animate({ scrollTop: $("#contact-top").offset().top }, 1000); } e.preventDefault(); }); // Animate main menu var mainTop = 10; // on scroll, $(window).on('scroll',function(){ // we round here to reduce a little workload stop = Math.round($(window).scrollTop()); if (stop > mainTop) { $('.header').addClass('is-solid'); } else { $('.header').removeClass('is-solid'); } }); // Waypoints if($('.circle-wrap').length >0 ){ var waypoint = new Waypoint({ element: document.getElementById('wp'), handler: function(direction) { $('.circle-wrap').addClass('run'); }, offset: 600 }); } });
{ "content_hash": "743fb36bfcad417c73c6313bdaefeedf", "timestamp": "", "source": "github", "line_count": 59, "max_line_length": 151, "avg_line_length": 26.10169491525424, "alnum_prop": 0.4954545454545455, "repo_name": "tiffanytse/tiffanytse.ca", "id": "aeff3365c05f00015e0536c3ff0770ac17ef0444", "size": "1540", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "js/script.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "73647" }, { "name": "HTML", "bytes": "38802" }, { "name": "JavaScript", "bytes": "1540" }, { "name": "Ruby", "bytes": "910" } ], "symlink_target": "" }
package com.visenze.visearch.internal; import com.visenze.visearch.ResponseMessages; /** * <h1> ViSenze exception object </h1> * This class allows custom exceptions for internal usage such as storing * replies from our servers, logging of internal response messages. * * @since 08 Jan 2021 */ public class InternalViSearchException extends RuntimeException { /** * Raw reply from server */ private String serverRawResponse; /** * Constructor * * @param message Message for runtime exception * @param serverRawResponse Server response for internal usage */ public InternalViSearchException(String message, String serverRawResponse) { super(message); this.serverRawResponse = serverRawResponse; } /** * Constructor * * @param message Message for runtime exception */ public InternalViSearchException(String message) { super(message); } /** * Constructor * * @param responseMessages Internal response message to convert for runtime * exception * @see ResponseMessages */ public InternalViSearchException(ResponseMessages responseMessages) { super(responseMessages.getMessage()); } /** * Constructor * * @param responseMessages Internal response message to convert for runtime * exception * @param cause Throwable object * * @see ResponseMessages */ public InternalViSearchException(ResponseMessages responseMessages, Throwable cause) { super(responseMessages.getMessage(), cause); } /** * Constructor * * @param responseMessages Internal response message to convert for runtime * exception * @param serverRawResponse Server response for internal usage * * @see ResponseMessages */ public InternalViSearchException(ResponseMessages responseMessages, String serverRawResponse) { super(responseMessages.getMessage()); this.serverRawResponse = serverRawResponse; } /** * Constructor * * @param responseMessages Internal response message to convert for runtime * exception * @param cause Throwable object * @param serverRawResponse Server response for internal usage * * @see ResponseMessages */ public InternalViSearchException(ResponseMessages responseMessages, Throwable cause, String serverRawResponse) { super(responseMessages.getMessage(), cause); this.serverRawResponse = serverRawResponse; } /** * Get the server's raw response * * @return raw message from server */ public String getServerRawResponse() { return serverRawResponse; } }
{ "content_hash": "64f8010dab26a4e5ff60cae0cfc0bcbb", "timestamp": "", "source": "github", "line_count": 107, "max_line_length": 80, "avg_line_length": 28.130841121495326, "alnum_prop": 0.6179401993355482, "repo_name": "visenze/visearch-sdk-java", "id": "979aea212c4e2549d9a208830af53f52f0b0d40b", "size": "3010", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/visenze/visearch/internal/InternalViSearchException.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "432991" } ], "symlink_target": "" }
package com.highway.studydemo; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumentation test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() throws Exception { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("com.highway.studydemo", appContext.getPackageName()); } }
{ "content_hash": "7e33f8fd359e73bbcff9364fbb178732", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 78, "avg_line_length": 28.692307692307693, "alnum_prop": 0.7479892761394102, "repo_name": "wuhighway/DailyStudy", "id": "790d9511c7918a1c150b0c5f58fea0d7c7dfd216", "size": "746", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "shapedemo/src/androidTest/java/com/highway/studydemo/ExampleInstrumentedTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "37397" }, { "name": "Java", "bytes": "723490" } ], "symlink_target": "" }
#define XML_MAP_FILE 01 #define XML_EXTERNAL_ENTITIES 02 extern int XML_ProcessFile(XML_Parser parser, const XML_Char *filename, unsigned flags);
{ "content_hash": "8df8189c8482c0525f1c9db775d51c6f", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 52, "avg_line_length": 26.375, "alnum_prop": 0.5497630331753555, "repo_name": "airgames/vuforia-gamekit-integration", "id": "466dd7f7959809854fb2f78110e964e9a6a0ee0f", "size": "328", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Gamekit/wxWidgets-2.9.1/src/expat/xmlwf/xmlfile.h", "mode": "33261", "license": "mit", "language": [], "symlink_target": "" }
package eu.artemis.demanes.lib.impl.coapParameterization.server; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Set; import org.apache.log4j.Logger; import eu.artemis.demanes.datatypes.ANES_URN; import eu.artemis.demanes.exceptions.ParameterizationException; import eu.artemis.demanes.exceptions.ParameterizationValueTypeException; import eu.artemis.demanes.lib.ParameterizationProxy; import eu.artemis.demanes.lib.impl.communication.CommUtils; import eu.artemis.demanes.lib.impl.communication.PayloadSerializationException; import eu.artemis.demanes.logging.LogConstants; import eu.artemis.demanes.logging.LogEntry; import eu.artemis.demanes.parameterization.Parameterizable; /** * CoapParameterizationServerProxy * * @author leeuwencjv * @version 0.1 * @since 20 okt. 2014 * */ public class CoapParameterizationProxy implements ParameterizationProxy { private final Logger logger = Logger.getLogger("dmns:log"); private final Parameterizable broker; /** * @param p * @param s */ public CoapParameterizationProxy(Parameterizable p) { this.broker = p; } /* * (non-Javadoc) * * @see * eu.artemis.demanes.lib.ParameterizationProxy#getParameter(eu.artemis. * demanes.datatypes.ANES_URN) */ @Override public byte[] getParameter(ANES_URN urn) throws ParameterizationException { try { Object value = broker.getParameter(urn); return CommUtils.serialize(value); } catch (PayloadSerializationException e) { throw new ParameterizationValueTypeException(e); } } /* * (non-Javadoc) * * @see eu.artemis.demanes.lib.ParameterizationProxy#listParameters() */ @Override public byte[] listParameters() throws ParameterizationException { Set<ANES_URN> urnList = broker.listParameters(); try { // Put the value in a stream ByteArrayOutputStream bos = new ByteArrayOutputStream(); for (ANES_URN urn : urnList) { bos.write((byte) urn.toString().length()); bos.write(urn.toString().getBytes()); } return bos.toByteArray(); } catch (IOException e) { logger.error(new LogEntry(this.getClass().getName(), LogConstants.LOG_LEVEL_ERROR, "Param", "Unable to create URN list")); throw new ParameterizationValueTypeException( "Unable to create URN list"); } } /* * (non-Javadoc) * * @see * eu.artemis.demanes.lib.ParameterizationProxy#setParameter(eu.artemis. * demanes.datatypes.ANES_URN, byte[]) */ @Override public void setParameter(ANES_URN urn, byte[] value) throws ParameterizationException { this.broker.setParameter(urn, value); } }
{ "content_hash": "cd93a2c90032e536f16b07def540299f", "timestamp": "", "source": "github", "line_count": 100, "max_line_length": 79, "avg_line_length": 27.02, "alnum_prop": 0.7135455218356773, "repo_name": "DEMANES/demanes-coapparam", "id": "87bc2f6302a78bdb847c0fef5b3ad051964dcb97", "size": "3440", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/eu/artemis/demanes/lib/impl/coapParameterization/server/CoapParameterizationProxy.java", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "30813" } ], "symlink_target": "" }
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //******************************************************** using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.ApplicationModel; using Windows.Security.ExchangeActiveSyncProvisioning; using Windows.System.Profile; using Windows.Devices.Enumeration.Pnp; namespace AudioVideoPlayer.Information { public static class SystemInformation { public static string SystemFamily { get; } public static string SystemVersion { get; } public static string SystemArchitecture { get; } public static string ApplicationName { get; } public static string ApplicationVersion { get; } public static string DeviceManufacturer { get; } public static string DeviceModel { get; } public static string AppSpecificHardwareID { get; } public static string GetWindowsVersion() { string str; string[] strArray = { "{A8B865DD-2E3D-4094-AD97-E593A70C75D6},3" }; PnpObject halDevice = GetHalDevice(strArray); if (halDevice == null || !halDevice.Properties.ContainsKey("{A8B865DD-2E3D-4094-AD97-E593A70C75D6},3")) str = "UNKNOWN"; else str = halDevice.Properties["{A8B865DD-2E3D-4094-AD97-E593A70C75D6},3"].ToString(); return str; } private static PnpObject GetHalDevice(params String[] properties) { String[] strArray = properties; String[] strArray1 = { "{A45C254E-DF1C-4EFD-8020-67D146A850E0},10" }; IEnumerable<String> enumerable = strArray.Concat(strArray1); try { PnpObjectCollection pnpObjectCollection = PnpObject.FindAllAsync(PnpObjectType.Device, enumerable, "System.Devices.ContainerId:=\"{00000000-0000-0000-FFFF-FFFFFFFFFFFF}\"").GetResults(); foreach (PnpObject pnpObject in pnpObjectCollection) { if (pnpObject.Properties == null || !pnpObject.Properties.Any()) continue; KeyValuePair<String, Object> keyValuePair = pnpObject.Properties.Last(); if (keyValuePair.Value == null || !keyValuePair.Value.ToString().Equals("4d36e966-e325-11ce-bfc1-08002be10318")) continue; return pnpObject; } } catch(Exception e) { System.Diagnostics.Debug.WriteLine("Exception: " + e.Message); return null; } return null; } private static string GetAppSpecificHardwareID() { Windows.System.Profile.HardwareToken packageSpecificToken; try { packageSpecificToken = Windows.System.Profile.HardwareIdentification.GetPackageSpecificToken(null); if (packageSpecificToken != null) { Windows.Storage.Streams.DataReader dataReader = Windows.Storage.Streams.DataReader.FromBuffer(packageSpecificToken.Id); byte[] bytes = new byte[packageSpecificToken.Id.Length]; dataReader.ReadBytes(bytes); return BitConverter.ToString(bytes); } } catch (Exception e) { System.Diagnostics.Debug.WriteLine("Exception in GetAppSpecificHardwareID: " + e.Message); } return "UNKNOWN"; } static SystemInformation() { // get the system family name AnalyticsVersionInfo ai = AnalyticsInfo.VersionInfo; SystemFamily = ai.DeviceFamily; // get the system version number #if WINDOWS_UWP string sv = AnalyticsInfo.VersionInfo.DeviceFamilyVersion; ulong v = ulong.Parse(sv); ulong v1 = (v & 0xFFFF000000000000L) >> 48; ulong v2 = (v & 0x0000FFFF00000000L) >> 32; ulong v3 = (v & 0x00000000FFFF0000L) >> 16; ulong v4 = (v & 0x000000000000FFFFL); SystemVersion = $"{v1}.{v2}.{v3}.{v4}"; #else // get os version SystemVersion = GetWindowsVersion(); #endif // get the package architecure Package package = Package.Current; SystemArchitecture = package.Id.Architecture.ToString(); // get the user friendly app name ApplicationName = package.DisplayName; // get the app version PackageVersion pv = package.Id.Version; ApplicationVersion = $"{pv.Major}.{pv.Minor}.{pv.Build}.{pv.Revision}"; // get the device manufacturer and model name EasClientDeviceInformation eas = new EasClientDeviceInformation(); DeviceManufacturer = eas.SystemManufacturer; DeviceModel = eas.SystemProductName; // get App Specific Hardware ID AppSpecificHardwareID = GetAppSpecificHardwareID(); } public static string GetString() { string result = string.Empty; try { result = string.Format("System Information:\r\nFamily: {0}\r\nVersion: {1}\r\nArchitecture: {2}\r\nApplication Name: {3}\r\nApplication Version: {4}\r\nDevice Manufacturer: {5}\r\nDevice Model: {6}\r\nHardware ID: {7}\r\n", SystemFamily, SystemVersion, SystemArchitecture, ApplicationName, ApplicationVersion, DeviceManufacturer, DeviceModel, AppSpecificHardwareID ); } catch(Exception e) { System.Diagnostics.Debug.WriteLine("Exception: " + e.Message); result = "OS version: UNKNOWN\r\nFamily: UNKNOWN\r\nVersion: UNKNOWN\r\nArchitecture: UNKNOWN\r\nApplication Name: UNKNOWN\r\nApplication Version: UNKNOWN\r\nDevice Manufacturer: UNKNOWN\r\nDevice Model: UNKNOWN\r\nHardware ID: UNKNOWN\r\n"; } return result; } } }
{ "content_hash": "fdc8de7d46eba9f4015cfa3c67a7e41f", "timestamp": "", "source": "github", "line_count": 158, "max_line_length": 257, "avg_line_length": 42.08227848101266, "alnum_prop": 0.5760264701458866, "repo_name": "flecoqui/Windows10", "id": "94595df95b8c7230fa9aa081a7343bdf009890dc", "size": "6651", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Samples/UniversalMediaPlayer/cs/AudioVideoPlayer/Information/SystemInformation.cs", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
typedef const char ** readstat_iconv_inbuf_t; #else typedef char ** readstat_iconv_inbuf_t; #endif typedef struct readstat_charset_entry_s { int code; char name[32]; } readstat_charset_entry_t;
{ "content_hash": "f2f76beaef37c669245f0dc4cdccd662", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 45, "avg_line_length": 23.333333333333332, "alnum_prop": 0.6952380952380952, "repo_name": "ivarref/ReadStat", "id": "17b24d47d6cfa9986485d3e4c341f8ef95afb569", "size": "252", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/readstat_iconv.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "823273" }, { "name": "M4", "bytes": "1562" }, { "name": "Makefile", "bytes": "5842" }, { "name": "Ragel", "bytes": "19440" }, { "name": "Shell", "bytes": "36" } ], "symlink_target": "" }
docker stack deploy --compose-file dc-S1-cloud-slice-part.yml cloudstackS1
{ "content_hash": "9515b67fa516d2a053bc4b0182f2ab0e", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 75, "avg_line_length": 75, "alnum_prop": 0.8133333333333334, "repo_name": "SINCConcept/sanalytics", "id": "55299cccaa8357f7f300513d5d2cfa6a3ca51fb3", "size": "75", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "sampleapps/cloud-swarm-manager/deploy-S1-cloud-slice-part.sh", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "1033" }, { "name": "Java", "bytes": "162690" }, { "name": "Shell", "bytes": "10749" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "a4539f26e567b84380cb2346719a5e98", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "ce005a8bfc2cc942c3ba495e6b9ae2699bb45919", "size": "172", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Rosales/Rosaceae/Rubus/Rubus decorus/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
albburtsev.github.io ==================== Home page of Alexander Burtsev in Github
{ "content_hash": "bf6f7f4fbc012e99782d99a87dc6ca86", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 40, "avg_line_length": 21, "alnum_prop": 0.6190476190476191, "repo_name": "albburtsev/albburtsev.github.io", "id": "b741159edf5ddced8e9a8f40a23a78c413e99f21", "size": "84", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
// Copyright 2020 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/performance_manager/policies/background_tab_loading_policy.h" #include <map> #include <memory> #include <vector> #include "base/memory/raw_ptr.h" #include "base/threading/sequenced_task_runner_handle.h" #include "chrome/browser/performance_manager/mechanisms/page_loader.h" #include "components/performance_manager/graph/graph_impl.h" #include "components/performance_manager/graph/page_node_impl.h" #include "components/performance_manager/public/persistence/site_data/feature_usage.h" #include "components/performance_manager/public/persistence/site_data/site_data_reader.h" #include "components/performance_manager/test_support/graph_test_harness.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" namespace performance_manager { namespace policies { using PageNodeAndNotificationPermission = BackgroundTabLoadingPolicy::PageNodeAndNotificationPermission; namespace { // Mock version of a performance_manager::mechanism::PageLoader. class LenientMockPageLoader : public performance_manager::mechanism::PageLoader { public: LenientMockPageLoader() = default; ~LenientMockPageLoader() override = default; LenientMockPageLoader(const LenientMockPageLoader& other) = delete; LenientMockPageLoader& operator=(const LenientMockPageLoader&) = delete; MOCK_METHOD1(LoadPageNode, void(const PageNode* page_node)); }; using MockPageLoader = ::testing::StrictMock<LenientMockPageLoader>; class MockBackgroundTabLoadingPolicy : public BackgroundTabLoadingPolicy { public: void SetSiteDataReaderForPageNode(const PageNode* page_node, SiteDataReader* site_data_reader) { site_data_readers_[page_node] = site_data_reader; } private: SiteDataReader* GetSiteDataReader(const PageNode* page_node) const override { auto it = site_data_readers_.find(page_node); if (it == site_data_readers_.end()) return nullptr; return it->second; } std::map<const PageNode*, SiteDataReader*> site_data_readers_; }; class MockSiteDataReader : public SiteDataReader { public: MockSiteDataReader(bool updates_favicon_in_background, bool updates_title_in_background, bool uses_audio_in_background) : updates_favicon_in_background_(updates_favicon_in_background), updates_title_in_background_(updates_title_in_background), uses_audio_in_background_(uses_audio_in_background) {} SiteFeatureUsage UpdatesFaviconInBackground() const override { return updates_favicon_in_background_ ? SiteFeatureUsage::kSiteFeatureInUse : SiteFeatureUsage::kSiteFeatureNotInUse; } SiteFeatureUsage UpdatesTitleInBackground() const override { return updates_title_in_background_ ? SiteFeatureUsage::kSiteFeatureInUse : SiteFeatureUsage::kSiteFeatureNotInUse; } SiteFeatureUsage UsesAudioInBackground() const override { return uses_audio_in_background_ ? SiteFeatureUsage::kSiteFeatureInUse : SiteFeatureUsage::kSiteFeatureNotInUse; } bool DataLoaded() const override { return true; } void RegisterDataLoadedCallback(base::OnceClosure&& callback) override { base::SequencedTaskRunnerHandle::Get()->PostTask(FROM_HERE, std::move(callback)); } private: const bool updates_favicon_in_background_; const bool updates_title_in_background_; const bool uses_audio_in_background_; }; } // namespace class BackgroundTabLoadingPolicyTest : public GraphTestHarness { public: using Super = GraphTestHarness; BackgroundTabLoadingPolicyTest() = default; ~BackgroundTabLoadingPolicyTest() override = default; BackgroundTabLoadingPolicyTest(const BackgroundTabLoadingPolicyTest& other) = delete; BackgroundTabLoadingPolicyTest& operator=( const BackgroundTabLoadingPolicyTest&) = delete; void SetUp() override { Super::SetUp(); system_node_ = std::make_unique<TestNodeWrapper<SystemNodeImpl>>( TestNodeWrapper<SystemNodeImpl>::Create(graph())); // Create the policy. auto policy = std::make_unique<MockBackgroundTabLoadingPolicy>(); policy_ = policy.get(); graph()->PassToGraph(std::move(policy)); // Make the policy use a mock PageLoader. auto mock_loader = std::make_unique<MockPageLoader>(); mock_loader_ = mock_loader.get(); policy_->SetMockLoaderForTesting(std::move(mock_loader)); // Set a value explicitly for thresholds that depends on system information. policy_->SetMaxSimultaneousLoadsForTesting(4); policy_->SetFreeMemoryForTesting(150); } void TearDown() override { graph()->TakeFromGraph(policy_); system_node_->reset(); Super::TearDown(); } protected: MockBackgroundTabLoadingPolicy* policy() { return policy_; } MockPageLoader* loader() { return mock_loader_; } SystemNodeImpl* system_node() { return system_node_.get()->get(); } private: std::unique_ptr< performance_manager::TestNodeWrapper<performance_manager::SystemNodeImpl>> system_node_; raw_ptr<MockBackgroundTabLoadingPolicy> policy_; raw_ptr<MockPageLoader> mock_loader_; }; TEST_F(BackgroundTabLoadingPolicyTest, ScheduleLoadForRestoredTabsWithoutNotificationPermission) { std::vector< performance_manager::TestNodeWrapper<performance_manager::PageNodeImpl>> page_nodes; std::vector<PageNodeAndNotificationPermission> to_load; // Create vector of PageNode to restore. for (int i = 0; i < 4; i++) { page_nodes.push_back(CreateNode<performance_manager::PageNodeImpl>()); PageNodeAndNotificationPermission page_node_and_notification_permission( page_nodes.back().get()->GetWeakPtr(), false); to_load.push_back(page_node_and_notification_permission); EXPECT_CALL(*loader(), LoadPageNode(to_load.back().page_node.get())); // Mark the PageNode as a tab as this is a requirement to pass it to // ScheduleLoadForRestoredTabs(). page_nodes.back()->SetType(PageType::kTab); } policy()->ScheduleLoadForRestoredTabs(to_load); task_env().RunUntilIdle(); } TEST_F(BackgroundTabLoadingPolicyTest, ScheduleLoadForRestoredTabsWithNotificationPermission) { std::vector< performance_manager::TestNodeWrapper<performance_manager::PageNodeImpl>> page_nodes; std::vector<PageNodeAndNotificationPermission> to_load; // Create vector of PageNode to restore. for (int i = 0; i < 4; i++) { page_nodes.push_back(CreateNode<performance_manager::PageNodeImpl>()); PageNodeAndNotificationPermission page_node_and_notification_permission( page_nodes.back().get()->GetWeakPtr(), true); to_load.push_back(page_node_and_notification_permission); EXPECT_CALL(*loader(), LoadPageNode(to_load.back().page_node.get())); // Mark the PageNode as a tab as this is a requirement to pass it to // ScheduleLoadForRestoredTabs(). page_nodes.back()->SetType(PageType::kTab); } policy()->ScheduleLoadForRestoredTabs(to_load); task_env().RunUntilIdle(); } TEST_F(BackgroundTabLoadingPolicyTest, AllLoadingSlotsUsed) { // Create 4 PageNode to restore. std::vector< performance_manager::TestNodeWrapper<performance_manager::PageNodeImpl>> page_nodes; std::vector<PageNodeAndNotificationPermission> to_load; // Create vector of PageNode to restore. for (int i = 0; i < 4; i++) { page_nodes.push_back(CreateNode<performance_manager::PageNodeImpl>()); PageNodeAndNotificationPermission page_node_and_notification_permission( page_nodes.back().get()->GetWeakPtr(), false); to_load.push_back(page_node_and_notification_permission); // Mark the PageNode as a tab as this is a requirement to pass it to // ScheduleLoadForRestoredTabs(). page_nodes.back()->SetType(PageType::kTab); } PageNodeImpl* page_node_impl = page_nodes[0].get(); EXPECT_CALL(*loader(), LoadPageNode(to_load[0].page_node.get())); EXPECT_CALL(*loader(), LoadPageNode(to_load[1].page_node.get())); // Use 2 loading slots, which means only 2 of the PageNodes should immediately // be scheduled to load. policy()->SetMaxSimultaneousLoadsForTesting(2); policy()->ScheduleLoadForRestoredTabs(to_load); task_env().RunUntilIdle(); testing::Mock::VerifyAndClear(loader()); // Simulate load start of a PageNode that initiated load. page_node_impl->SetLoadingState(PageNode::LoadingState::kLoading); // The policy should allow one more PageNode to load after a PageNode finishes // loading. EXPECT_CALL(*loader(), LoadPageNode(to_load[2].page_node.get())); // Simulate load finish of a PageNode. page_node_impl->SetLoadingState(PageNode::LoadingState::kLoadedIdle); } // Regression test for crbug.com/1166745 TEST_F(BackgroundTabLoadingPolicyTest, LoadingStateLoadedBusy) { // Create 1 PageNode to load. performance_manager::TestNodeWrapper<performance_manager::PageNodeImpl> page_node(CreateNode<performance_manager::PageNodeImpl>()); PageNodeAndNotificationPermission page_node_and_notification_permission( page_node.get()->GetWeakPtr(), false); std::vector<PageNodeAndNotificationPermission> page_node_and_notification_permission_to_load_vector{ page_node_and_notification_permission}; // Mark the PageNode as a tab as this is a requirement to pass it to // ScheduleLoadForRestoredTabs(). page_node->SetType(PageType::kTab); EXPECT_CALL(*loader(), LoadPageNode(page_node.get())); policy()->ScheduleLoadForRestoredTabs( page_node_and_notification_permission_to_load_vector); task_env().RunUntilIdle(); testing::Mock::VerifyAndClear(loader()); // Transition to kLoading, to kLoadedBusy, and then back to kLoading. This // should not crash. page_node->SetLoadingState(PageNode::LoadingState::kLoading); page_node->SetLoadingState(PageNode::LoadingState::kLoadedBusy); page_node->SetLoadingState(PageNode::LoadingState::kLoading); // Simulate load finish. page_node->SetLoadingState(PageNode::LoadingState::kLoadedIdle); } TEST_F(BackgroundTabLoadingPolicyTest, ShouldLoad_MaxTabsToRestore) { // Create vector of PageNodes to restore. std::vector< performance_manager::TestNodeWrapper<performance_manager::PageNodeImpl>> page_nodes; std::vector<PageNode*> raw_page_nodes; for (uint32_t i = 0; i < policy()->kMaxTabsToLoad + 1; i++) { page_nodes.push_back(CreateNode<performance_manager::PageNodeImpl>()); raw_page_nodes.push_back(page_nodes.back().get()); } // Test the maximum number of tabs to load threshold. for (uint32_t i = 0; i < policy()->kMaxTabsToLoad; i++) { EXPECT_TRUE(policy()->ShouldLoad(raw_page_nodes[i])); policy()->tab_loads_started_++; } EXPECT_FALSE(policy()->ShouldLoad(raw_page_nodes[policy()->kMaxTabsToLoad])); } TEST_F(BackgroundTabLoadingPolicyTest, ShouldLoad_MinTabsToRestore) { // Create vector of PageNodes to restore. std::vector< performance_manager::TestNodeWrapper<performance_manager::PageNodeImpl>> page_nodes; std::vector<PageNode*> raw_page_nodes; for (uint32_t i = 0; i < policy()->kMinTabsToLoad + 1; i++) { page_nodes.push_back(CreateNode<performance_manager::PageNodeImpl>()); raw_page_nodes.push_back(page_nodes.back().get()); } // When free memory limit is reached. const size_t kFreeMemoryLimit = policy()->kDesiredAmountOfFreeMemoryMb - 1; policy()->SetFreeMemoryForTesting(kFreeMemoryLimit); // Test that the minimum number of tabs to load is respected. for (uint32_t i = 0; i < policy()->kMinTabsToLoad; i++) { EXPECT_TRUE(policy()->ShouldLoad(raw_page_nodes[i])); policy()->tab_loads_started_++; } EXPECT_FALSE(policy()->ShouldLoad(raw_page_nodes[policy()->kMinTabsToLoad])); } TEST_F(BackgroundTabLoadingPolicyTest, ShouldLoad_FreeMemory) { // Create a PageNode to restore. performance_manager::TestNodeWrapper<performance_manager::PageNodeImpl> page_node; PageNode* raw_page_node; page_node = CreateNode<performance_manager::PageNodeImpl>(); raw_page_node = page_node.get(); // Simulate that kMinTabsToLoad have loaded. policy()->tab_loads_started_ = policy()->kMinTabsToLoad; // Test the free memory constraint. const size_t kFreeMemoryLimit = policy()->kDesiredAmountOfFreeMemoryMb; policy()->SetFreeMemoryForTesting(kFreeMemoryLimit); EXPECT_TRUE(policy()->ShouldLoad(raw_page_node)); policy()->SetFreeMemoryForTesting(kFreeMemoryLimit - 1); EXPECT_FALSE(policy()->ShouldLoad(raw_page_node)); policy()->SetFreeMemoryForTesting(kFreeMemoryLimit + 1); EXPECT_TRUE(policy()->ShouldLoad(raw_page_node)); } TEST_F(BackgroundTabLoadingPolicyTest, ShouldLoad_OldTab) { // Create an old tab. performance_manager::TestNodeWrapper<performance_manager::PageNodeImpl> page_node; PageNode* raw_page_node; page_node = CreateNode<performance_manager::PageNodeImpl>( WebContentsProxy(), std::string(), GURL(), false, false, base::TimeTicks::Now() - (base::Seconds(1) + policy()->kMaxTimeSinceLastUseToLoad)); raw_page_node = page_node.get(); // Simulate that kMinTabsToLoad have loaded. policy()->tab_loads_started_ = policy()->kMinTabsToLoad; // Test the max time since last use threshold. EXPECT_FALSE(policy()->ShouldLoad(raw_page_node)); } TEST_F(BackgroundTabLoadingPolicyTest, ScoreAndScheduleTabLoad) { // Use 1 loading slot so only one PageNode loads at a time. policy()->SetMaxSimultaneousLoadsForTesting(1); MockSiteDataReader site_data_reader_favicon( /* updates_favicon_in_background=*/true, /* updates_title_in_background=*/false, /* uses_audio_in_background=*/false); MockSiteDataReader site_data_reader_title( /* updates_favicon_in_background=*/false, /* updates_title_in_background=*/true, /* uses_audio_in_background=*/false); MockSiteDataReader site_data_reader_audio( /* updates_favicon_in_background=*/false, /* updates_title_in_background=*/false, /* uses_audio_in_background=*/true); MockSiteDataReader site_data_reader_default( /* updates_favicon_in_background=*/false, /* updates_title_in_background=*/false, /* uses_audio_in_background=*/false); // Create PageNodes with decreasing last visibility time (oldest to newest). std::vector< performance_manager::TestNodeWrapper<performance_manager::PageNodeImpl>> page_nodes; std::vector<PageNodeAndNotificationPermission> to_load; // Add tabs to restore: // Old page_nodes.push_back(CreateNode<performance_manager::PageNodeImpl>( WebContentsProxy(), std::string(), GURL(), false, false, base::TimeTicks::Now() - base::Days(30))); policy()->SetSiteDataReaderForPageNode(page_nodes.back().get(), &site_data_reader_default); PageNodeAndNotificationPermission old(page_nodes.back().get()->GetWeakPtr(), false); to_load.push_back(old); // Recent page_nodes.push_back(CreateNode<performance_manager::PageNodeImpl>( WebContentsProxy(), std::string(), GURL(), false, false, base::TimeTicks::Now() - base::Seconds(1))); policy()->SetSiteDataReaderForPageNode(page_nodes.back().get(), &site_data_reader_default); PageNodeAndNotificationPermission recent( page_nodes.back().get()->GetWeakPtr(), false); to_load.push_back(recent); // Slightly older tabs which were observed updating their title or favicon or // playing audio in the background page_nodes.push_back(CreateNode<performance_manager::PageNodeImpl>( WebContentsProxy(), std::string(), GURL(), false, false, base::TimeTicks::Now() - base::Seconds(2))); policy()->SetSiteDataReaderForPageNode(page_nodes.back().get(), &site_data_reader_title); PageNodeAndNotificationPermission title(page_nodes.back().get()->GetWeakPtr(), false); to_load.push_back(title); page_nodes.push_back(CreateNode<performance_manager::PageNodeImpl>( WebContentsProxy(), std::string(), GURL(), false, false, base::TimeTicks::Now() - base::Seconds(3))); policy()->SetSiteDataReaderForPageNode(page_nodes.back().get(), &site_data_reader_favicon); PageNodeAndNotificationPermission favicon( page_nodes.back().get()->GetWeakPtr(), false); to_load.push_back(favicon); page_nodes.push_back(CreateNode<performance_manager::PageNodeImpl>( WebContentsProxy(), std::string(), GURL(), false, false, base::TimeTicks::Now() - base::Seconds(4))); policy()->SetSiteDataReaderForPageNode(page_nodes.back().get(), &site_data_reader_audio); PageNodeAndNotificationPermission audio(page_nodes.back().get()->GetWeakPtr(), false); to_load.push_back(audio); // Internal page page_nodes.push_back(CreateNode<performance_manager::PageNodeImpl>( WebContentsProxy(), std::string(), GURL("chrome://newtab"), false, false, base::TimeTicks::Now() - base::Seconds(1))); policy()->SetSiteDataReaderForPageNode(page_nodes.back().get(), &site_data_reader_default); PageNodeAndNotificationPermission internal( page_nodes.back().get()->GetWeakPtr(), false); to_load.push_back(internal); // Page with notification permission page_nodes.push_back(CreateNode<performance_manager::PageNodeImpl>( WebContentsProxy(), std::string(), GURL("chrome://newtab"), false, false, base::TimeTicks::Now() - base::Seconds(1))); policy()->SetSiteDataReaderForPageNode(page_nodes.back().get(), &site_data_reader_default); PageNodeAndNotificationPermission notification( page_nodes.back().get()->GetWeakPtr(), true); to_load.push_back(notification); for (auto& page_node : page_nodes) { // Mark the PageNode as a tab as this is a requirement to pass it to // ScheduleLoadForRestoredTabs(). page_node->SetType(PageType::kTab); } // Test that tabs are loaded in the expected order: const std::vector<PageNodeAndNotificationPermission> expected_load_order{ notification, title, favicon, recent, audio, old, internal}; // 1st tab starts loading when ScheduleLoadForRestoredTabs is invoked. EXPECT_CALL(*loader(), LoadPageNode(expected_load_order[0].page_node.get())); policy()->ScheduleLoadForRestoredTabs(to_load); task_env().RunUntilIdle(); testing::Mock::VerifyAndClear(loader()); // Other tabs start loading when the previous tab finishes loading. for (size_t i = 1; i < expected_load_order.size(); ++i) { PageNodeImpl::FromNode(expected_load_order[i - 1].page_node.get()) ->SetLoadingState(PageNode::LoadingState::kLoading); EXPECT_CALL(*loader(), LoadPageNode(expected_load_order[i].page_node.get())); PageNodeImpl::FromNode(expected_load_order[i - 1].page_node.get()) ->SetLoadingState(PageNode::LoadingState::kLoadedIdle); testing::Mock::VerifyAndClear(loader()); } } TEST_F(BackgroundTabLoadingPolicyTest, OnMemoryPressure) { // Multiple PageNodes are necessary to make sure that the policy // doesn't immediately kick off loading of all tabs. std::vector< performance_manager::TestNodeWrapper<performance_manager::PageNodeImpl>> page_nodes; std::vector<PageNodeAndNotificationPermission> to_load; for (uint32_t i = 0; i < 2; i++) { page_nodes.push_back(CreateNode<performance_manager::PageNodeImpl>()); PageNodeAndNotificationPermission page_node_and_permisssion( page_nodes.back().get()->GetWeakPtr(), false); to_load.push_back(page_node_and_permisssion); // Mark the PageNode as a tab as this is a requirement to pass it to // ScheduleLoadForRestoredTabs(). page_nodes.back()->SetType(PageType::kTab); } // Use 1 loading slot so only one PageNode loads at a time. policy()->SetMaxSimultaneousLoadsForTesting(1); // Test that the score produces the expected loading order EXPECT_CALL(*loader(), LoadPageNode(to_load[0].page_node.get())); policy()->ScheduleLoadForRestoredTabs(to_load); task_env().RunUntilIdle(); testing::Mock::VerifyAndClear(loader()); // Simulate memory pressure and expect the tab loader to disable loading. system_node()->OnMemoryPressureForTesting( base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_MODERATE); PageNodeImpl* page_node_impl = page_nodes[0].get(); // Simulate load start of a PageNode that initiated load. page_node_impl->SetLoadingState(PageNode::LoadingState::kLoading); // Simulate load finish of a PageNode and expect the policy to not start // another load. page_node_impl->SetLoadingState(PageNode::LoadingState::kLoadedIdle); } } // namespace policies } // namespace performance_manager
{ "content_hash": "e2b48f24e54e5af756287ab9dd3adead", "timestamp": "", "source": "github", "line_count": 533, "max_line_length": 89, "avg_line_length": 39.70168855534709, "alnum_prop": 0.7062048107367327, "repo_name": "nwjs/chromium.src", "id": "4e47fd81c03f1e87ce4255605d2058a89004aec5", "size": "21161", "binary": false, "copies": "1", "ref": "refs/heads/nw70", "path": "chrome/browser/performance_manager/policies/background_tab_loading_policy_unittest.cc", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
package com.amazonaws.services.secretsmanager.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.secretsmanager.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * PublicPolicyException JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class PublicPolicyExceptionUnmarshaller extends EnhancedJsonErrorUnmarshaller { private PublicPolicyExceptionUnmarshaller() { super(com.amazonaws.services.secretsmanager.model.PublicPolicyException.class, "PublicPolicyException"); } @Override public com.amazonaws.services.secretsmanager.model.PublicPolicyException unmarshallFromContext(JsonUnmarshallerContext context) throws Exception { com.amazonaws.services.secretsmanager.model.PublicPolicyException publicPolicyException = new com.amazonaws.services.secretsmanager.model.PublicPolicyException( null); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return null; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return publicPolicyException; } private static PublicPolicyExceptionUnmarshaller instance; public static PublicPolicyExceptionUnmarshaller getInstance() { if (instance == null) instance = new PublicPolicyExceptionUnmarshaller(); return instance; } }
{ "content_hash": "c3b1eeb48e4bd8d2c6514ec57ac158d7", "timestamp": "", "source": "github", "line_count": 63, "max_line_length": 168, "avg_line_length": 36.41269841269841, "alnum_prop": 0.6813426329555362, "repo_name": "aws/aws-sdk-java", "id": "225cedab80e7f4a335a01bdf30578de4fe6879a9", "size": "2874", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "aws-java-sdk-secretsmanager/src/main/java/com/amazonaws/services/secretsmanager/model/transform/PublicPolicyExceptionUnmarshaller.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
var assert = require('assert'); suite('Players', function() { test('in the server', function(done, server) { server.eval(function() { Players.insert({name: 'Totti', role: 'A', Squadra: 'Rome', Quota:'87'}); var docs = Players.find().fetch(); emit('docs', docs); }); server.once('docs', function(docs) { assert.equal(docs.length, 1); done(); }); }); test('using both client and the server', function(done, server, client) { server.eval(function() { Current.find().observe({ added: addedNewCurrentPlayer }); function addedNewCurrentPlayer(player) { emit('player', player); } }).once('player', function(player) { assert.equal(player.name, 'Totti'); done(); }); client.eval(function() { Current.insert({name: 'Totti'}); }); }); });
{ "content_hash": "ab331452a578905ecbf6e2d84df43c34", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 78, "avg_line_length": 23.22222222222222, "alnum_prop": 0.5825358851674641, "repo_name": "dfucci/FantasyFootballBidding", "id": "ecb76610fdb6221f5de4a91e83c73f2ab3aa6c61", "size": "836", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/players.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "31" }, { "name": "CoffeeScript", "bytes": "1292" }, { "name": "JavaScript", "bytes": "836" } ], "symlink_target": "" }
title: Apache Mesos - Release Guide layout: documentation --- # Release Guide This guide describes the process of doing an official release of Mesos. ## Prerequisites 1. Ensure that you have a GPG key or generate a new one, e.g., using `gpg --gen-key`. 2. Add your GPG public key to the Apache Mesos dist repository in the KEYS file. * Fetch the svn repository: $ svn co https://dist.apache.org/repos/dist/release/mesos * Append your public key using one of methods described in KEYS, e.g.: $ (gpg --list-sigs <your name> && gpg --armor --export <your name>) >> KEYS * Push the commit: $ svn ci 3. Submit your GPG public key to a keyserver, e.g., [MIT PGP Public Key Server](https://pgp.mit.edu). 4. Add your GPG fingerprint (`gpg --fingerprint <your name>`) to your [Apache account](https://id.apache.org/). 5. Create a Maven settings file (`~/.m2/settings.xml`) for the Apache servers where you must copy your encrypted Apache password which you can get from running `mvn --encrypt-password`. **NOTE:** You may need to first generate a [master password](http://maven.apache.org/guides/mini/guide-encryption.html). <settings> <servers> <server> <id>apache.snapshots.https</id> <username>APACHE USERNAME</username> <password>APACHE ENCRYPTED PASSWORD</password> </server> <server> <id>apache.releases.https</id> <username>APACHE USERNAME</username> <password>APACHE ENCRYPTED PASSWORD</password> </server> </servers> </settings> 6. Use `gpg-agent` to avoid typing your passphrase repeatedly: $ export GPG_TTY="$(tty)" && eval $(gpg-agent --daemon) ## Preparation 1. Go to [Apache JIRA](https://issues.apache.org/jira/browse/MESOS) and make sure that the `CHANGELOG` for the release version is up to date. **NOTE:** You should move all **Unresolved** tickets marked with `Fix Version` or `Target Version` as the release version to the next release version. **PROTIP:** Use a JIRA dashboard [(example)](https://issues.apache.org/jira/secure/Dashboard.jspa?selectPageId=12329720) to track the progress of targeted issues as the release date approaches. This JIRA filter may be useful (`<X.Y.Z>` is the release version): `project = MESOS AND "Target Version/s" = <X.Y.Z> AND (fixVersion != <X.Y.Z> OR fixVersion = EMPTY)` **PROTIP:** Use `bulk edit` option in JIRA to move the tickets and make sure to **uncheck** the option that emails everyone about the move to avoid spamming. 2. Checkout the correct branch for the release. For regular releases this is the "master" branch. For patch releases this would be the corresponding release branch (e.g., 1.0.x). 3. Update and commit the `CHANGELOG` for the release. For regular releases: * Make sure all new API changes, deprecations, major features, and features graduating from experimental to stable are called out at the top of the `CHANGELOG`. This JIRA query may be helpful in identifying some of these (`<X.Y.Z>` is the release version): `project = MESOS AND "Target Version/s" = <X.Y.Z> AND type = Epic` * Ensure that the "Unresolved Critical Issues" section is populated correctly. This JIRA query may be helpful: `project = Mesos AND type = bug AND status != Resolved AND priority IN (blocker, critical)` * Prepare a full list of experimental features. The easiest way to do this is to take the list from the previous minor release, remove features that have been declared stable, and those, that declared experimental in the current release. Do not forget to mention features transitioning from experimental to stable in this release at the top of the `CHANGELOG`. **NOTE:** You should use JIRA to generate the major portion of the `CHANGELOG` for you. Click on the release version in [JIRA](https://issues.apache.org/jira/browse/MESOS#selectedTab=com.atlassian.jira.plugin.system.project%3Aversions-panel) and click on the `Release Notes`. Make sure to configure the release notes in text format. **NOTE:** The JIRA Release Notes will list only tickets with `Fix Version` set to that version. You should check for any Resolved tickets that have `Target Version` set but not `Fix Version`. Also check for any Unresolved or `Duplicate`/`Invalid` tickets that incorrectly set the `Fix Version`. For patch releases update the `CHANGELOG` on master branch and then cherry pick onto the release branch. 4. Ensure version in `configure.ac` and `CMakeLists.txt` is correctly set for the release. Do not forget to remove "(WIP)" suffix from the release notes' title. 5. Run `make && support/generate-endpoint-help.py` and commit any resulting changes. 6. Update and commit `docs/configuration.md` to reflect the current state of the master, agent, and configure flags. If this is a patch release, update it on master branch and then cherry pick onto the release branch. 7. If this is a regular release, update and commit `docs/upgrades.md` with instructions about how to upgrade a live cluster from the previous release version to this release version. 8. If this is a regular release, please ensure that user documentation has been added for any new features. 9. Make sure that for any updates of the API, specifically the scheduler API, the public mesos protobuf definitions are part of both, `include/mesos` as well as `include/mesos/v1`. **NOTE:** This might actually demand code updates if any omissions were identified. ## Tagging the Release Candidate 1. Ensure that you can build and pass all the tests. $ sudo make -j<cores> distcheck 2. Run the benchmarks and compare with the previous release for any performance regressions: $ make bench -j<cores> GTEST_FILTER="*BENCHMARK*" 3. First tag the required SHA locally. $ git tag <X.Y.Z-rcR> **NOTE:** `X.Y.Z` is based on [semantic versioning](http://semver.org/) scheme. `R` is release candidate version that starts with 1. 4. Tag the release externally and deploy the corresponding JAR to the [Apache maven repository](https://repository.apache.org). It is recommended to use the `support/tag.sh` script to accomplish this. $ ./support/tag.sh X.Y.Z R **NOTE:** This script assumes that you have the requisite permissions to deploy the JAR. For instructions on how to set it up, please refer to `src/java/MESOS-MAVEN-README`. **NOTE:** gnu-sed (Linux) requires `-i''` instead of the `-i ''` (space-separated) that default OSX uses. You may need to modify your local copy of `tag.sh` for it to complete successfully. 5. If this is a regular release, create a new release branch (<major>.<minor>.x) from this tag. $ git checkout -b X.Y.x Now, update master branch to the *next* minor version in `configure.ac`: change `AC_INIT([mesos], [X.Y.Z]))`, as well as in `CMakeLists.txt`: change `set(MESOS_MAJOR_VERSION X)`, `set(MESOS_MINOR_VERSION Y)`, `set(MESOS_PATCH_VERSION Z)` and then commit. ## Voting the Release Candidate 1. Once a release candidate is deemed worthy to be officially released you should call a vote on the `dev@mesos.apache.org` (and optionally `user@mesos.apache.org`) mailing list. 2. It is recommended to use the `support/vote.sh` script to vote the release candidate. $ ./support/vote.sh X.Y.Z R 3. The release script also spits out an email template that you could use to send the vote email. **NOTE:** The `date -v+3d` command does not work on some platforms (e.g. Ubuntu), so you may need to fill in the vote end date manually. The vote should last for 3 business days instead of 3 calendar days anyway. Sometimes we allow a longer vote, to allow more time for integration testing. ## Preparing a New Release Candidate 1. If the vote does not pass (any -1s or showstopper bugs), track the issues as new JIRAs for the release. 2. When all known issues are resolved, update the `CHANGELOG` with the newly fixed JIRAs. 3. Once all patches are committed to master, cherry-pick them on to the corresponding release branch. This is the same process used for patch releases (e.g., 1.0.2) as well. $ git checkout X.Y.x $ git cherry-pick abcdefgh... 4. Now go back up to the "Tagging the Release Candidate" section and repeat. ## Releasing the Release Candidate 1. You should only release an official version if the vote passes with at least **3 +1 binding votes and no -1 votes**. For more information, please refer to [Apache release guidelines](http://www.apache.org/dev/release.html). 2. It is recommended to use `support/release.sh` script to release the candidate. $ ./support/release.sh X.Y.Z R 3. The release script also spits out an email template that you could use to notify the mailing lists about the result of the vote and the release. **NOTE:** Make sure you fill the email template with the names of binding and non-binding voters. 4. Update the version in `configure.ac` and `CMakeLists.txt` in the **release** branch to the **next** patch version. ## Updating the Website 1. After a successful release, add the information associated with the release in `site/data/releases.yml`. It is used to generate the release information on the website. 2. Update the [Getting Started](getting-started.md) guide to use the latest release link. 3. Check out the website from svn. $ svn co https://svn.apache.org/repos/asf/mesos/site mesos-site See our [website README](https://github.com/apache/mesos/blob/master/site/README.md/) for details on how to build the website. See the general [Apache project website guide](https://www.apache.org/dev/project-site.html) for details on how to publish the website. 4. Write a blog post announcing the new release and its features and major bug fixes. Include a link to the updated website. * This command may be helpful to gather the list of all contributors between two tags: `git log --pretty=format:%an <tagX>..<tagY> | sort | uniq | awk '{print}' ORS=', '` * Mention the blog post in `site/data/releases.yml`. ## Removing Old Releases from svn Per the guidelines [when to archive](http://www.apache.org/dev/release.html#when-to-archive), we should only keep the latest release in each version under development. 1. Checkout the mesos distribution folder: $ svn co https://dist.apache.org/repos/dist/release/mesos 2. Remove all minor versions that are no longer under development and commit the change. ## Releasing the Version on JIRA Find the released Mesos version [here](https://issues.apache.org/jira/plugins/servlet/project-config/MESOS/versions), and "release" it with the correct release date by clicking on "settings"&nbsp;&rarr;&nbsp;"Release". Also, make sure to add the names of the release managers in "Description" section. ## Updating External Tooling Upload the mesos.interface package to PyPi. 1. Create/use a PyPi account with access to the [mesos.interface submit form](https://pypi.python.org/pypi?name=mesos.interface&:action=submit_form). You may need to ask a current package owner to add you as an owner/maintainer. 2. Setup your [`~/.pypirc`](https://docs.python.org/2/distutils/packageindex.html#pypirc) with your PyPi username and password. 3. After a successful Mesos `make` (any architecture), cd to `build/src/python/interface`. 4. Run `python setup.py register` to register this package. 5. Run `python setup.py sdist bdist_egg upload` to upload the source distribution and egg for this package. Update the Mesos Homebrew package. 1. Update the [Homebrew formula for Mesos](https://github.com/Homebrew/homebrew-core/blob/master/Formula/mesos.rb) and test. 2. Submit a PR to the [Homebrew repo](https://github.com/Homebrew/homebrew-core). 3. Once accepted, verify that `brew install mesos` works.
{ "content_hash": "56cfd12decd9739bc7329ece24718e29", "timestamp": "", "source": "github", "line_count": 320, "max_line_length": 124, "avg_line_length": 38.00625, "alnum_prop": 0.7130406183193554, "repo_name": "zmalik/mesos", "id": "fa607287456dff5e078fe97690ef3728a6419e8a", "size": "12166", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "docs/release-guide.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "7957" }, { "name": "C++", "bytes": "11265925" }, { "name": "CMake", "bytes": "76593" }, { "name": "CSS", "bytes": "7241" }, { "name": "HTML", "bytes": "89549" }, { "name": "Java", "bytes": "142025" }, { "name": "JavaScript", "bytes": "1093580" }, { "name": "M4", "bytes": "176860" }, { "name": "Makefile", "bytes": "108500" }, { "name": "PowerShell", "bytes": "2547" }, { "name": "Python", "bytes": "258189" }, { "name": "Ruby", "bytes": "9055" }, { "name": "Shell", "bytes": "121115" } ], "symlink_target": "" }
using System; using System.Threading.Tasks; using Azure; using Azure.Core; using Azure.Core.Pipeline; namespace Azure.Analytics.Synapse.AccessControl { // Data plane generated client. The RoleAssignments service client. /// <summary> The RoleAssignments service client. </summary> public partial class RoleAssignmentsClient { private static readonly string[] AuthorizationScopes = new string[] { "https://dev.azuresynapse.net/.default" }; private readonly TokenCredential _tokenCredential; private readonly HttpPipeline _pipeline; private readonly Uri _endpoint; private readonly string _apiVersion; /// <summary> The ClientDiagnostics is used to provide tracing support for the client library. </summary> internal ClientDiagnostics ClientDiagnostics { get; } /// <summary> The HTTP pipeline for sending and receiving REST requests and responses. </summary> public virtual HttpPipeline Pipeline => _pipeline; /// <summary> Initializes a new instance of RoleAssignmentsClient for mocking. </summary> protected RoleAssignmentsClient() { } /// <summary> Initializes a new instance of RoleAssignmentsClient. </summary> /// <param name="endpoint"> The workspace development endpoint, for example https://myworkspace.dev.azuresynapse.net. </param> /// <param name="credential"> A credential used to authenticate to an Azure Service. </param> /// <exception cref="ArgumentNullException"> <paramref name="endpoint"/> or <paramref name="credential"/> is null. </exception> public RoleAssignmentsClient(Uri endpoint, TokenCredential credential) : this(endpoint, credential, new AccessControlClientOptions()) { } /// <summary> Initializes a new instance of RoleAssignmentsClient. </summary> /// <param name="endpoint"> The workspace development endpoint, for example https://myworkspace.dev.azuresynapse.net. </param> /// <param name="credential"> A credential used to authenticate to an Azure Service. </param> /// <param name="options"> The options for configuring the client. </param> /// <exception cref="ArgumentNullException"> <paramref name="endpoint"/> or <paramref name="credential"/> is null. </exception> public RoleAssignmentsClient(Uri endpoint, TokenCredential credential, AccessControlClientOptions options) { Argument.AssertNotNull(endpoint, nameof(endpoint)); Argument.AssertNotNull(credential, nameof(credential)); options ??= new AccessControlClientOptions(); ClientDiagnostics = new ClientDiagnostics(options, true); _tokenCredential = credential; _pipeline = HttpPipelineBuilder.Build(options, Array.Empty<HttpPipelinePolicy>(), new HttpPipelinePolicy[] { new BearerTokenAuthenticationPolicy(_tokenCredential, AuthorizationScopes) }, new ResponseClassifier()); _endpoint = endpoint; _apiVersion = options.Version; } /// <summary> Check if the given principalId has access to perform list of actions at a given scope. </summary> /// <param name="content"> The content to send as the body of the request. Details of the request body schema are in the Remarks section below. </param> /// <param name="contentType"> Body Parameter content-type. Allowed values: &quot;application/json&quot; | &quot;text/json&quot;. </param> /// <param name="context"> The request context, which can override default behaviors of the client pipeline on a per-call basis. </param> /// <exception cref="ArgumentNullException"> <paramref name="content"/> is null. </exception> /// <exception cref="RequestFailedException"> Service returned a non-success status code. </exception> /// <returns> The response returned from the service. Details of the response body schema are in the Remarks section below. </returns> /// <include file="Docs/RoleAssignmentsClient.xml" path="doc/members/member[@name='CheckPrincipalAccessAsync(RequestContent,ContentType,RequestContext)']/*" /> public virtual async Task<Response> CheckPrincipalAccessAsync(RequestContent content, ContentType contentType, RequestContext context = null) { Argument.AssertNotNull(content, nameof(content)); using var scope = ClientDiagnostics.CreateScope("RoleAssignmentsClient.CheckPrincipalAccess"); scope.Start(); try { using HttpMessage message = CreateCheckPrincipalAccessRequest(content, contentType, context); return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Check if the given principalId has access to perform list of actions at a given scope. </summary> /// <param name="content"> The content to send as the body of the request. Details of the request body schema are in the Remarks section below. </param> /// <param name="contentType"> Body Parameter content-type. Allowed values: &quot;application/json&quot; | &quot;text/json&quot;. </param> /// <param name="context"> The request context, which can override default behaviors of the client pipeline on a per-call basis. </param> /// <exception cref="ArgumentNullException"> <paramref name="content"/> is null. </exception> /// <exception cref="RequestFailedException"> Service returned a non-success status code. </exception> /// <returns> The response returned from the service. Details of the response body schema are in the Remarks section below. </returns> /// <include file="Docs/RoleAssignmentsClient.xml" path="doc/members/member[@name='CheckPrincipalAccess(RequestContent,ContentType,RequestContext)']/*" /> public virtual Response CheckPrincipalAccess(RequestContent content, ContentType contentType, RequestContext context = null) { Argument.AssertNotNull(content, nameof(content)); using var scope = ClientDiagnostics.CreateScope("RoleAssignmentsClient.CheckPrincipalAccess"); scope.Start(); try { using HttpMessage message = CreateCheckPrincipalAccessRequest(content, contentType, context); return _pipeline.ProcessMessage(message, context); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> List role assignments. </summary> /// <param name="roleId"> Synapse Built-In Role Id. </param> /// <param name="principalId"> Object ID of the AAD principal or security-group. </param> /// <param name="scope"> Scope of the Synapse Built-in Role. </param> /// <param name="continuationToken"> Continuation token. </param> /// <param name="context"> The request context, which can override default behaviors of the client pipeline on a per-call basis. </param> /// <exception cref="RequestFailedException"> Service returned a non-success status code. </exception> /// <returns> The response returned from the service. Details of the response body schema are in the Remarks section below. </returns> /// <include file="Docs/RoleAssignmentsClient.xml" path="doc/members/member[@name='GetRoleAssignmentsAsync(String,String,String,String,RequestContext)']/*" /> public virtual async Task<Response> GetRoleAssignmentsAsync(string roleId = null, string principalId = null, string scope = null, string continuationToken = null, RequestContext context = null) { using var scope0 = ClientDiagnostics.CreateScope("RoleAssignmentsClient.GetRoleAssignments"); scope0.Start(); try { using HttpMessage message = CreateGetRoleAssignmentsRequest(roleId, principalId, scope, continuationToken, context); return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } catch (Exception e) { scope0.Failed(e); throw; } } /// <summary> List role assignments. </summary> /// <param name="roleId"> Synapse Built-In Role Id. </param> /// <param name="principalId"> Object ID of the AAD principal or security-group. </param> /// <param name="scope"> Scope of the Synapse Built-in Role. </param> /// <param name="continuationToken"> Continuation token. </param> /// <param name="context"> The request context, which can override default behaviors of the client pipeline on a per-call basis. </param> /// <exception cref="RequestFailedException"> Service returned a non-success status code. </exception> /// <returns> The response returned from the service. Details of the response body schema are in the Remarks section below. </returns> /// <include file="Docs/RoleAssignmentsClient.xml" path="doc/members/member[@name='GetRoleAssignments(String,String,String,String,RequestContext)']/*" /> public virtual Response GetRoleAssignments(string roleId = null, string principalId = null, string scope = null, string continuationToken = null, RequestContext context = null) { using var scope0 = ClientDiagnostics.CreateScope("RoleAssignmentsClient.GetRoleAssignments"); scope0.Start(); try { using HttpMessage message = CreateGetRoleAssignmentsRequest(roleId, principalId, scope, continuationToken, context); return _pipeline.ProcessMessage(message, context); } catch (Exception e) { scope0.Failed(e); throw; } } /// <summary> Create role assignment. </summary> /// <param name="roleAssignmentId"> The ID of the role assignment. </param> /// <param name="content"> The content to send as the body of the request. Details of the request body schema are in the Remarks section below. </param> /// <param name="contentType"> Body Parameter content-type. Allowed values: &quot;application/json&quot; | &quot;text/json&quot;. </param> /// <param name="context"> The request context, which can override default behaviors of the client pipeline on a per-call basis. </param> /// <exception cref="ArgumentNullException"> <paramref name="roleAssignmentId"/> or <paramref name="content"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="roleAssignmentId"/> is an empty string, and was expected to be non-empty. </exception> /// <exception cref="RequestFailedException"> Service returned a non-success status code. </exception> /// <returns> The response returned from the service. Details of the response body schema are in the Remarks section below. </returns> /// <include file="Docs/RoleAssignmentsClient.xml" path="doc/members/member[@name='CreateRoleAssignmentAsync(String,RequestContent,ContentType,RequestContext)']/*" /> public virtual async Task<Response> CreateRoleAssignmentAsync(string roleAssignmentId, RequestContent content, ContentType contentType, RequestContext context = null) { Argument.AssertNotNullOrEmpty(roleAssignmentId, nameof(roleAssignmentId)); Argument.AssertNotNull(content, nameof(content)); using var scope = ClientDiagnostics.CreateScope("RoleAssignmentsClient.CreateRoleAssignment"); scope.Start(); try { using HttpMessage message = CreateCreateRoleAssignmentRequest(roleAssignmentId, content, contentType, context); return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Create role assignment. </summary> /// <param name="roleAssignmentId"> The ID of the role assignment. </param> /// <param name="content"> The content to send as the body of the request. Details of the request body schema are in the Remarks section below. </param> /// <param name="contentType"> Body Parameter content-type. Allowed values: &quot;application/json&quot; | &quot;text/json&quot;. </param> /// <param name="context"> The request context, which can override default behaviors of the client pipeline on a per-call basis. </param> /// <exception cref="ArgumentNullException"> <paramref name="roleAssignmentId"/> or <paramref name="content"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="roleAssignmentId"/> is an empty string, and was expected to be non-empty. </exception> /// <exception cref="RequestFailedException"> Service returned a non-success status code. </exception> /// <returns> The response returned from the service. Details of the response body schema are in the Remarks section below. </returns> /// <include file="Docs/RoleAssignmentsClient.xml" path="doc/members/member[@name='CreateRoleAssignment(String,RequestContent,ContentType,RequestContext)']/*" /> public virtual Response CreateRoleAssignment(string roleAssignmentId, RequestContent content, ContentType contentType, RequestContext context = null) { Argument.AssertNotNullOrEmpty(roleAssignmentId, nameof(roleAssignmentId)); Argument.AssertNotNull(content, nameof(content)); using var scope = ClientDiagnostics.CreateScope("RoleAssignmentsClient.CreateRoleAssignment"); scope.Start(); try { using HttpMessage message = CreateCreateRoleAssignmentRequest(roleAssignmentId, content, contentType, context); return _pipeline.ProcessMessage(message, context); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Get role assignment by role assignment Id. </summary> /// <param name="roleAssignmentId"> The ID of the role assignment. </param> /// <param name="context"> The request context, which can override default behaviors of the client pipeline on a per-call basis. </param> /// <exception cref="ArgumentNullException"> <paramref name="roleAssignmentId"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="roleAssignmentId"/> is an empty string, and was expected to be non-empty. </exception> /// <exception cref="RequestFailedException"> Service returned a non-success status code. </exception> /// <returns> The response returned from the service. Details of the response body schema are in the Remarks section below. </returns> /// <include file="Docs/RoleAssignmentsClient.xml" path="doc/members/member[@name='GetRoleAssignmentByIdAsync(String,RequestContext)']/*" /> public virtual async Task<Response> GetRoleAssignmentByIdAsync(string roleAssignmentId, RequestContext context = null) { Argument.AssertNotNullOrEmpty(roleAssignmentId, nameof(roleAssignmentId)); using var scope = ClientDiagnostics.CreateScope("RoleAssignmentsClient.GetRoleAssignmentById"); scope.Start(); try { using HttpMessage message = CreateGetRoleAssignmentByIdRequest(roleAssignmentId, context); return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Get role assignment by role assignment Id. </summary> /// <param name="roleAssignmentId"> The ID of the role assignment. </param> /// <param name="context"> The request context, which can override default behaviors of the client pipeline on a per-call basis. </param> /// <exception cref="ArgumentNullException"> <paramref name="roleAssignmentId"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="roleAssignmentId"/> is an empty string, and was expected to be non-empty. </exception> /// <exception cref="RequestFailedException"> Service returned a non-success status code. </exception> /// <returns> The response returned from the service. Details of the response body schema are in the Remarks section below. </returns> /// <include file="Docs/RoleAssignmentsClient.xml" path="doc/members/member[@name='GetRoleAssignmentById(String,RequestContext)']/*" /> public virtual Response GetRoleAssignmentById(string roleAssignmentId, RequestContext context = null) { Argument.AssertNotNullOrEmpty(roleAssignmentId, nameof(roleAssignmentId)); using var scope = ClientDiagnostics.CreateScope("RoleAssignmentsClient.GetRoleAssignmentById"); scope.Start(); try { using HttpMessage message = CreateGetRoleAssignmentByIdRequest(roleAssignmentId, context); return _pipeline.ProcessMessage(message, context); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Delete role assignment by role assignment Id. </summary> /// <param name="roleAssignmentId"> The ID of the role assignment. </param> /// <param name="scope"> Scope of the Synapse Built-in Role. </param> /// <param name="context"> The request context, which can override default behaviors of the client pipeline on a per-call basis. </param> /// <exception cref="ArgumentNullException"> <paramref name="roleAssignmentId"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="roleAssignmentId"/> is an empty string, and was expected to be non-empty. </exception> /// <exception cref="RequestFailedException"> Service returned a non-success status code. </exception> /// <returns> The response returned from the service. </returns> /// <include file="Docs/RoleAssignmentsClient.xml" path="doc/members/member[@name='DeleteRoleAssignmentByIdAsync(String,String,RequestContext)']/*" /> public virtual async Task<Response> DeleteRoleAssignmentByIdAsync(string roleAssignmentId, string scope = null, RequestContext context = null) { Argument.AssertNotNullOrEmpty(roleAssignmentId, nameof(roleAssignmentId)); using var scope0 = ClientDiagnostics.CreateScope("RoleAssignmentsClient.DeleteRoleAssignmentById"); scope0.Start(); try { using HttpMessage message = CreateDeleteRoleAssignmentByIdRequest(roleAssignmentId, scope, context); return await _pipeline.ProcessMessageAsync(message, context).ConfigureAwait(false); } catch (Exception e) { scope0.Failed(e); throw; } } /// <summary> Delete role assignment by role assignment Id. </summary> /// <param name="roleAssignmentId"> The ID of the role assignment. </param> /// <param name="scope"> Scope of the Synapse Built-in Role. </param> /// <param name="context"> The request context, which can override default behaviors of the client pipeline on a per-call basis. </param> /// <exception cref="ArgumentNullException"> <paramref name="roleAssignmentId"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="roleAssignmentId"/> is an empty string, and was expected to be non-empty. </exception> /// <exception cref="RequestFailedException"> Service returned a non-success status code. </exception> /// <returns> The response returned from the service. </returns> /// <include file="Docs/RoleAssignmentsClient.xml" path="doc/members/member[@name='DeleteRoleAssignmentById(String,String,RequestContext)']/*" /> public virtual Response DeleteRoleAssignmentById(string roleAssignmentId, string scope = null, RequestContext context = null) { Argument.AssertNotNullOrEmpty(roleAssignmentId, nameof(roleAssignmentId)); using var scope0 = ClientDiagnostics.CreateScope("RoleAssignmentsClient.DeleteRoleAssignmentById"); scope0.Start(); try { using HttpMessage message = CreateDeleteRoleAssignmentByIdRequest(roleAssignmentId, scope, context); return _pipeline.ProcessMessage(message, context); } catch (Exception e) { scope0.Failed(e); throw; } } internal HttpMessage CreateCheckPrincipalAccessRequest(RequestContent content, ContentType contentType, RequestContext context) { var message = _pipeline.CreateMessage(context, ResponseClassifier200); var request = message.Request; request.Method = RequestMethod.Post; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendPath("/checkAccessSynapseRbac", false); uri.AppendQuery("api-version", _apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json, text/json"); request.Headers.Add("Content-Type", contentType.ToString()); request.Content = content; return message; } internal HttpMessage CreateGetRoleAssignmentsRequest(string roleId, string principalId, string scope, string continuationToken, RequestContext context) { var message = _pipeline.CreateMessage(context, ResponseClassifier200); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendPath("/roleAssignments", false); uri.AppendQuery("api-version", _apiVersion, true); if (roleId != null) { uri.AppendQuery("roleId", roleId, true); } if (principalId != null) { uri.AppendQuery("principalId", principalId, true); } if (scope != null) { uri.AppendQuery("scope", scope, true); } request.Uri = uri; if (continuationToken != null) { request.Headers.Add("x-ms-continuation", continuationToken); } request.Headers.Add("Accept", "application/json, text/json"); return message; } internal HttpMessage CreateCreateRoleAssignmentRequest(string roleAssignmentId, RequestContent content, ContentType contentType, RequestContext context) { var message = _pipeline.CreateMessage(context, ResponseClassifier200); var request = message.Request; request.Method = RequestMethod.Put; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendPath("/roleAssignments/", false); uri.AppendPath(roleAssignmentId, true); uri.AppendQuery("api-version", _apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json, text/json"); request.Headers.Add("Content-Type", contentType.ToString()); request.Content = content; return message; } internal HttpMessage CreateGetRoleAssignmentByIdRequest(string roleAssignmentId, RequestContext context) { var message = _pipeline.CreateMessage(context, ResponseClassifier200); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendPath("/roleAssignments/", false); uri.AppendPath(roleAssignmentId, true); uri.AppendQuery("api-version", _apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json, text/json"); return message; } internal HttpMessage CreateDeleteRoleAssignmentByIdRequest(string roleAssignmentId, string scope, RequestContext context) { var message = _pipeline.CreateMessage(context, ResponseClassifier200204); var request = message.Request; request.Method = RequestMethod.Delete; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendPath("/roleAssignments/", false); uri.AppendPath(roleAssignmentId, true); uri.AppendQuery("api-version", _apiVersion, true); if (scope != null) { uri.AppendQuery("scope", scope, true); } request.Uri = uri; request.Headers.Add("Accept", "application/json, text/json"); return message; } private static ResponseClassifier _responseClassifier200; private static ResponseClassifier ResponseClassifier200 => _responseClassifier200 ??= new StatusCodeClassifier(stackalloc ushort[] { 200 }); private static ResponseClassifier _responseClassifier200204; private static ResponseClassifier ResponseClassifier200204 => _responseClassifier200204 ??= new StatusCodeClassifier(stackalloc ushort[] { 200, 204 }); } }
{ "content_hash": "4620e3faf3d6565c66b9f1157c2e3749", "timestamp": "", "source": "github", "line_count": 424, "max_line_length": 225, "avg_line_length": 61.341981132075475, "alnum_prop": 0.6555807605059787, "repo_name": "Azure/azure-sdk-for-net", "id": "0bbcc395e0aaccd40ea33318e858cae369f5c0b3", "size": "26147", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "sdk/synapse/Azure.Analytics.Synapse.AccessControl/src/Generated/RoleAssignmentsClient.cs", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
struct MatchMakingKeyValuePair_t { MatchMakingKeyValuePair_t() { m_szKey[0] = m_szValue[0] = 0; } MatchMakingKeyValuePair_t( const char *pchKey, const char *pchValue ) { strncpy( m_szKey, pchKey, sizeof(m_szKey) ); // this is a public header, use basic c library string funcs only! strncpy( m_szValue, pchValue, sizeof(m_szValue) ); } char m_szKey[ 256 ]; char m_szValue[ 256 ]; }; enum EMatchMakingServerResponse { eServerResponded = 0, eServerFailedToRespond, eNoServersListedOnMasterServer // for the Internet query type, returned in response callback if no servers of this type match }; enum EMatchMakingType { eInternetServer = 0, eLANServer, eFriendsServer, eFavoritesServer, eHistoryServer, eSpectatorServer, eInvalidServer }; // servernetadr_t is all the addressing info the serverbrowser needs to know about a game server, // namely: its IP, its connection port, and its query port. class servernetadr_t { public: void Init( unsigned int ip, uint16 usQueryPort, uint16 usConnectionPort ); #ifdef NETADR_H void Init( const netadr_t &ipAndQueryPort, uint16 usConnectionPort ); netadr_t& GetIPAndQueryPort(); #endif // Access the query port. uint16 GetQueryPort() const; void SetQueryPort( uint16 usPort ); // Access the connection port. uint16 GetConnectionPort() const; void SetConnectionPort( uint16 usPort ); // Access the IP uint32 GetIP() const; void SetIP( uint32 ); // This gets the 'a.b.c.d:port' string with the connection port (instead of the query port). const char *GetConnectionAddressString() const; const char *GetQueryAddressString() const; // Comparison operators and functions. bool operator<(const servernetadr_t &netadr) const; void operator=( const servernetadr_t &that ) { m_usConnectionPort = that.m_usConnectionPort; m_usQueryPort = that.m_usQueryPort; m_unIP = that.m_unIP; } private: const char *ToString( uint32 unIP, uint16 usPort ) const; uint16 m_usConnectionPort; // (in HOST byte order) uint16 m_usQueryPort; uint32 m_unIP; }; inline void servernetadr_t::Init( unsigned int ip, uint16 usQueryPort, uint16 usConnectionPort ) { m_unIP = ip; m_usQueryPort = usQueryPort; m_usConnectionPort = usConnectionPort; } #ifdef NETADR_H inline void servernetadr_t::Init( const netadr_t &ipAndQueryPort, uint16 usConnectionPort ) { Init( ipAndQueryPort.GetIP(), ipAndQueryPort.GetPort(), usConnectionPort ); } inline netadr_t& servernetadr_t::GetIPAndQueryPort() { static netadr_t netAdr; netAdr.SetIP( m_unIP ); netAdr.SetPort( m_usQueryPort ); return netAdr; } #endif inline uint16 servernetadr_t::GetQueryPort() const { return m_usQueryPort; } inline void servernetadr_t::SetQueryPort( uint16 usPort ) { m_usQueryPort = usPort; } inline uint16 servernetadr_t::GetConnectionPort() const { return m_usConnectionPort; } inline void servernetadr_t::SetConnectionPort( uint16 usPort ) { m_usConnectionPort = usPort; } inline uint32 servernetadr_t::GetIP() const { return m_unIP; } inline void servernetadr_t::SetIP( uint32 unIP ) { m_unIP = unIP; } inline const char *servernetadr_t::ToString( uint32 unIP, uint16 usPort ) const { static char s[4][64]; static int nBuf = 0; unsigned char *ipByte = (unsigned char *)&unIP; Q_snprintf (s[nBuf], sizeof( s[nBuf] ), "%u.%u.%u.%u:%i", (int)(ipByte[3]), (int)(ipByte[2]), (int)(ipByte[1]), (int)(ipByte[0]), usPort ); const char *pchRet = s[nBuf]; ++nBuf; nBuf %= ( (sizeof(s)/sizeof(s[0])) ); return pchRet; } inline const char* servernetadr_t::GetConnectionAddressString() const { return ToString( m_unIP, m_usConnectionPort ); } inline const char* servernetadr_t::GetQueryAddressString() const { return ToString( m_unIP, m_usQueryPort ); } inline bool servernetadr_t::operator<(const servernetadr_t &netadr) const { return ( m_unIP < netadr.m_unIP ) || ( m_unIP == netadr.m_unIP && m_usQueryPort < netadr.m_usQueryPort ); } //----------------------------------------------------------------------------- // Purpose: Data describing a single server //----------------------------------------------------------------------------- class gameserveritem_t { public: gameserveritem_t(); const char* GetName() const; void SetName( const char *pName ); public: servernetadr_t m_NetAdr; // IP/Query Port/Connection Port for this server int m_nPing; // current ping time in milliseconds bool m_bHadSuccessfulResponse; // server has responded successfully in the past bool m_bDoNotRefresh; // server is marked as not responding and should no longer be refreshed char m_szGameDir[32]; // current game directory char m_szMap[32]; // current map char m_szGameDescription[64]; // game description int m_nAppID; // Steam App ID of this server int m_nPlayers; // current number of players on the server int m_nMaxPlayers; // Maximum players that can join this server int m_nBotPlayers; // Number of bots (i.e simulated players) on this server bool m_bPassword; // true if this server needs a password to join bool m_bSecure; // Is this server protected by VAC uint32 m_ulTimeLastPlayed; // time (in unix time) when this server was last played on (for favorite/history servers) int m_nServerVersion; // server version as reported to Steam private: char m_szServerName[64]; // Game server name // For data added after SteamMatchMaking001 add it here public: char m_szGameTags[128]; // the tags this server exposes }; inline gameserveritem_t::gameserveritem_t() { m_szGameDir[0] = m_szMap[0] = m_szGameDescription[0] = m_szServerName[0] = 0; m_bHadSuccessfulResponse = m_bDoNotRefresh = m_bPassword = m_bSecure = false; m_nPing = m_nAppID = m_nPlayers = m_nMaxPlayers = m_nBotPlayers = m_ulTimeLastPlayed = m_nServerVersion = 0; m_szGameTags[0] = 0; } inline const char* gameserveritem_t::GetName() const { // Use the IP address as the name if nothing is set yet. if ( m_szServerName[0] == 0 ) return m_NetAdr.GetConnectionAddressString(); else return m_szServerName; } inline void gameserveritem_t::SetName( const char *pName ) { strncpy( m_szServerName, pName, sizeof( m_szServerName ) ); } #endif // MATCHMAKINGTYPES_H
{ "content_hash": "7f4e16cdefb9296ee1951292ea6ba63e", "timestamp": "", "source": "github", "line_count": 218, "max_line_length": 140, "avg_line_length": 28.28440366972477, "alnum_prop": 0.707914369120986, "repo_name": "scen/ionlib", "id": "7054339562651f73dbcc06f91473ce136f299c9e", "size": "6494", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/sdk/hl2_ob/public/steam/matchmakingtypes.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "9790968" }, { "name": "C++", "bytes": "149439667" }, { "name": "D", "bytes": "81870968" }, { "name": "Objective-C", "bytes": "376824" }, { "name": "Perl", "bytes": "77795" }, { "name": "Python", "bytes": "2596" }, { "name": "Shell", "bytes": "2289" }, { "name": "Squirrel", "bytes": "4289" } ], "symlink_target": "" }
"""This is the docstring for the convertSkewToTemp.py module.""" import numpy as np def convertSkewToTemp(xcoord, press, skew): """ convertSkewToTemp(xcoord, press, skew) Determines temperature from knowledge of a plotting coordinate system and corresponding plot skew. Parameters - - - - - - xcoord : int X coordinate in temperature plotting coordinates. press : float Pressure (hPa). skew : int Skew of a given coordinate system. Returns - - - - Temp : float Converted temperature in degC. Examples - - - - - >>> convertSkewToTemp(300, 8.e4, 30) 638.6934574096806 """ Temp = xcoord + skew * np.log(press); return Temp def _test(): import doctest doctest.testmod() if __name__ == "__main__": _test()
{ "content_hash": "2964cc33e84ec5a332deb82a95935476", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 66, "avg_line_length": 20.975, "alnum_prop": 0.6042908224076281, "repo_name": "phaustin/pythermo", "id": "5dc110004c9648103fde8ac136f5ff4fb1294a19", "size": "839", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "code/thermlib/convertSkewToTemp.py", "mode": "33188", "license": "mit", "language": [ { "name": "Matlab", "bytes": "1207" }, { "name": "Python", "bytes": "117656" } ], "symlink_target": "" }
wget https://github.com/kgabis/parson/raw/master/parson.c -O external/parson.c wget https://github.com/kgabis/parson/raw/master/parson.h -O external/parson.h
{ "content_hash": "26ba451ceeb60fd5c7e9068c699dca46", "timestamp": "", "source": "github", "line_count": 2, "max_line_length": 78, "avg_line_length": 79, "alnum_prop": 0.7848101265822784, "repo_name": "iatanasov/sbar", "id": "486888542b1784865404be4667b71a6149d56e95", "size": "169", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "update.sh", "mode": "33261", "license": "mit", "language": [ { "name": "C", "bytes": "12601" }, { "name": "Makefile", "bytes": "543" }, { "name": "Shell", "bytes": "169" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>hammer-tactics: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.11.1 / hammer-tactics - 1.1.1+8.9</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> hammer-tactics <small> 1.1.1+8.9 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-04-13 21:39:51 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-04-13 21:39:51 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils coq 8.11.1 Formal proof management system num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic ocaml 4.11.2 The OCaml compiler (virtual package) ocaml-base-compiler 4.11.2 Official release 4.11.2 ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.3 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;palmskog@gmail.com&quot; homepage: &quot;https://github.com/lukaszcz/coqhammer&quot; dev-repo: &quot;git+https://github.com/lukaszcz/coqhammer.git&quot; bug-reports: &quot;https://github.com/lukaszcz/coqhammer/issues&quot; license: &quot;LGPL-2.1-only&quot; synopsis: &quot;Reconstruction tactics for the hammer for Coq&quot; description: &quot;&quot;&quot; Collection of tactics that are used by the hammer for Coq to reconstruct proofs found by automated theorem provers. When the hammer has been successfully applied to a project, only this package needs to be installed; the hammer plugin is not required. &quot;&quot;&quot; build: [make &quot;-j%{jobs}%&quot; {ocaml:version &gt;= &quot;4.06&quot;} &quot;tactics&quot;] install: [make &quot;install-tactics&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.8&quot; &amp; &lt; &quot;8.10~&quot;} ] conflicts: [ &quot;coq-hammer&quot; {!= version} ] tags: [ &quot;keyword:automation&quot; &quot;keyword:hammer&quot; &quot;keyword:tactics&quot; &quot;logpath:Hammer&quot; &quot;date:2019-06-12&quot; ] authors: [ &quot;Lukasz Czajka &lt;lukaszcz@mimuw.edu.pl&gt;&quot; &quot;Cezary Kaliszyk &lt;cezary.kaliszyk@uibk.ac.at&gt;&quot; &quot;Burak Ekici &lt;burak.ekici@uibk.ac.at&gt;&quot; ] url { src: &quot;https://github.com/lukaszcz/coqhammer/archive/refs/tags/v1.1.1-coq8.9.tar.gz&quot; checksum: &quot;sha256=4f167c5fa8cc8a26c81a0efb6f7c360acf4f15151d3d53f8d0c8ab654c8dd814&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-hammer-tactics.1.1.1+8.9 coq.8.11.1</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.11.1). The following dependencies couldn&#39;t be met: - coq-hammer-tactics -&gt; coq &lt; 8.10~ -&gt; ocaml &lt; 4.10 base of this switch (use `--unlock-base&#39; to force) No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-hammer-tactics.1.1.1+8.9</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{ "content_hash": "8a8d44c4211b06b1fa6fee16fcfc3346", "timestamp": "", "source": "github", "line_count": 176, "max_line_length": 159, "avg_line_length": 40.40340909090909, "alnum_prop": 0.549852341442835, "repo_name": "coq-bench/coq-bench.github.io", "id": "874609093ff27ee4d32914952c927be2e79214c3", "size": "7136", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.11.2-2.0.7/released/8.11.1/hammer-tactics/1.1.1+8.9.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
package org.spongepowered.api.event.entity.living; import org.spongepowered.api.entity.living.Living; import org.spongepowered.api.event.entity.EntityInteractEvent; /** * Called when a {@link Living} interacts with the world. */ public interface LivingInteractEvent extends LivingEvent, EntityInteractEvent { }
{ "content_hash": "2708f333d4ca974c5b32aec41a1d8ece", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 79, "avg_line_length": 26.416666666666668, "alnum_prop": 0.8012618296529969, "repo_name": "frogocomics/SpongeAPI", "id": "082457002a8dfdab9c59229225fc0f10637e92f6", "size": "1567", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "src/main/java/org/spongepowered/api/event/entity/living/LivingInteractEvent.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "3168083" }, { "name": "Shell", "bytes": "77" } ], "symlink_target": "" }
layout: page title: Atkinson 40th Anniversary date: 2016-05-24 author: Julia Compton tags: weekly links, java status: published summary: Cras tincidunt consequat purus quis cursus. banner: images/banner/leisure-03.jpg booking: startDate: 11/09/2017 endDate: 11/10/2017 ctyhocn: ALBSPHX groupCode: A4A published: true --- Nulla in dui a lectus aliquet tempus ut ac elit. Curabitur eleifend, metus in imperdiet porttitor, mi metus sodales quam, vitae tempus ante mauris in nibh. Sed tristique a dui et convallis. Donec fermentum congue tortor eget tincidunt. Donec ultrices neque id lobortis sollicitudin. Cras dapibus eget massa vel fringilla. Curabitur feugiat metus ut nisl accumsan, at molestie nunc cursus. Nulla ut dolor dapibus, imperdiet elit et, pulvinar orci. Ut id turpis non massa convallis mollis. Vestibulum vitae pharetra magna. Sed non justo vel augue fermentum varius ut eu libero. Ut tellus nibh, faucibus in lacus vel, sollicitudin ultricies dolor. Duis eros turpis, luctus ac odio nec, rutrum sagittis sem. * Donec sagittis odio vel aliquam blandit * Aliquam auctor augue eget ex vulputate convallis. Vivamus non fringilla sapien, a porta turpis. Etiam eget tellus sagittis eros tincidunt aliquet in suscipit odio. Pellentesque elementum accumsan purus nec vehicula. In pellentesque, urna vitae ultricies euismod, enim urna sodales justo, ut porta quam lectus a mauris. Vivamus sollicitudin facilisis sagittis. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Nam scelerisque tortor ligula, et finibus mauris dapibus at. Praesent consequat venenatis nibh, sagittis varius urna rhoncus in. Etiam eget egestas purus. Aenean non finibus risus, luctus suscipit lectus. Etiam euismod, nibh id egestas iaculis, velit quam bibendum elit, a congue nulla dolor et lorem. Sed in convallis turpis, in finibus massa. Fusce elementum volutpat ultricies. Morbi vitae pellentesque ipsum, vitae ultricies nisl. Nulla facilisi. Fusce ut aliquam nisl. Aenean auctor quam ipsum, in ultrices nisi consectetur faucibus. Integer orci turpis, tristique in erat non, ultricies elementum urna. Donec a ex ac nibh condimentum vehicula.
{ "content_hash": "8195a386fef4d8d849be41153e3988e2", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 703, "avg_line_length": 98.95454545454545, "alnum_prop": 0.8102893890675241, "repo_name": "KlishGroup/prose-pogs", "id": "160b1c53218f67d29622b46778050e382fc68d01", "size": "2181", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "pogs/A/ALBSPHX/A4A/index.md", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
package com.soundcloud.api; import org.apache.http.HttpHost; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpUriRequest; import java.io.IOException; import java.net.URI; /** * Interface with SoundCloud, using OAuth2. * * This is the interface, for the implementation see ApiWrapper. * @see ApiWrapper */ public interface CloudAPI { // OAuth2 parameters String GRANT_TYPE = "grant_type"; String CLIENT_ID = "client_id"; String CLIENT_SECRET = "client_secret"; String USERNAME = "username"; String REDIRECT_URI = "redirect_uri"; String CODE = "code"; String RESPONSE_TYPE = "response_type"; String SCOPE = "scope"; String DISPLAY = "display"; String STATE = "state"; // standard oauth2 grant types String PASSWORD = "password"; String AUTHORIZATION_CODE = "authorization_code"; String REFRESH_TOKEN = "refresh_token"; String CLIENT_CREDENTIALS = "client_credentials"; // custom String OAUTH1_TOKEN_GRANT_TYPE = "oauth1_token"; // soundcloud String FACEBOOK_GRANT_TYPE = "urn:soundcloud:oauth2:grant-type:facebook&access_token="; // oauth2 extension String GOOGLE_PLUS_GRANT_TYPE = "urn:soundcloud:oauth2:grant-type:google_plus&access_token="; // other constants String REALM = "SoundCloud"; String OAUTH_SCHEME = "oauth"; String VERSION = "1.3.1"; String USER_AGENT = "SoundCloud Java Wrapper ("+VERSION+")"; String POPUP = "popup"; /** * Request a token using <a href="http://tools.ietf.org/html/draft-ietf-oauth-v2-10#section-4.1.2"> * Resource Owner Password Credentials</a>. * * @param username SoundCloud username * @param password SoundCloud password * @param scopes the desired scope(s), or empty for default scope * @return a valid token * @throws com.soundcloud.api.CloudAPI.InvalidTokenException * invalid token * @throws IOException In case of network/server errors */ Token login(String username, String password, String... scopes) throws IOException; /** * Request a token using <a href="http://tools.ietf.org/html/draft-ietf-oauth-v2-10#section-4.1.1"> * Authorization Code</a>, requesting a default scope. * * @param code the authorization code * @param scopes the desired scope(s), or empty for default scope * @return a valid token * @throws com.soundcloud.api.CloudAPI.InvalidTokenException invalid token * @throws IOException In case of network/server errors */ Token authorizationCode(String code, String... scopes) throws IOException; /** * Request a "signup" token using <a href="http://tools.ietf.org/html/draft-ietf-oauth-v2-15#section-4.4"> * Client Credentials</a>. * * Note that this token is <b>not</b> set as the current token in the wrapper - it should only be used * for one request (typically the signup / user creation request). * Also note that not all apps are allowed to request this token type (the wrapper throws * InvalidTokenException in this case). * * @param scopes the desired scope(s), or empty for default scope * @return a valid token * @throws IOException IO/Error * @throws com.soundcloud.api.CloudAPI.InvalidTokenException if requested scope is not available */ Token clientCredentials(String... scopes) throws IOException; /** * Request a token using an <a href="http://tools.ietf.org/html/draft-ietf-oauth-v2-22#section-4.5"> * extension grant type</a>. * @param grantType * @param scopes * @return * @throws IOException */ Token extensionGrantType(String grantType, String... scopes) throws IOException; /** * Tries to refresh the currently used access token with the refresh token. * If successful the API wrapper will have the new token set already. * @return a valid token * @throws IOException in case of network problems * @throws com.soundcloud.api.CloudAPI.InvalidTokenException invalid token * @throws IllegalStateException if no refresh token present */ Token refreshToken() throws IOException; /** * This method should be called when the token was found to be invalid. * Also replaces the current token, if there is one available. * @return an alternative token, or null if none available * (which indicates that a refresh could be tried) */ Token invalidateToken(); /** * @param request resource to HEAD * @return the HTTP response * @throws IOException IO/Error */ HttpResponse head(Request request) throws IOException; /** * @param request resource to GET * @return the HTTP response * @throws IOException IO/Error */ HttpResponse get(Request request) throws IOException; /** * @param request resource to POST * @return the HTTP response * @throws IOException IO/Error */ HttpResponse post(Request request) throws IOException; /** * @param request resource to PUT * @return the HTTP response * @throws IOException IO/Error */ HttpResponse put(Request request) throws IOException; /** * @param request resource to DELETE * @return the HTTP response * @throws IOException IO/Error */ HttpResponse delete(Request request) throws IOException; /** * @return the used httpclient */ HttpClient getHttpClient(); /** * Generic execute method, with added workarounds for various HTTPClient bugs. * * @param target the target host (can be null) * @param request the request * @return the HTTP response * @throws IOException network errors * @throws BrokenHttpClientException in case of HTTPClient framework bugs */ HttpResponse safeExecute(HttpHost target, HttpUriRequest request) throws IOException; /** * Resolve the given SoundCloud URI * * @param uri SoundCloud model URI, e.g. http://soundcloud.com/bob * @return the id * @throws IOException network errors * @throws ResolverException if object could not be resolved */ long resolve(String uri) throws IOException; /** * Resolve the given SoundCloud stream URI * * @param uri SoundCloud stream URI, e.g. https://api.soundcloud.com/tracks/25272620/stream * @param skipLogging skip logging the play of this track (client needs * {@link com.soundcloud.api.Token#SCOPE_PLAYCOUNT}) * @return the resolved stream * @throws IOException network errors * @throws com.soundcloud.api.CloudAPI.ResolverException resolver error (invalid status etc) */ Stream resolveStreamUrl(String uri, boolean skipLogging) throws IOException; /** @return the current token */ Token getToken(); /** @param token the token to be used */ void setToken(Token token); /** * Registers a listener. The listener will be informed when an access token was found * to be invalid, and when the token had to be refreshed. * @param listener token listener */ void setTokenListener(TokenListener listener); /** * Request login via authorization code * After login, control will go to the redirect URI (wrapper specific), with * one of the following query parameters appended: * <ul> * <li><code>code</code> in case of success, this will contain the code used for the * <code>authorizationCode</code> call to obtain the access token. * <li><code>error</code> in case of failure, this contains an error code (most likely * <code>access_denied</code>). * </ul> * @param options auth endpoint to use (leave out for default), requested scope (leave out for default), display ('popup' for mobile optimized screen) and state. * @return the URI to open in a browser/WebView etc. * @see CloudAPI#authorizationCode(String, String...) */ URI authorizationCodeUrl(String... options); /** * Changes the default content type sent in the "Accept" header. * If you don't set this it defaults to "application/json". * * @param contentType the request mime type. */ void setDefaultContentType(String contentType); void setDefaultAcceptEncoding(String encoding); /** * Interested in changes to the current token. */ interface TokenListener { /** * Called when token was found to be invalid * @param token the invalid token * @return a cached token if available, or null */ Token onTokenInvalid(Token token); /** * Called when the token got successfully refreshed * @param token the refreshed token */ void onTokenRefreshed(Token token); } /** * Thrown when token is not valid. */ class InvalidTokenException extends IOException { private static final long serialVersionUID = 1954919760451539868L; /** * @param code the HTTP error code * @param status the HTTP status, or other error message */ public InvalidTokenException(int code, String status) { super("HTTP error:" + code + " (" + status + ")"); } } /** * Thrown if resolving the audio stream of a SoundCloud sound fails. */ class ResolverException extends ApiResponseException { public ResolverException(String s, HttpResponse resp) { super(resp, s); } public ResolverException(Throwable throwable, HttpResponse response) { super(throwable, response); } } /** * Thrown if the service API responds in error. The HTTP status code can be obtained via {@link #getStatusCode()}. */ class ApiResponseException extends IOException { private static final long serialVersionUID = -2990651725862868387L; public final HttpResponse response; public ApiResponseException(HttpResponse resp, String error) { super(resp.getStatusLine().getStatusCode() + ": [" + resp.getStatusLine().getReasonPhrase() + "] " + (error != null ? error : "")); this.response = resp; } public ApiResponseException(Throwable throwable, HttpResponse response) { super(throwable == null ? null : throwable.toString()); initCause(throwable); this.response = response; } public int getStatusCode() { return response.getStatusLine().getStatusCode(); } @Override public String getMessage() { return super.getMessage()+" "+(response != null ? response.getStatusLine() : ""); } } class BrokenHttpClientException extends IOException { private static final long serialVersionUID = -4764332412926419313L; BrokenHttpClientException(Throwable throwable) { super(throwable == null ? null : throwable.toString()); initCause(throwable); } } }
{ "content_hash": "27b020a38b1310d9a11f17afccf067d8", "timestamp": "", "source": "github", "line_count": 317, "max_line_length": 166, "avg_line_length": 35.791798107255524, "alnum_prop": 0.6464833421470122, "repo_name": "guffyWave/java-api-wrapper", "id": "dd42e3ec97d2c703480148a8f4f5e7a08ca4f709", "size": "11346", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "src/main/java/com/soundcloud/api/CloudAPI.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "204196" }, { "name": "Shell", "bytes": "707" } ], "symlink_target": "" }
-- Shared part /*--------------------------------------------------------------------------- Sound crash glitch ---------------------------------------------------------------------------*/ local entity = FindMetaTable("Entity") local EmitSound = entity.EmitSound function entity:EmitSound(sound, ...) if string.find(sound, "??", 0, true) then return end return EmitSound(self, sound, ...) end function DarkRP.getAvailableVehicles() local vehicles = list.Get("Vehicles") for k, v in pairs(list.Get("SCarsList") or {}) do vehicles[v.PrintName] = { Name = v.PrintName, Class = v.ClassName, Model = v.CarModel } end return vehicles end local osdate = os.date if system.IsWindows() then local replace = function(txt) if txt == "%%" then return txt end -- Edge case, %% is allowed return "" end function os.date(format, time) if format then format = string.gsub(format, "%%[^aAbBcdHIjmMpSUwWxXyYz]", replace) end return osdate(format, time) end end -- Clientside part if CLIENT then /*--------------------------------------------------------------------------- Generic InitPostEntity workarounds ---------------------------------------------------------------------------*/ hook.Add("InitPostEntity", "DarkRP_Workarounds", function() if hook.GetTable().HUDPaint then hook.Remove("HUDPaint","drawHudVital") end -- Removes the white flashes when the server lags and the server has flashbang. Workaround because it's been there for fucking years end) local camstart3D = cam.Start3D local camend3D = cam.End3D local cam3DStarted = 0 function cam.Start3D(a,b,c,d,e,f,g,h,i,j) cam3DStarted = cam3DStarted + 1 return camstart3D(a,b,c,d,e,f,g,h,i,j) end -- cam.End3D should not crash a player when 3D hasn't been started function cam.End3D() if not cam3DStarted then return end cam3DStarted = cam3DStarted - 1 return camend3D() end return end /*--------------------------------------------------------------------------- SetPos crash ---------------------------------------------------------------------------*/ local oldSetPos = entity.SetPos function entity:SetPos(vec) vec.x = math.Clamp(vec.x, -99999997952, 99999997952) vec.y = math.Clamp(vec.y, -99999997952, 99999997952) vec.z = math.Clamp(vec.z, -99999997952, 99999997952) return oldSetPos(self, vec) end /*--------------------------------------------------------------------------- Generic InitPostEntity workarounds ---------------------------------------------------------------------------*/ hook.Add("InitPostEntity", "DarkRP_Workarounds", function() local commands = concommand.GetTable() if commands["durgz_witty_sayings"] then game.ConsoleCommand("durgz_witty_sayings 0\n") -- Deals with the cigarettes exploit. I'm fucking tired of them. I hate having to fix other people's mods, but this mod maker is retarded and refuses to update his mod. end -- Remove ULX /me command. (the /me command is the only thing this hook does) hook.Remove("PlayerSay", "ULXMeCheck") -- why can people even save multiplayer games? -- Lag exploit if SERVER and not game.SinglePlayer() then concommand.Remove("gm_save") end end) /*--------------------------------------------------------------------------- Anti map spawn kill (like in rp_downtown_v4c) this is the only way I could find. ---------------------------------------------------------------------------*/ hook.Add("PlayerSpawn", "AntiMapKill", function(ply) timer.Simple(0, function() if IsValid(ply) and not ply:Alive() then ply:Spawn() ply:AddDeaths(-1) end end) end) /*--------------------------------------------------------------------------- Wire field generator exploit ---------------------------------------------------------------------------*/ hook.Add("OnEntityCreated", "DRP_WireFieldGenerator", function(ent) timer.Simple(0, function() if IsValid(ent) and ent:GetClass() == "gmod_wire_field_device" then local TriggerInput = ent.TriggerInput function ent:TriggerInput(iname, value) if value ~= nil and iname == "Distance" then value=math.Min(value, 400); end TriggerInput(self, iname, value) end end end) end) /*--------------------------------------------------------------------------- Door tool is shitty Let's fix that huge class exploit ---------------------------------------------------------------------------*/ hook.Add("InitPostEntity", "FixDoorTool", function() local oldFunc = makedoor if oldFunc then function makedoor(ply,trace,ang,model,open,close,autoclose,closetime,class,hardware, ...) if class ~= "prop_dynamic" and class ~= "prop_door_rotating" then return end oldFunc(ply,trace,ang,model,open,close,autoclose,closetime,class,hardware, ...) end end end) /*--------------------------------------------------------------------------- Anti crash exploit ---------------------------------------------------------------------------*/ hook.Add("PropBreak", "drp_AntiExploit", function(attacker, ent) if IsValid(ent) and ent:GetPhysicsObject():IsValid() then constraint.RemoveAll(ent) end end) local allowedDoors = { ["prop_dynamic"] = true, ["prop_door_rotating"] = true, [""] = true } hook.Add("CanTool", "DoorExploit", function(ply, trace, tool) if not IsValid(ply:GetActiveWeapon()) or not ply:GetActiveWeapon().GetToolObject or not ply:GetActiveWeapon():GetToolObject() then return end local tool = ply:GetActiveWeapon():GetToolObject() if not allowedDoors[string.lower(tool:GetClientInfo("door_class") or "")] then return false end end) /*--------------------------------------------------------------------------- ply:UniqueID calculates the CRC of "gm_"..ply:SteamID().."_gm" That calculation is slow ---------------------------------------------------------------------------*/ local plyMeta = FindMetaTable("Player") local oldUID = plyMeta.UniqueID function plyMeta:UniqueID() self.UIDCache = self.UIDCache or oldUID(self) return self.UIDCache end
{ "content_hash": "56e61688529243fc06f231091896ca83", "timestamp": "", "source": "github", "line_count": 178, "max_line_length": 217, "avg_line_length": 33.42134831460674, "alnum_prop": 0.5579088922507984, "repo_name": "cardentity/DarkRP", "id": "b98db05dac0887b42b4eaa6381af890208597f1e", "size": "5949", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "gamemode/modules/workarounds/sh_workarounds.lua", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
import json import os import shutil import urlparse from django.conf import settings from django.core.cache import cache from django.utils.http import http_date from django.test.utils import override_settings import pytest from cache_nuggets.lib import Message from mock import patch from pyquery import PyQuery as pq from olympia import amo from olympia.amo.tests import TestCase, version_factory from olympia.amo.urlresolvers import reverse from olympia.addons.models import Addon from olympia.files.helpers import DiffHelper, FileViewer from olympia.files.models import File from olympia.users.models import UserProfile dictionary = 'src/olympia/files/fixtures/files/dictionary-test.xpi' unicode_filenames = 'src/olympia/files/fixtures/files/unicode-filenames.xpi' not_binary = 'install.js' binary = 'dictionaries/ar.dic' class FilesBase(object): def login_as_admin(self): assert self.client.login(email='admin@mozilla.com') def login_as_editor(self): assert self.client.login(email='editor@mozilla.com') def setUp(self): super(FilesBase, self).setUp() self.addon = Addon.objects.get(pk=3615) self.dev = self.addon.authors.all()[0] self.regular = UserProfile.objects.get(pk=999) self.version = self.addon.versions.latest() self.file = self.version.all_files[0] p = [amo.PLATFORM_LINUX.id, amo.PLATFORM_WIN.id, amo.PLATFORM_MAC.id] self.file.update(platform=p[0]) self.files = [self.file, File.objects.create(version=self.version, platform=p[1], hash='abc123', filename='dictionary-test.xpi'), File.objects.create(version=self.version, platform=p[2], hash='abc123', filename='dictionary-test.xpi')] self.login_as_editor() for file_obj in self.files: src = os.path.join(settings.ROOT, dictionary) try: os.makedirs(os.path.dirname(file_obj.file_path)) except OSError: pass shutil.copyfile(src, file_obj.file_path) self.file_viewer = FileViewer(self.file) def tearDown(self): self.file_viewer.cleanup() super(FilesBase, self).tearDown() def files_redirect(self, file): return reverse('files.redirect', args=[self.file.pk, file]) def files_serve(self, file): return reverse('files.serve', args=[self.file.pk, file]) def test_view_access_anon(self): self.client.logout() self.check_urls(403) def test_view_access_anon_view_source(self): self.addon.update(view_source=True) self.file_viewer.extract() self.client.logout() self.check_urls(200) def test_view_access_editor(self): self.file_viewer.extract() self.check_urls(200) def test_view_access_editor_view_source(self): self.addon.update(view_source=True) self.file_viewer.extract() self.check_urls(200) def test_view_access_developer(self): self.client.logout() assert self.client.login(email=self.dev.email) self.file_viewer.extract() self.check_urls(200) def test_view_access_reviewed(self): self.addon.update(view_source=True) self.file_viewer.extract() self.client.logout() for status in amo.UNREVIEWED_FILE_STATUSES: self.addon.update(status=status) self.check_urls(403) for status in amo.REVIEWED_STATUSES: self.addon.update(status=status) self.check_urls(200) def test_view_access_developer_view_source(self): self.client.logout() assert self.client.login(email=self.dev.email) self.addon.update(view_source=True) self.file_viewer.extract() self.check_urls(200) def test_view_access_another_developer(self): self.client.logout() assert self.client.login(email=self.regular.email) self.file_viewer.extract() self.check_urls(403) def test_view_access_another_developer_view_source(self): self.client.logout() assert self.client.login(email=self.regular.email) self.addon.update(view_source=True) self.file_viewer.extract() self.check_urls(200) def test_poll_extracted(self): self.file_viewer.extract() res = self.client.get(self.poll_url()) assert res.status_code == 200 assert json.loads(res.content)['status'] def test_poll_not_extracted(self): res = self.client.get(self.poll_url()) assert res.status_code == 200 assert not json.loads(res.content)['status'] def test_poll_extracted_anon(self): self.client.logout() res = self.client.get(self.poll_url()) assert res.status_code == 403 def test_content_headers(self): self.file_viewer.extract() res = self.client.get(self.file_url('install.js')) assert 'etag' in res._headers assert 'last-modified' in res._headers def test_content_headers_etag(self): self.file_viewer.extract() self.file_viewer.select('install.js') obj = getattr(self.file_viewer, 'left', self.file_viewer) etag = obj.selected.get('md5') res = self.client.get(self.file_url('install.js'), HTTP_IF_NONE_MATCH=etag) assert res.status_code == 304 def test_content_headers_if_modified(self): self.file_viewer.extract() self.file_viewer.select('install.js') obj = getattr(self.file_viewer, 'left', self.file_viewer) date = http_date(obj.selected.get('modified')) res = self.client.get(self.file_url('install.js'), HTTP_IF_MODIFIED_SINCE=date) assert res.status_code == 304 def test_file_header(self): self.file_viewer.extract() res = self.client.get(self.file_url(not_binary)) url = res.context['file_link']['url'] assert url == reverse('editors.review', args=[self.addon.slug]) def test_file_header_anon(self): self.client.logout() self.file_viewer.extract() self.addon.update(view_source=True) res = self.client.get(self.file_url(not_binary)) url = res.context['file_link']['url'] assert url == reverse('addons.detail', args=[self.addon.pk]) def test_content_no_file(self): self.file_viewer.extract() res = self.client.get(self.file_url()) doc = pq(res.content) assert len(doc('#content')) == 0 def test_files(self): self.file_viewer.extract() res = self.client.get(self.file_url()) assert res.status_code == 200 assert 'files' in res.context def test_files_anon(self): self.client.logout() res = self.client.get(self.file_url()) assert res.status_code == 403 def test_files_file(self): self.file_viewer.extract() res = self.client.get(self.file_url(not_binary)) assert res.status_code == 200 assert 'selected' in res.context def test_files_back_link(self): self.file_viewer.extract() res = self.client.get(self.file_url(not_binary)) doc = pq(res.content) assert doc('#commands td')[-1].text_content() == 'Back to review' def test_files_back_link_anon(self): self.file_viewer.extract() self.client.logout() self.addon.update(view_source=True) res = self.client.get(self.file_url(not_binary)) assert res.status_code == 200 doc = pq(res.content) assert doc('#commands td')[-1].text_content() == 'Back to add-on' def test_diff_redirect(self): ids = self.files[0].id, self.files[1].id res = self.client.post(self.file_url(), {'left': ids[0], 'right': ids[1]}) self.assert3xx(res, reverse('files.compare', args=ids)) def test_browse_redirect(self): ids = self.files[0].id, res = self.client.post(self.file_url(), {'left': ids[0]}) self.assert3xx(res, reverse('files.list', args=ids)) def test_browse_404(self): res = self.client.get('/files/browse/file/dont/exist.png', follow=True) assert res.status_code == 404 def test_invalid_redirect(self): res = self.client.post(self.file_url(), {}) self.assert3xx(res, self.file_url()) def test_file_chooser(self): res = self.client.get(self.file_url()) doc = pq(res.content) left = doc('#id_left') assert len(left) == 1 ver = left('optgroup') assert len(ver) == 1 assert ver.attr('label') == self.version.version files = ver('option') assert len(files) == 2 def test_file_chooser_coalescing(self): res = self.client.get(self.file_url()) doc = pq(res.content) unreviewed_file = doc('#id_left > optgroup > option.status-unreviewed') public_file = doc('#id_left > optgroup > option.status-public') assert public_file.text() == str(self.files[0].get_platform_display()) assert unreviewed_file.text() == ( '%s, %s' % (self.files[1].get_platform_display(), self.files[2].get_platform_display())) assert public_file.attr('value') == str(self.files[0].id) assert unreviewed_file.attr('value') == str(self.files[1].id) def test_file_chooser_disabled_coalescing(self): self.files[1].update(status=amo.STATUS_DISABLED) res = self.client.get(self.file_url()) doc = pq(res.content) disabled_file = doc('#id_left > optgroup > option.status-disabled') assert disabled_file.attr('value') == str(self.files[2].id) def test_files_for_unlisted_addon_returns_404(self): """Files browsing isn't allowed for unlisted addons.""" self.make_addon_unlisted(self.addon) assert self.client.get(self.file_url()).status_code == 404 def test_files_for_unlisted_addon_with_admin(self): """Files browsing is allowed for unlisted addons if you're admin.""" self.login_as_admin() self.make_addon_unlisted(self.addon) assert self.client.get(self.file_url()).status_code == 200 def test_all_versions_shown_for_admin(self): self.login_as_admin() listed_ver = version_factory( addon=self.addon, channel=amo.RELEASE_CHANNEL_LISTED, version='4.0', created=self.days_ago(1)) unlisted_ver = version_factory( addon=self.addon, channel=amo.RELEASE_CHANNEL_UNLISTED, version='5.0') assert self.addon.versions.count() == 3 res = self.client.get(self.file_url()) doc = pq(res.content) left_select = doc('#id_left') assert left_select('optgroup').attr('label') == self.version.version file_options = left_select('option.status-public') assert len(file_options) == 3, left_select.html() # Check the files in the list are the two we added and the default. assert file_options.eq(0).attr('value') == str( unlisted_ver.all_files[0].pk) assert file_options.eq(1).attr('value') == str( listed_ver.all_files[0].pk) assert file_options.eq(2).attr('value') == str(self.file.pk) # Check there are prefixes on the labels for the channels assert file_options.eq(0).text().endswith('[Self]') assert file_options.eq(1).text().endswith('[AMO]') assert file_options.eq(2).text().endswith('[AMO]') def test_channel_prefix_not_shown_when_no_mixed_channels(self): self.login_as_admin() version_factory(addon=self.addon, channel=amo.RELEASE_CHANNEL_LISTED) assert self.addon.versions.count() == 2 res = self.client.get(self.file_url()) doc = pq(res.content) left_select = doc('#id_left') assert left_select('optgroup').attr('label') == self.version.version # Check there are NO prefixes on the labels for the channels file_options = left_select('option.status-public') assert not file_options.eq(0).text().endswith('[Self]') assert not file_options.eq(1).text().endswith('[AMO]') assert not file_options.eq(2).text().endswith('[AMO]') def test_only_listed_versions_shown_for_editor(self): listed_ver = version_factory( addon=self.addon, channel=amo.RELEASE_CHANNEL_LISTED, version='4.0') version_factory( addon=self.addon, channel=amo.RELEASE_CHANNEL_UNLISTED, version='5.0') assert self.addon.versions.count() == 3 res = self.client.get(self.file_url()) doc = pq(res.content) left_select = doc('#id_left') assert left_select('optgroup').attr('label') == self.version.version # Check the files in the list are just the listed, and the default. file_options = left_select('option.status-public') assert len(file_options) == 2, left_select.html() assert file_options.eq(0).attr('value') == str( listed_ver.all_files[0].pk) assert file_options.eq(1).attr('value') == str(self.file.pk) # Check there are NO prefixes on the labels for the channels assert not file_options.eq(0).text().endswith('[AMO]') assert not file_options.eq(1).text().endswith('[AMO]') class TestFileViewer(FilesBase, TestCase): fixtures = ['base/addon_3615', 'base/users'] def poll_url(self): return reverse('files.poll', args=[self.file.pk]) def file_url(self, file=None): args = [self.file.pk] if file: args.extend(['file', file]) return reverse('files.list', args=args) def check_urls(self, status): for url in [self.poll_url(), self.file_url()]: assert self.client.get(url).status_code == status def add_file(self, name, contents): dest = os.path.join(self.file_viewer.dest, name) open(dest, 'w').write(contents) def test_files_xss(self): self.file_viewer.extract() self.add_file('<script>alert("foo")', '') res = self.client.get(self.file_url()) doc = pq(res.content) # Note: this is text, not a DOM element, so escaped correctly. assert '<script>alert("' in doc('#files li a').text() def test_content_file(self): self.file_viewer.extract() res = self.client.get(self.file_url('install.js')) doc = pq(res.content) assert len(doc('#content')) == 1 def test_content_no_file(self): self.file_viewer.extract() res = self.client.get(self.file_url()) doc = pq(res.content) assert len(doc('#content')) == 1 assert res.context['key'] == 'install.rdf' def test_content_xss(self): self.file_viewer.extract() for name in ['file.txt', 'file.html', 'file.htm']: # If you are adding files, you need to clear out the memcache # file listing. cache.clear() self.add_file(name, '<script>alert("foo")</script>') res = self.client.get(self.file_url(name)) doc = pq(res.content) # Note: this is text, not a DOM element, so escaped correctly. assert doc('#content').attr('data-content').startswith('<script') def test_binary(self): self.file_viewer.extract() self.add_file('file.php', '<script>alert("foo")</script>') res = self.client.get(self.file_url('file.php')) assert res.status_code == 200 assert self.file_viewer.get_files()['file.php']['md5'] in res.content def test_tree_no_file(self): self.file_viewer.extract() res = self.client.get(self.file_url('doesnotexist.js')) assert res.status_code == 404 def test_directory(self): self.file_viewer.extract() res = self.client.get(self.file_url('doesnotexist.js')) assert res.status_code == 404 def test_unicode(self): self.file_viewer.src = unicode_filenames self.file_viewer.extract() res = self.client.get(self.file_url(u'\u1109\u1161\u11a9')) assert res.status_code == 200 @override_settings(TMP_PATH=unicode(settings.TMP_PATH)) def test_unicode_fails_with_wrong_configured_basepath(self): file_viewer = FileViewer(self.file) file_viewer.src = unicode_filenames with pytest.raises(UnicodeDecodeError): file_viewer.extract() def test_serve_no_token(self): self.file_viewer.extract() res = self.client.get(self.files_serve(binary)) assert res.status_code == 403 def test_serve_fake_token(self): self.file_viewer.extract() res = self.client.get(self.files_serve(binary) + '?token=aasd') assert res.status_code == 403 def test_serve_bad_token(self): self.file_viewer.extract() res = self.client.get(self.files_serve(binary) + '?token=a asd') assert res.status_code == 403 def test_serve_get_token(self): self.file_viewer.extract() res = self.client.get(self.files_redirect(binary)) assert res.status_code == 302 url = res['Location'] assert urlparse.urlparse(url).query.startswith('token=') def test_memcache_goes_bye_bye(self): self.file_viewer.extract() res = self.client.get(self.files_redirect(binary)) url = res['Location'] res = self.client.get(url) assert res.status_code == 200 cache.clear() res = self.client.get(url) assert res.status_code == 403 def test_bounce(self): self.file_viewer.extract() res = self.client.get(self.files_redirect(binary), follow=True) assert res.status_code == 200 assert res[settings.XSENDFILE_HEADER] == ( self.file_viewer.get_files().get(binary)['full']) @patch.object(settings, 'FILE_VIEWER_SIZE_LIMIT', 5) def test_file_size(self): self.file_viewer.extract() res = self.client.get(self.file_url(not_binary)) doc = pq(res.content) assert doc('.error').text().startswith('File size is') def test_poll_failed(self): msg = Message('file-viewer:%s' % self.file_viewer) msg.save('I like cheese.') res = self.client.get(self.poll_url()) assert res.status_code == 200 data = json.loads(res.content) assert not data['status'] assert data['msg'] == ['I like cheese.'] def test_file_chooser_selection(self): res = self.client.get(self.file_url()) doc = pq(res.content) assert doc('#id_left option[selected]').attr('value') == ( str(self.files[0].id)) assert len(doc('#id_right option[value][selected]')) == 0 def test_file_chooser_non_ascii_platform(self): PLATFORM_NAME = u'所有移动平台' f = self.files[0] with patch.object(File, 'get_platform_display', lambda self: PLATFORM_NAME): assert f.get_platform_display() == PLATFORM_NAME res = self.client.get(self.file_url()) doc = pq(res.content.decode('utf-8')) assert doc('#id_left option[value="%d"]' % f.id).text() == ( PLATFORM_NAME) def test_content_file_size_uses_binary_prefix(self): self.file_viewer.extract() response = self.client.get(self.file_url('dictionaries/license.txt')) assert '17.6 KiB' in response.content class TestDiffViewer(FilesBase, TestCase): fixtures = ['base/addon_3615', 'base/users'] def setUp(self): super(TestDiffViewer, self).setUp() self.file_viewer = DiffHelper(self.files[0], self.files[1]) def poll_url(self): return reverse('files.compare.poll', args=[self.files[0].pk, self.files[1].pk]) def add_file(self, file_obj, name, contents): dest = os.path.join(file_obj.dest, name) open(dest, 'w').write(contents) def file_url(self, file=None): args = [self.files[0].pk, self.files[1].pk] if file: args.extend(['file', file]) return reverse('files.compare', args=args) def check_urls(self, status): for url in [self.poll_url(), self.file_url()]: assert self.client.get(url).status_code == status def test_tree_no_file(self): self.file_viewer.extract() res = self.client.get(self.file_url('doesnotexist.js')) assert res.status_code == 404 def test_content_file(self): self.file_viewer.extract() res = self.client.get(self.file_url(not_binary)) doc = pq(res.content) assert len(doc('#content')) == 0 assert len(doc('#diff[data-left][data-right]')) == 1 def test_binary_serve_links(self): self.file_viewer.extract() res = self.client.get(self.file_url(binary)) doc = pq(res.content) node = doc('#content-wrapper a') assert len(node) == 2 assert node[0].text.startswith('Download ar.dic') def test_view_both_present(self): self.file_viewer.extract() res = self.client.get(self.file_url(not_binary)) doc = pq(res.content) assert len(doc('#content')) == 0 assert len(doc('#diff[data-left][data-right]')) == 1 assert len(doc('#content-wrapper p')) == 2 def test_view_one_missing(self): self.file_viewer.extract() os.remove(os.path.join(self.file_viewer.right.dest, 'install.js')) res = self.client.get(self.file_url(not_binary)) doc = pq(res.content) assert len(doc('#content')) == 0 assert len(doc('#diff[data-left][data-right]')) == 1 assert len(doc('#content-wrapper p')) == 1 def test_view_left_binary(self): self.file_viewer.extract() filename = os.path.join(self.file_viewer.left.dest, 'install.js') open(filename, 'w').write('MZ') res = self.client.get(self.file_url(not_binary)) assert 'This file is not viewable online' in res.content def test_view_right_binary(self): self.file_viewer.extract() filename = os.path.join(self.file_viewer.right.dest, 'install.js') open(filename, 'w').write('MZ') assert not self.file_viewer.is_diffable() res = self.client.get(self.file_url(not_binary)) assert 'This file is not viewable online' in res.content def test_different_tree(self): self.file_viewer.extract() os.remove(os.path.join(self.file_viewer.left.dest, not_binary)) res = self.client.get(self.file_url(not_binary)) doc = pq(res.content) assert doc('h4:last').text() == 'Deleted files:' assert len(doc('ul.root')) == 2 def test_file_chooser_selection(self): res = self.client.get(self.file_url()) doc = pq(res.content) assert doc('#id_left option[selected]').attr('value') == ( str(self.files[0].id)) assert doc('#id_right option[selected]').attr('value') == ( str(self.files[1].id)) def test_file_chooser_selection_same_hash(self): """ In cases where multiple files are coalesced, the file selector may not have an actual entry for certain files. Instead, the entry with the identical hash should be selected. """ res = self.client.get(reverse('files.compare', args=(self.files[0].id, self.files[2].id))) doc = pq(res.content) assert doc('#id_left option[selected]').attr('value') == ( str(self.files[0].id)) assert doc('#id_right option[selected]').attr('value') == ( str(self.files[1].id))
{ "content_hash": "e4b50a98da1342d44a6cce660875d0fb", "timestamp": "", "source": "github", "line_count": 642, "max_line_length": 79, "avg_line_length": 37.61993769470405, "alnum_prop": 0.6006955945677377, "repo_name": "mstriemer/olympia", "id": "428a7c97aba5c276004e5635aaa2936aa7a4d250", "size": "24179", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/olympia/files/tests/test_views.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "808125" }, { "name": "HTML", "bytes": "729004" }, { "name": "JavaScript", "bytes": "1325833" }, { "name": "Makefile", "bytes": "7671" }, { "name": "PLSQL", "bytes": "74" }, { "name": "Python", "bytes": "4379805" }, { "name": "Shell", "bytes": "9699" }, { "name": "Smarty", "bytes": "1930" } ], "symlink_target": "" }
'use strict'; const dns = require('dns'); const kerberos = require('../kerberos'); class MongoAuthProcess { constructor(host, port, serviceName, options) { options = options || {}; this.host = host; this.port = port; // Set up service name this.serviceName = serviceName || options.gssapiServiceName || 'mongodb'; // Options this.canonicalizeHostName = typeof options.gssapiCanonicalizeHostName === 'boolean' ? options.gssapiCanonicalizeHostName : false; // Set up first transition this._transition = firstTransition(this); // Number of retries this.retries = 10; } init(username, password, callback) { const self = this; this.username = username; this.password = password; // Canonicialize host name if needed function performGssapiCanonicalizeHostName(canonicalizeHostName, host, callback) { if (!canonicalizeHostName) return callback(); // Attempt to resolve the host name dns.resolveCname(host, (err, r) => { if (err) return callback(err); // Get the first resolve host id if (Array.isArray(r) && r.length > 0) { self.host = r[0]; } callback(); }); } // Canonicialize host name if needed performGssapiCanonicalizeHostName(this.canonicalizeHostName, this.host, err => { if (err) return callback(err); const initOptions = {}; if (password != null) { Object.assign(initOptions, { user: username, password }); } const service = process.platform === 'win32' ? `${this.serviceName}/${this.host}` : `${this.serviceName}@${this.host}`; kerberos.initializeClient(service, initOptions, (err, client) => { if (err) return callback(err, null); self.client = client; callback(null, client); }); }); } transition(payload, callback) { if (this._transition == null) { return callback(new Error('Transition finished')); } this._transition(payload, callback); } } function firstTransition(auth) { return (payload, callback) => { auth.client.step('', (err, response) => { if (err) return callback(err); // Set up the next step auth._transition = secondTransition(auth); // Return the payload callback(null, response); }); }; } function secondTransition(auth) { return (payload, callback) => { auth.client.step(payload, (err, response) => { if (err && auth.retries === 0) return callback(err); // Attempt to re-establish a context if (err) { // Adjust the number of retries auth.retries = auth.retries - 1; // Call same step again return auth.transition(payload, callback); } // Set up the next step auth._transition = thirdTransition(auth); // Return the payload callback(null, response || ''); }); }; } function thirdTransition(auth) { return (payload, callback) => { // GSS Client Unwrap auth.client.unwrap(payload, (err, response) => { if (err) return callback(err, false); // Wrap the response auth.client.wrap(response, { user: auth.username }, (err, wrapped) => { if (err) return callback(err, false); // Set up the next step auth._transition = fourthTransition(auth); // Return the payload callback(null, wrapped); }); }); }; } function fourthTransition(auth) { return (payload, callback) => { // Set the transition to null auth._transition = null; // Callback with valid authentication callback(null, true); }; } // Set the process module.exports = { MongoAuthProcess };
{ "content_hash": "e7fd47564a08b23f7ae0722780c7d0d8", "timestamp": "", "source": "github", "line_count": 151, "max_line_length": 86, "avg_line_length": 24.7682119205298, "alnum_prop": 0.6045454545454545, "repo_name": "christkv/kerberos", "id": "ff14b9eedc9e1956c76dcfd2ca41fdfcc39e0734", "size": "3740", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/auth_processes/mongodb.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "60819" }, { "name": "C++", "bytes": "107028" }, { "name": "JavaScript", "bytes": "31237" }, { "name": "Python", "bytes": "1449" } ], "symlink_target": "" }
package com.rsi.cita; import com.rsi.gems.bbb.run.Methods; import com.rsi.gems.bbb.run.Ajax; import com.rsi.gems.bbb.run.B3Req; import com.rsi.gems.run.Page; import com.rsi.gems.run.Req; import com.rsi.gems.run.App; import com.rsi.gems.utl.CU; import org.json.JSONArray; import org.json.JSONObject; import com.rsi.act.ACT; import com.rsi.act.Item; import javax.servlet.http.HttpServletResponse; import com.google.appengine.api.datastore.Text; import java.util.HashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.rsi.cita.gdo.GdoCitaData; public class CitaMethods extends Methods { HashMap<String,JSONObject> oAuthTab = new HashMap<String,JSONObject>(); public static void log(String sMsg) {System.out.println(sMsg);} // TODO: token check. private boolean checkAuth(B3Req oR,Ajax oAjax,JSONObject oExec) throws Exception { JSONObject oJO = oExec.getJSONObject("auth"); String sKeyName = "*/"+oJO.getString("cust")+"/"+oJO.getString("user"); log(""+sKeyName+" check"); if (oAuthTab.containsKey(sKeyName)) return true; ACT.Status oS = oR.getACT().viewItemByKey(GdoCitaData.class,sKeyName); if (!oS.isGOOD()) { log(""+sKeyName+" not found"); JSONObject oRet = new JSONObject(); oRet.put("STATUS","AUTH-ERR"); oRet.put("CODE","not-in-auth-table"); oAjax.addBlock("RESULT",oRet); return false; } GdoCitaData oGWD = (GdoCitaData)oS.oItem; String sDF = ""+oGWD.getDataFld().getValue(); JSONObject oProps = new JSONObject(); if (sDF.startsWith("{")) oProps = new JSONObject(sDF); //log(""+sKeyName+" props "+oProps); oAuthTab.put(sKeyName,oProps); return true; } private JSONObject getProfile(B3Req oR,JSONObject oExec) throws Exception { JSONObject oJO = oExec.getJSONObject("auth"); String sKeyName = "*/"+oJO.getString("cust")+"/"+oJO.getString("user"); JSONObject oProps = oAuthTab.get(sKeyName); return oProps; } private boolean isRole(B3Req oR,JSONObject oExec,String sRole) throws Exception { JSONObject oProps = getProfile(oR,oExec); if (oProps == null) return false; String sAuth = oProps.optString("role"); if (sAuth == null) return false; //log("isAdmin "+sAuth+" "+sKeyName); if (sAuth.indexOf(sRole) >= 0) return true; return false; } B3Req insertOriginHeader(Req oR) throws Exception { HttpServletResponse oSrvRes = (HttpServletResponse)oR.getRes(); oSrvRes.setHeader("Access-Control-Allow-Origin","*"); return (B3Req)oR; } private boolean validatePassword(B3Req oR,JSONObject oUser,String sPassword) throws Exception { String sStoredPassword = oUser.getString("password"); Matcher oM = Pattern.compile("[a-zA-Z]").matcher(""); if (oM.reset(sStoredPassword).find()) { // new password //log("New password mode:"+sStoredPassword); if (sPassword.equals(sStoredPassword)) { oUser.put("password",encryptCitaPassword(oR,sPassword,null)); return true; } return false; } // encrypted password String sES = encryptCitaPassword(oR,sPassword,null); //log("Compare:"+sStoredPassword+" "+sES); return sES.equals(sStoredPassword); } private boolean performLogin(B3Req oR,Ajax oAjax,JSONObject oExec) throws Exception { JSONObject oJO = oExec.getJSONObject("auth"); JSONObject[] oObjs = validateUserPassword(oR,oAjax,oJO,oJO.getString("user"),oJO.getString("password"),true); if (oObjs == null) return false; JSONObject oUser = oObjs[0]; JSONObject oRet = oObjs[1]; oRet.put("user",oJO.getString("user")); // check for double login requirement String sDbl = oUser.optString("double"); if ("true".equals(sDbl)) { JSONObject[] oObjs2 = validateUserPassword(oR,oAjax,oJO,oJO.getString("user2"),oJO.getString("password2"),false); if (oObjs2 == null) return false; oRet.put("user2",oJO.getString("user2")); } else { if (oJO.optString("user2",null) != null) oRet.put("user2",oJO.getString("user2")); } //log("isAdmin "+sAuth+" "+sKeyName); String sToken = oUser.getString("token"); oRet.put("STATUS","OK"); oRet.put("token",sToken); addProfile(oRet,oUser); oAjax.addBlock("RESULT",oRet); returnAppDataStat(oR,oJO,oRet); return true; } private JSONObject[] validateUserPassword(B3Req oR,Ajax oAjax,JSONObject oJO,String sUser,String sPassword,boolean bPrimary) throws Exception { String sKeyName = "*/"+oJO.getString("cust")+"/"+sUser; //log("KeyName:"+sKeyName); ACT.Status oS = oR.getACT().viewItemByKey(GdoCitaData.class,sKeyName); JSONObject oRet = new JSONObject(); if (!oS.isGOOD()) { oRet.put("STATUS","AUTH-ERR"); oRet.put("CODE","not-in-auth-table primary="+bPrimary); oAjax.addBlock("RESULT",oRet); return null; } oS = oR.getACT().readItemForUpdate(GdoCitaData.class,oS.oItem.getGekID()); GdoCitaData oGWD = (GdoCitaData)oS.oItem; String sDF = ""+oGWD.getDataFld().getValue(); if (!sDF.startsWith("{")) { oRet.put("STATUS","AUTH-ERR"); oRet.put("CODE","non-JSON user data primary="+bPrimary); oAjax.addBlock("RESULT",oRet); return null; } JSONObject oUser = new JSONObject(sDF); String sOldPassword = oUser.getString("password"); if (!validatePassword(oR,oUser,sPassword)) { oRet.put("STATUS","AUTH-ERR"); oRet.put("CODE","mismatches-password-value primary="+bPrimary); oAjax.addBlock("RESULT",oRet); return null; } if (bPrimary) { String sToken = encryptCitaPassword(oR,sKeyName+System.nanoTime(),null); oUser.put("token",sToken); } if (bPrimary || (!sOldPassword.equals(oUser.getString(("password"))))) { oGWD.setDataFld(new Text(""+oUser)); oS = oR.getACT().updateItem(oGWD,oGWD.getGekRawUTS()); } return new JSONObject[]{oUser,oRet}; } private boolean performChangePassword(B3Req oR,Ajax oAjax,JSONObject oExec) throws Exception { JSONObject oJO = oExec.getJSONObject("auth"); String sKeyName = "*/"+oJO.getString("cust")+"/"+oJO.getString("user"); log("ChangePassword KeyName:"+sKeyName); ACT.Status oS = oR.getACT().viewItemByKey(GdoCitaData.class,sKeyName); JSONObject oRet = new JSONObject(); if (!oS.isGOOD()) { oRet.put("STATUS","AUTH-ERR"); oRet.put("CODE","not-in-auth-table"); oAjax.addBlock("RESULT",oRet); return false; } oS = oR.getACT().readItemForUpdate(GdoCitaData.class,oS.oItem.getGekID()); GdoCitaData oGWD = (GdoCitaData)oS.oItem; String sDF = ""+oGWD.getDataFld().getValue(); if (!sDF.startsWith("{")) { oRet.put("STATUS","AUTH-ERR"); oRet.put("CODE","non-JSON user data"); oAjax.addBlock("RESULT",oRet); return false; } JSONObject oUser = new JSONObject(sDF); String sPassword = ""+oJO.getString("password"); if (!validatePassword(oR,oUser,sPassword)) { oRet.put("STATUS","AUTH-ERR"); oRet.put("CODE","mismatches-stored-password-value"); oAjax.addBlock("RESULT",oRet); return false; } JSONObject oPL = oExec.getJSONObject("payload"); String sNewPassword = oPL.getString("NewPassword"); String sES = encryptCitaPassword(oR,sNewPassword,null); oUser.put("password",sES); oGWD.setDataFld(new Text(""+oUser)); oS = oR.getACT().updateItem(oGWD,oGWD.getGekRawUTS()); oRet.put("STATUS","OK"); addProfile(oRet,oUser); oAjax.addBlock("RESULT",oRet); return true; } private void addProfile(JSONObject oRet,JSONObject oUser) throws Exception { JSONObject oProf = new JSONObject(""+oUser); oProf.remove("token"); oProf.remove("password"); oRet.put("PROFILE",oProf); } private boolean performValidateToken(B3Req oR,Ajax oAjax,JSONObject oExec) throws Exception { JSONObject oJO = oExec.getJSONObject("auth"); String sKeyName = "*/"+oJO.getString("cust")+"/"+oJO.getString("user"); log("KeyName:"+sKeyName); ACT.Status oS = oR.getACT().viewItemByKey(GdoCitaData.class,sKeyName); JSONObject oRet = new JSONObject(); if (!oS.isGOOD()) { oRet.put("STATUS","AUTH-ERR"); oRet.put("CODE","not-in-auth-table"); oAjax.addBlock("RESULT",oRet); return false; } GdoCitaData oGWD = (GdoCitaData)oS.oItem; JSONObject oRec = oGWD.populateJSON(); log("TV.Record:"+oRec); log("TV.DataFld:"+oGWD.getDataFld().getValue()); String sDF = ""+oGWD.getDataFld().getValue(); JSONObject oUser = new JSONObject(); if (sDF.startsWith("{")) { oUser = new JSONObject(sDF); String sToken = oUser.optString("token","*****"); if (!sToken.equals(oJO.optString("token"))) { oRet.put("STATUS","AUTH-ERR"); oRet.put("CODE","token-has-expired"); oAjax.addBlock("RESULT",oRet); return false; } } else { oRet.put("STATUS","AUTH-ERR"); oRet.put("CODE","token-does-not-exist"); oAjax.addBlock("RESULT",oRet); return false; } addProfile(oRet,oUser); oRet.put("STATUS","OK"); oAjax.addBlock("RESULT",oRet); returnAppDataStat(oR,oJO,oRet); return true; } private void returnAppDataStat(B3Req oR,JSONObject oJO,JSONObject oRet) throws Exception { String sKeyName = ""+oJO.getString("cust")+"/%"; JSONObject oDS = findCitaData(oR,oJO,false,sKeyName); oRet.put("DataStat",oDS); } private String encryptCitaPassword(Req oR,String sStr,String sApp) { App oApp = oR.getApp(); if (sApp != null) { oApp = oR.getCust().findApp(sApp); log("Lost "+sApp); oApp = oR.getApp(); } String sSrc = sStr+oApp.getParm("PasswordObfuscator")+sStr; String sResult = CU.getAdlerString(sSrc); //System.out.println("Encrypter:"+sSrc+" result="+sResult); return sResult; } public String ajaxLogin(Req oRP,Page oP,Ajax oAjax,JSONObject oExec) throws Exception { try { B3Req oR = insertOriginHeader(oRP); log("ExecLogin:"+oExec); if (!performLogin(oR,oAjax,oExec)) return oAjax.setFail("no-auth"); return oAjax.setGood("login OK"); } catch (Exception e) { return trap(e,oAjax); } } public String ajaxValidateToken(Req oRP,Page oP,Ajax oAjax,JSONObject oExec) throws Exception { try { B3Req oR = insertOriginHeader(oRP); log("ExecValidateToken:"+oExec); if (!performValidateToken(oR,oAjax,oExec)) return oAjax.setFail("no-auth"); return oAjax.setGood("validate OK"); } catch (Exception e) { return trap(e,oAjax); } } public String ajaxChangePassword(Req oRP,Page oP,Ajax oAjax,JSONObject oExec) throws Exception { try { B3Req oR = insertOriginHeader(oRP); log("ExecLogin:"+oExec); if (!performChangePassword(oR,oAjax,oExec)) return oAjax.setFail("no-auth"); return oAjax.setGood("login OK"); } catch (Exception e) { return trap(e,oAjax); } } public String ajaxSendCitaData(Req oRP,Page oP,Ajax oAjax,JSONObject oExec) throws Exception { try { B3Req oR = insertOriginHeader(oRP); if (!checkAuth(oR,oAjax,oExec)) return oAjax.setFail("no-auth"); JSONObject oProf = getProfile(oR,oExec); String sSandbox = oProf.optString("sandbox"); //thwart potential hackers if ("true".equals(sSandbox)) { log("sandbox write rejected"); return oAjax.setFail("Attempt to write in sandbox mode thwarted"); } JSONObject oJO = oExec.getJSONObject("payload"); String sKeyName = oJO.getString("KeyName"); String sValErr = validateKey(oR,oAjax,oExec,sKeyName); if (sValErr != null) return sValErr; if (sKeyName.startsWith("*/")) oAuthTab = new HashMap<String,JSONObject>(); JSONObject oRet = makeCitaData(oR,oJO); oAjax.addBlock("RESULT",oRet); String sStr = oAjax.setGood("Cita record"); if ("WAKS-call".equals(oAjax.getInput().getString("AjaxID"))) { sStr += "\r\n"+"**GIO.EOF.MARKER**\r\n"; // add EOF marker } //log("ajaxSendCitaData "+sStr); log("ajaxSendCitaData successful "+sKeyName); return sStr; } catch (Exception e) { return trap(e,oAjax); } } String trap(Exception e,Ajax oAjax) throws Exception { JSONObject oRet = new JSONObject(); oRet.put("STATUS","TRAP"); oRet.put("CODE",""+e); e.printStackTrace(); oAjax.addBlock("RESULT",oRet); return oAjax.setFail("exception"); } private String validateKey(B3Req oR,Ajax oAjax,JSONObject oExec,String sKeyName) throws Exception { if (sKeyName.startsWith("*/")) { if (!isRole(oR,oExec,"admin")) return oAjax.setFail("KeyType requires admin role for find"); } if (sKeyName.startsWith("./")) { //thwart access to SuperUser if (!isRole(oR,oExec,"admin")) return oAjax.setFail("KeyType invalid format"); } return null; } public String ajaxFindCitaData(Req oRP,Page oP,Ajax oAjax,JSONObject oExec) throws Exception { try { B3Req oR = insertOriginHeader(oRP); log("ExecFind:"+oExec); if (!checkAuth(oR,oAjax,oExec)) return oAjax.setFail("no-auth"); JSONObject oJO = oExec.getJSONObject("payload"); String sKeyName = oJO.getString("KeyName"); String sValErr = validateKey(oR,oAjax,oExec,sKeyName); if (sValErr != null) return sValErr; JSONObject oRet = findCitaData(oR,oJO,false,sKeyName); oAjax.addBlock("RESULT",oRet); return oAjax.setGood("Cita record"); } catch (Exception e) { return trap(e,oAjax); } } public String ajaxFindUserData(Req oRP,Page oP,Ajax oAjax,JSONObject oExec) throws Exception { try { B3Req oR = insertOriginHeader(oRP); if (!checkAuth(oR,oAjax,oExec)) return oAjax.setFail("no-auth"); if (!isRole(oR,oExec,"admin")) return oAjax.setFail("User access requires admin role"); log("ExecFind:"+oExec); //JSONObject oJO0 = oExec.getJSONObject("payload"); JSONObject oAuth = oExec.getJSONObject("auth"); String sCust = oAuth.getString("cust"); JSONObject oJO = new JSONObject(); oJO.put("KeyName","\\*/"+sCust+"/%"); String sKeyName = oJO.getString("KeyName"); JSONObject oRet = findCitaData(oR,oJO,true,sKeyName); oAjax.addBlock("RESULT",oRet); return oAjax.setGood("Cita record"); } catch (Exception e) { return trap(e,oAjax); } } public String ajaxSendReminder(Req oRP,Page oP,Ajax oAjax,JSONObject oExec) throws Exception { try { B3Req oR = insertOriginHeader(oRP); /*if (!checkAuth(oR,oAjax,oExec)) return oAjax.setFail("no-auth"); if (!isAdmin(oR,oExec)) return oAjax.setFail("User access requires admin role"); log("ExecFind:"+oExec); //JSONObject oJO0 = oExec.getJSONObject("payload"); JSONObject oJO = new JSONObject(); oJO.put("KeyName","\\ * /mems/%"); */ sendReminder(oR); JSONObject oRet = new JSONObject(); oRet.put("STATUS","OK"); oRet.put("CODE","email sent to xxx"); oAjax.addBlock("RESULT",oRet); return oAjax.setGood("Reminder Sent"); } catch (Exception e) { return trap(e,oAjax); } } public String ajaxDeleteKey(Req oRP,Page oP,Ajax oAjax,JSONObject oExec) throws Exception { try { B3Req oR = insertOriginHeader(oRP); if (!checkAuth(oR,oAjax,oExec)) return oAjax.setFail("no-auth"); if (!isRole(oR,oExec,"admin") && !isRole(oR,oExec,"mgr")) return oAjax.setFail("DeleteKey requires admin/mgr role"); JSONObject oPL = oExec.getJSONObject("payload"); int nGekID = Integer.parseInt(oPL.getString("GekID")); log("DeleteKey:"+oExec+" GekID="+nGekID); JSONObject oRet = performDeleteKey(oR,nGekID); oAjax.addBlock("RESULT",oRet); return oAjax.setGood("Removal executed"); } catch (Exception e) { return trap(e,oAjax); } } JSONObject performDeleteKey(B3Req oR,int nGekID) throws Exception { JSONObject oRet = new JSONObject(); ACT.Status oS = oR.getACT().removeItem(GdoCitaData.class,nGekID); if (oS.isGOOD()) { oRet.put("STATUS","OK"); oRet.put("CODE","Item removed"); } else { oRet.put("STATUS","NAK"); oRet.put("CODE","removal failed"); } return oRet; } public String ajaxReadCitaData(Req oRP,Page oP,Ajax oAjax,JSONObject oExec) throws Exception { try { B3Req oR = insertOriginHeader(oRP); if (!checkAuth(oR,oAjax,oExec)) return oAjax.setFail("no-auth"); log("ExecRead:"+oExec); JSONObject oJO = oExec.getJSONObject("payload"); String sKeyName = oJO.getString("KeyName"); String sValErr = validateKey(oR,oAjax,oExec,sKeyName); if (sValErr != null) return sValErr; JSONObject oRet = readCitaData(oR,oJO); oAjax.addBlock("RESULT",oRet); String sStr = oAjax.setGood("Cita record"); if ("GIO".equals(oJO.optString("flag-eof"))) { sStr += "\r\n**GIO.EOF.MARKER**\r\n"; log("Added GIO flag"); } return sStr; } catch (Exception e) { return trap(e,oAjax); } } JSONObject readCitaData(B3Req oR,JSONObject oJO) throws Exception { String sKeyName = oJO.getString("KeyName"); log("getCitaData key="+sKeyName); JSONObject oRet = new JSONObject(); ACT.Status oS = oR.getACT().viewItemByKey(GdoCitaData.class,sKeyName); log("ReadStatus for "+sKeyName+" "+oS); if (oS.isGOOD()) { oS = oR.getACT().viewItem(GdoCitaData.class,oS.oItem.getGekID()); GdoCitaData oGWD = (GdoCitaData)oS.oItem; JSONObject oRec = oGWD.populateJSON(); oRet.put("STATUS","OK"); oRet.put("CODE","found"); oRet.put("RECORD",oRec); oRet.put("UpdateTS",""+oS.oItem.getGekUpdateTS().getTime()); } else { oRet.put("STATUS","NAK"); oRet.put("CODE","not-found"); } return oRet; } JSONObject findCitaData(B3Req oR,JSONObject oJO,boolean bData,String sKeyName) throws Exception { log("getCitaData "+sKeyName); JSONObject oRet = new JSONObject(); String[][] sLikes = new String[][]{new String[]{"KeyName",sKeyName}}; ACT.Status oS = oR.getACT().viewSelectedItems(GdoCitaData.class,sLikes); log("ReadStatus for find key="+sKeyName+" good="+oS.isGOOD()); if (oS.isGOOD()) { JSONArray oJA = new JSONArray(); log("Find returned "+oS.oItems.length+" item(s)"); for(Item oItem:oS.oItems) { GdoCitaData oGWD = (GdoCitaData)oItem; JSONObject oOut = new JSONObject(); addStr(oOut,"GekID",""+oGWD.getGekID()); addStr(oOut,"KeyName",oGWD.getKeyName()); addStr(oOut,"CreateTS",""+oItem.getGekCreateTS().getTime()); addStr(oOut,"UpdateTS",""+oItem.getGekUpdateTS().getTime()); if (bData) addStr(oOut,"DataFld",""+""+oGWD.getDataFld().getValue()); oJA.put(oOut); } oRet.put("STATUS","OK"); oRet.put("CODE","found"); oRet.put("RECORD",oJA); } else { oRet.put("STATUS","NAK"); oRet.put("CODE","find faild"); } return oRet; } JSONObject makeCitaData(B3Req oR,JSONObject oJO) throws Exception { String sKeyName = oJO.getString("KeyName"); log("makeCitaData "+sKeyName); JSONObject oRet = new JSONObject(); GdoCitaData oGWD = new GdoCitaData().populateItem(oJO); log("madeCitaData "+oGWD); ACT.Status oS = oR.getACT().viewItemByKey(GdoCitaData.class,sKeyName); log("ReadStatus for "+sKeyName+" "+oS); String sStat = "?"; if (!oS.isGOOD()) { oS = oR.getACT().createRecord(oGWD); sStat = "new"; } else { oS = oR.getACT().readItemForUpdate(GdoCitaData.class,oS.oItem.getGekID()); GdoCitaData oOldGWD = (GdoCitaData)oS.oItem; oOldGWD.setDataFld(oGWD.getDataFld()); oS = oR.getACT().updateItem(oOldGWD,oOldGWD.getGekRawUTS()); oGWD.setGekID(oOldGWD.getGekID()); sStat = "updated"; } JSONObject oRec = oGWD.populateJSON(); oRet.put("STATUS","OK"); oRet.put("CODE",""+sStat); oRet.put("RECORD",oRec); return oRet; } void addStr(JSONObject oOut,String sFldName,String sValue) throws Exception { if (sValue == null) return; oOut.put(sFldName,sValue); } void sendReminder(B3Req oR) throws Exception { String sHTML = "<html>" + "<body>" + "<pre>" + " Your temporary password is: <b>{{TEMP}}</b>" + " Use this value to login to the system." + " The system will ask you to set up a new password." + "</pre>" + "Thanks,<br>" + "SysAdmin" + "</body>" + "<html>"; String sCRLF = "\r\n"; String sTEXT = " Your temporary password is: {{TEMP}}"+sCRLF + " Use this value to login to the system."+sCRLF + " The system will ask you to set up a new password."+sCRLF + ""+sCRLF + "Thanks,"+sCRLF + "SysAdmin"+sCRLF; basicSendMail(oR,"public@rexcel.com","Your password",sHTML,sTEXT); } // --------------------------------------------------------------- // Note: These are WAKS interfaces. WAKS calls must provide the SuperUser ID & password. // // We also allow a leading $ to indicate we are reading writing User records. // // Since the SuperUser ID is created under the Boot application we have to supply // this to cause the encryptCitaPassword to use the write parm string. // public String ajaxWaksFindCitaData(Req oRP,Page oP,Ajax oAjax,JSONObject oExec) throws Exception { try { B3Req oR = insertOriginHeader(oRP); log("ExecFind:"+oExec); String sAuth = validateSuperAdmin(oR,oAjax,oExec,"Boot"); if (sAuth != null) log("Failed:"+sAuth); if (sAuth != null) return sAuth; JSONObject oJO = oExec.getJSONObject("payload"); String sKeyName = oJO.getString("KeyName"); if (sKeyName.startsWith("$/")) sKeyName = "\\*"+sKeyName.substring(1); JSONObject oRet = findCitaData(oR,oJO,false,sKeyName); oAjax.addBlock("RESULT",oRet); return oAjax.setGood("Cita record"); } catch (Exception e) { return trap(e,oAjax); } } public String ajaxWaksReadCitaData(Req oRP,Page oP,Ajax oAjax,JSONObject oExec) throws Exception { try { B3Req oR = insertOriginHeader(oRP); String sAuth = validateSuperAdmin(oR,oAjax,oExec,"Boot"); if (sAuth != null) return sAuth; log("ExecRead:"+oExec); JSONObject oJO = oExec.getJSONObject("payload"); String sKeyName = oJO.getString("KeyName"); if (sKeyName.startsWith("$/")) sKeyName = "*"+sKeyName.substring(1); JSONObject oRet = readCitaData(oR,oJO); oAjax.addBlock("RESULT",oRet); String sStr = oAjax.setGood("Cita record"); if ("GIO".equals(oJO.optString("flag-eof"))) { sStr += "\r\n**GIO.EOF.MARKER**\r\n"; log("Added GIO flag"); } return sStr; } catch (Exception e) { return trap(e,oAjax); } } public String ajaxWaksSendCitaData(Req oRP,Page oP,Ajax oAjax,JSONObject oExec) throws Exception { try { B3Req oR = insertOriginHeader(oRP); String sAuth = validateSuperAdmin(oR,oAjax,oExec,"Boot"); if (sAuth != null) return sAuth; JSONObject oJO = oExec.getJSONObject("payload"); String sKeyName = oJO.getString("KeyName"); if (sKeyName.startsWith("$/")) sKeyName = "*"+sKeyName.substring(1); JSONObject oRet = makeCitaData(oR,oJO); oAjax.addBlock("RESULT",oRet); String sStr = oAjax.setGood("Cita record"); if ("WAKS-call".equals(oAjax.getInput().getString("AjaxID"))) { sStr += "\r\n"+"**GIO.EOF.MARKER**\r\n"; // add EOF marker } //log("ajaxSendCitaData "+sStr); log("ajaxSendCitaData successful "+sKeyName); return sStr; } catch (Exception e) { return trap(e,oAjax); } } // --------------------------------------------------------------- // Note: These are accesses with the 'boot' application so that B3Req is not instantiated // because at this point it would fail. // // These are special methods to test for and construct a Datastore. // public String ajaxValidateStore(Req oR,Page oP,Ajax oAjax,JSONObject oExec) throws Exception { try { //B3Req oR = insertOriginHeader(oRP); log("Exec validateStore:"+oExec); //if (!performLogin(oR,oAjax,oExec)) return oAjax.setFail("no-auth"); ACT oACT = ACT.getACT(); ACT.Status oS = oACT.viewControlRecord(); if (oS.isGOOD()) { return oAjax.setGood("validateStore primed"); } else { return oAjax.setFail("not-primed"); } } catch (Exception e) { e.printStackTrace(); return trap(e,oAjax); } } public String ajaxPrimeStore(Req oR,Page oP,Ajax oAjax,JSONObject oExec) throws Exception { try { log("Exec PrimeStore:"+oExec); ACT oACT = ACT.getACT(); oACT.formatControlRecord(); App oApp = oR.getCust().findApp("Bbb"); String sStrGEK = oApp.getParm("ActItems") + ";com.rsi.cita.gdo.GdoCitaData"; String[] sGEKs = sStrGEK.split(";"); oACT.assignControlRecordGEKs(sGEKs); JSONObject oAuth = oExec.getJSONObject("auth"); String sKeyName = "././"+oAuth.getString("user"); JSONObject oUser = new JSONObject(); JSONObject oProp = new JSONObject(); String sES = encryptCitaPassword(oR,oAuth.getString("user")+"/"+oAuth.get("password"),null); oProp.put("password",sES); oUser.put("DataFld",""+oProp); oUser.put("KeyName",sKeyName); GdoCitaData oGWD = new GdoCitaData().populateItem(oUser); ACT.Status oS = oACT.createRecord(oGWD); if (oS.isGOOD()) { return oAjax.setGood("primeStore OK"); } else { return oAjax.setFail("primeStore failed "+oS); } } catch (Exception e) { return trap(e,oAjax); } } public String ajaxSuperLogin(Req oR,Page oP,Ajax oAjax,JSONObject oExec) throws Exception { try { log("Exec superLogin:"+oExec); String sOK = validateSuperAdmin(oR,oAjax,oExec,null); if (sOK != null) return sOK; } catch (Exception e) { return trap(e,oAjax); } return oAjax.setGood("superLogin primed"); } public String ajaxAddAdminUser(Req oR,Page oP,Ajax oAjax,JSONObject oExec) throws Exception { try { log("Exec addAdminUser:"+oExec); String sOK = validateSuperAdmin(oR,oAjax,oExec,null); if (sOK != null) return sOK; ACT oACT = ACT.getACT(); JSONObject oPL = oExec.getJSONObject("payload"); String sPassword = oPL.getString("NewPassword"); String sCust = oPL.getString("AppID"); String sUser = oPL.getString("User"); String sKeyName = "*/"+sCust+"/"+sUser; String[][] sLikes = new String[][]{new String[]{"KeyName","\\"+sKeyName}}; ACT.Status oS = oACT.viewSelectedItems(GdoCitaData.class,sLikes); log("ReadStatus for find key="+sKeyName+" good="+oS.isGOOD()); if (oS.isGOOD() && (oS.oItems != null) && (oS.oItems.length > 0)) { return oAjax.setFail("App="+sCust+" user="+sUser+" already configured"); } else { JSONObject oUser = new JSONObject(); JSONObject oProp = new JSONObject(); oProp.put("password",sPassword); oProp.put("role","admin"); oUser.put("DataFld",""+oProp); oUser.put("KeyName",sKeyName); GdoCitaData oGWD = new GdoCitaData().populateItem(oUser); oS = oACT.createRecord(oGWD); if (oS.isGOOD()) { return oAjax.setGood("AddAdminUser OK"); } else { return oAjax.setFail("AddAdminUser failed "+oS); } } } catch (Exception e) { return trap(e,oAjax); } } public String ajaxListApps(Req oR,Page oP,Ajax oAjax,JSONObject oExec) throws Exception { try { log("Exec addAdminUser:"+oExec); String sOK = validateSuperAdmin(oR,oAjax,oExec,null); if (sOK != null) return sOK; ACT oACT = ACT.getACT(); String sKeyName = "*/%"; String[][] sLikes = new String[][]{new String[]{"KeyName","\\"+sKeyName}}; ACT.Status oS = oACT.viewSelectedItems(GdoCitaData.class,sLikes); log("ReadStatus for find key="+sKeyName+" good="+oS.isGOOD()); if (oS.isGOOD() && (oS.oItems != null) && (oS.oItems.length > 0)) { JSONObject oRet = new JSONObject(); JSONArray oJA = new JSONArray(); log("Find returned "+oS.oItems.length+" item(s)"); for(Item oItem:oS.oItems) { GdoCitaData oGWD = (GdoCitaData)oItem; JSONObject oOut = new JSONObject(); String sKey = oGWD.getKeyName(); String sDF = ""+oGWD.getDataFld().getValue(); JSONObject oProp = new JSONObject(sDF); String sRole = oProp.optString("role",null); if ((sRole != null) && (sRole.indexOf("admin") >= 0)) { String[] sParts = sKey.split("/"); addStr(oOut,"app",sParts[1]); addStr(oOut,"user",sParts[2]); oJA.put(oOut); } } oRet.put("STATUS","OK"); oRet.put("CODE","found"); oRet.put("RECORD",oJA); oAjax.addBlock("RESULT",oRet); return oAjax.setGood("apps returned"); } else { return oAjax.setFail("no apps configured"); } } catch (Exception e) { return trap(e,oAjax); } } private String validateSuperAdmin(Req oR,Ajax oAjax,JSONObject oExec,String sApp) throws Exception { ACT oACT = ACT.getACT(); JSONObject oAuth = oExec.getJSONObject("auth"); String sKeyName = "././"+oAuth.getString("user"); ACT.Status oS = oACT.viewItemByKey(GdoCitaData.class,sKeyName); if (oS.isGOOD()) { GdoCitaData oGWD = (GdoCitaData)oS.oItem; String sDF = ""+oGWD.getDataFld().getValue(); JSONObject oProps = new JSONObject(sDF); log("UserRecord:"+oProps); String sES0 = oProps.getString("password"); String sES1 = encryptCitaPassword(oR,oAuth.getString("user")+"/"+oAuth.get("password"),sApp); if (sES1.equals(sES0)) { log("UserRecord:"+oProps+" is good as superuser"); return null; // Its good } else { String sPassword = ""+oAuth.get("password"); //allow change if SuperUser token known and special overide format if (sPassword.startsWith("=") || sPassword.startsWith(".") ) { String[] sParts = sPassword.substring(1).split("/"); if (sParts[0].equals(sES0) && sParts.length == 2) { sES1 = encryptCitaPassword(oR,oAuth.getString("user")+"/"+sParts[1],sApp); oProps.put("password",sES1); oGWD.setDataFld(new Text(""+oProps)); oS = oACT.updateItem(oGWD,oGWD.getGekRawUTS()); log("SuperUser password changed to "+sParts[1]+" "+sES1); return null; // Its good } } log("SuperUser credentials bad expect="+sES0+" have="+sES1); return oAjax.setFail("SuperUser credentials bad"); } } else { return oAjax.setFail("Lost SuperUser record"); } } }
{ "content_hash": "d8ebe4f98e419a459c350ec8cedc9a8f", "timestamp": "", "source": "github", "line_count": 817, "max_line_length": 145, "avg_line_length": 38.17992656058752, "alnum_prop": 0.6281537524444587, "repo_name": "srp7474/tri", "id": "d6345e89948c89b07b83b0c778f3884aa87a238a", "size": "31193", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "java/CitaMethods.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "60549" }, { "name": "Java", "bytes": "31193" }, { "name": "JavaScript", "bytes": "579876" }, { "name": "Shell", "bytes": "12495" } ], "symlink_target": "" }
# angular-joyride A simple joyride directive for angular. This is inspired by [ng-joyride](https://github.com/abhikmitra/ng-joyride) and works very similarly but with less dependencies. The only dependency is [ngAnimate](https://docs.angularjs.org/api/ngAnimate), no jquery or any other libraries required. ## [Demo](http://ahmed-wagdi.github.io/angular-joyride) ## Key Features 1. **Minumum dependencies:** Only AngularJS and ngAnimate are required. 2. **Customizability:** The directive gives you the ability to customize the positioning, styling, HTML and even the animations of the joyride. 3. **Auto-adjusting positioning:** You choose where the joyride should be positioned, but in cases where the joyride might go offscreen the directive will adjust it's position to make sure it stays completely visible. 4. **Responsive Positioning:** For cases where the auto-adjusting position isn't enough, you can specify a certain breakpoint where you want to completely change the placement of the joyride to ensure it works on smaller screens. ## Installation Install with npm: ``` npm install angular-joyride ``` Install with bower: ``` bower install angular-joyride ``` Inject `angular-joyride` and `ngAnimate` into your angular module: ``` angular.module('MyApp', ['ngAnimate', 'angular-joyride']); ``` Add the `joyride` directive as an element: ``` <joyride></joyride> ``` ## Usage This directive relies on a service for handling the joyride content and configuration, so include the `joyrideService` in your controller: ```` app.controller('MainCtrl', function($scope, joyrideService) { var joyride = joyrideService; joyride.start = true; joyride.config = { overlay: false, onStepChange: function(){ // Code Here }, onStart: function(){ // Code Here }, onFinish: function(){ // Code Here }, steps : [ { title: "Title 2", content: '<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptatibus, quidem, quia mollitia harum tempora laudantium deserunt deleniti. Expedita, soluta, atque maxime minus commodi quaerat ipsum reiciendis veritatis eum laboriosam incidunt.</p><p>another example</p>' }, { type: 'element', selector: "#title", title: "Title 1", content: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptatibus, quidem, quia mollitia harum tempora laudantium deserunt deleniti. Expedita, soluta, atque maxime minus commodi quaerat ipsum reiciendis veritatis eum laboriosam incidunt.', placement: 'top' } ] }, }); ```` #### Starting the joyride The `start` property can be used to trigger the joyride, setting it to `true` starts the joyride and `false` will end it. ### Configuration - __steps -__ The steps to be used in the joyride, expects an array of objects. - __overlay -__ Display overlay, default is true. - __template -__ This can be used to add a custom template for the joyride, a path to an html file should be given. - __onStepChange -__ Callback for step change. - __onStart -__ Callback for joyride start. - __onFinish -__ Callback for joyride end. ## Joyride Steps The `steps` property accepts an array containing the steps of the joyride, each step should be an object with the following properties: | Property | Type | Description | :------------- |:------------- |:------------- | type | String | Type of step, default is "Regular" | title | String | Title of step | content | String | Step content, can incude html tags | selector | String | If type is set to "element" this is the selector used to find the element | placement | String | If type is set to "element" determines the placement of the container, default is "bottom" | appendToBody | boolean | If type is set to "element" setting to true appends the joyride to the body instead of the element the joyride is pointing to, default is false | scroll | boolean | If type is set to "element" can disable/enable scrolling to element, default is true | beforeStep | function | Function called before step transitions in, can pause joyride until some code executes #### Step Types There are 2 available types: * __Regular:__ The default type, appears as a regular pop-up. * __Element:__ Highlights a certain element in the DOM. Requires the `selector` property to work and can be positioned with the `placement` property with top, right, bottom or left. ### Before step callback This should be used if you want to pause between steps to execute some code first, for example opening a modal or going to a different page before going to the next step. If you use the `beforeStep` callback then the joyride will be paused, you have to let it know once you're done so that it can continue, you can do that by using the `resumeJoyride` function. In the example below the modal should be open in the second step but it should be closed in the first and third step: ```` joyride.config.steps = [ { title : 'Step 1', content: "<p>This step is on the main page with the modal closed.</p>", beforeStep: closeModal }, { type: 'element', selector: '.modal .button', title: "Step 2", content: "This step should wait for the modal to open first!", beforeStep: openModal, scroll: false }, { title : 'Step 3', content: "<p>Last step is on the main page with the modal closed.</p>", beforeStep: closeModal } ]; // Make sure to call resume to let the joyride know it should continue function openModal(){ modal.open.then(function(){ joyride.resumeJoyride(); }); } function closeModal(){ modal.close.then(function(){ joyride.resumeJoyride(); }); } ```` #### Multipage Joyride You can also use the `beforeStep` callback to navigate between different pages in between steps. Here's an example for `ui-router`, if you're using an older version of ui-router then you might need to use the $stateChange* events instead of $transitions: 1. In your controller use `beforeStep` to navigate to a different state: ```` joyride.config = { steps : [ { title: "Step 1", content: "<p>Welcome to the joyride demo!</p><p>This is a simple joyride directive built to have minimal dependencies.</p>" }, { title: "Step 2", content: "<p>Welcome to the joyride demo!</p><p>This is a simple joyride directive built to have minimal dependencies.</p>", beforeStep: toHome }, { title: "Step 3", content: "<p>Welcome to the joyride demo!</p><p>This is a simple joyride directive built to have minimal dependencies.</p>", beforeStep: toAbout } ] } function toHome(){ $state.go("home"); } function toAbout(){ $state.go("about"); } ```` 2. To resume the joyride we need to call `resumeJoyride` after the state changes and if no state change takes place at all: ```` app.run(function($transitions, joyrideService, $timeout) { /** After changing states call resumeJoyride * to un-pause. The $timeout just fixes an * animation issue if the next step is of * type "element" **/ $transitions.onFinish({ }, function(trans) { trans.promise.then(function(response){ $timeout(function(){ joyrideService.resumeJoyride(); }) }); }); /** Handles the case when you're beforeStep * function calls $state.go and tries to * go to the current state. **/ $transitions.onBefore({ }, function(trans) { trans.promise.then(null,function(response){ joyrideService.resumeJoyride(); }) }); }) ```` ### Responsive Positioning It's possible to switch the placement of a step based on the screen width by declaring a `responsive` property inside a step object: ```` { type: 'element', selector: '.button', title: "Step 2", content: "Lorem ipsum dolor sit amet, consectetur adipisicing elit.", placement: 'left', responsive: { breakpoint: 600, placement: 'top' } } ```` The `responsive` object takes 2 properties, the breakpoint where you want to change the placement (in pixels) and the new placement, if no placement is given then it will be set to bottom by default. This directive only supports the use of 1 breakpoint. ### Methods | Method | Description | :------------- |:------------- | next | Goes to the next step | prev | Goes to the previous step | goTo | Goes to a specific step, requires a number representing the index of the step __Usage:__ ```` $scope.customNext = function(){ joyride.next(); } $scope.go = function(index){ joyride.goTo(index) } ```` ## Animations This directive relies on `ngAnimate` and the [$animate](https://docs.angularjs.org/api/ng/service/$animate) service for handling animation classes. By default the joyride has simple fade in/out animations, but you can customize them by using the `.jr_start` class for start/end animations and the `.jr_transition` for step transition animations: ```` .jr_container{ transition: opacity 0.3s, transform 0.3s } //////// START/END ANIMATIONS .jr_container.jr_start-add { opacity: 0; } .jr_container.jr_start-add-active { opacity: 1; } .jr_container.jr_start-remove { opacity: 1; } .jr_container.jr_start-remove-active { opacity: 0; } //////////// STEP TRANSITION ANIMATIONS .jr_container.jr_transition{ opacity: 0; } .jr_container.jr_transition-add { opacity: 1; transform: translateY(0px); } .jr_container.jr_transition-add-active { opacity: 0; transform: translateY(-100px); } .jr_container.jr_transition-remove { opacity: 0; transform: translateY(-100px); } .jr_container.jr_transition-remove-active { opacity: 1; transform: translateY(0px); } ```` ### Custom Templates If you want to use your own template for the joyride then add the template in an html file then enter the path to that file in your controller similar to the following: ```` joyride.config.template = 'partials/myCustomTemplate.html' ```` Your template must contain a div with the class `jr_container`, i would recommend copying the html of the default template and editing it, you can find the html below: ```` <div class="jr_container" id="jr_step_{{joyride.current}}"> <div class="jr_step"> <h4 ng-if="joyride.config.steps[joyride.current].title" class="jr_title">{{joyride.config.steps[joyride.current].title}}</h4> <div ng-if="joyride.config.steps[joyride.current].content" class="jr_content" ng-bind-html="joyride.config.steps[joyride.current].content | jr_trust"></div> </div> <div class="jr_buttons"> <div class="jr_left_buttons"> <a class="jr_button jr_skip" ng-click="joyride.start = false">Skip</a> </div> <div class="jr_right_buttons"> <a class="jr_button jr_prev" ng-click="joyride.prev()" ng-class="{'disabled' : joyride.current === 0}">Prev</a> <a class="jr_button jr_next" ng-click="joyride.next()" ng-bind="(joyride.current == joyride.config.steps.length-1) ? 'Finish' : 'Next'"></a> </div> </div> </div> ```` ## License The MIT License (MIT) Copyright (c) 2016 Ahmed Wagdi 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.
{ "content_hash": "a466c44fb66e571ace9fb76ae339adab", "timestamp": "", "source": "github", "line_count": 324, "max_line_length": 460, "avg_line_length": 38.00308641975309, "alnum_prop": 0.6891902866888654, "repo_name": "kinnekcodebase/angular-joyride", "id": "e1ec3dd39e9049ad1b249760f6dea1cbae5f76a8", "size": "12313", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "5974" }, { "name": "JavaScript", "bytes": "17411" } ], "symlink_target": "" }